python-6-windows和linux中后台运行python代码

Python程序后台运行的五种方式

1 windows中后台运行python程序

1.1 启动bat弹出界面

(1)main.py

import time
while True:
    with open("log.txt",'a+',encoding="utf-8") as fw:
        fw.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"and 123\n")
    time.sleep(2)

(2)start_show.bat

python main.py

在这里插入图片描述bat文件必须放在main.py的同一目录下。
查看任务管理器
在这里插入图片描述

1.2 启动vbs后台运行

vbs文件必须放在main.py的同一目录下,且必须有.bat文件同在。VBS是微软公司可视化BASIC语言-脚本版,简写VBS,vbs是一种脚本语言,语言也类似于语言VB。目前,vbs文件可以在windows上直接打开。
(1)main.py

import time
while True:
    with open("log.txt",'a+',encoding="utf-8") as fw:
        fw.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"and 123\n")
    time.sleep(2)

(2)start_show.bat

python main.py

(3)start_hidden.vbs

Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c start_show.bat",0

在这里插入图片描述双击start_hidden.vbs
进程会增加一个python.exe进程,增加的python.exe进程为后台启动的,可以通过任务管理器查看。
在这里插入图片描述

1.3 杀死后台所有python进程

stop_all_python.bat
在其中添加如下内容

taskkill /im python.exe /f

双击运行即可

1.4 杀死当前的main.py

(1)windows下的:taskkill /im python.exe /f命令会将所有python解释器进程全部杀死。
(2)windows下的:taskkill /pid 1235404 /f命令会将进程编号为1235404的进程杀死。那么要做的就是找到main.py启动时的进程编号,然后在写入到名为stop_main.bat文件中,形如:

taskkill /pid 1235404 /f
del %0

(3)注意:
pid后面的进程号是python程序随机生成的,所有获取pid进程号的时候也必须用python程序自动获取。

del %0命令的作用是stop_main.bat文件运行结束后,删除stop_main.bat文件。目的是防止反复双击运行stop_main.bat文件,误删系统进程,导致系统崩溃。
(4)main.py

# ========增加代码--开始========
import os
def produce_stop_bat(pid, tmpfile="stop_xxx.bat"):
    stop_cmd = 'taskkill /pid ' + str(pid) + ' /f'  # 关闭指定进程
    del_self_cmd = "del %0"  # 删除自身文件
    # 写入文件
    with open(file=tmpfile, mode="w") as f:
        f.write(stop_cmd + "\n" + del_self_cmd)
 
# 进程号
pid = os.getpid()
# 生成关闭进程的脚本文件
produce_stop_bat(pid)
 
# ========增加代码--结束========
import time
while True:
    with open("log.txt",'a+',encoding="utf-8") as fw:
        fw.write(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+"and 123\n")
    time.sleep(2)

在这里插入图片描述

2 linux中后台运行python程序

1、后台运行python代码命令:nohup python3 main.py &
2、nohup 是 no hang up 的缩写,就是不挂起的意思,不断地运行。
3、最后一个 & ,代表该命令在后台执行。
4、命令运行后会有提示,示例: [1] 1111 代表进程 1111 运行中。
5、执行命令ps aux |grep python可以看到python程序,刚刚运行的程序状态为R。
6、关闭程序:kill -9 pid。

import logging
import logging.handlers
import re
import os
def setup_log(log_name):
    # (1)创建logger对象,传入logger名字
    logger = logging.getLogger(log_name)
    log_path = os.path.join("./",log_name)
    # 设置日志记录等级
    logger.setLevel(logging.INFO)

    # (2)创建一个handler,用于写入日志文件
    # interval 滚动周期,
    # when="MIDNIGHT", interval=1 表示每天0点为更新点,每天生成一个文件
    # backupCount  表示日志保存个数,会自动滚动更新
    file_handler = logging.handlers.TimedRotatingFileHandler(
        filename=log_path, when="S", interval=60, backupCount=5
    )
    # filename="mylog" suffix设置,会生成文件名为mylog.2020-02-25.log
    file_handler.suffix = "%Y-%m-%d-%H-%M-%S.log"
    # extMatch是编译好正则表达式,用于匹配日志文件名后缀
    # 需要注意的是suffix和extMatch一定要匹配的上,如果不匹配,过期日志不会被删除。
    file_handler.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}.log$")
    # (3)定义日志输出格式
    file_handler.setFormatter(
        logging.Formatter(
            '[%(asctime)s] [%(levelname)s] [%(module)s] [%(filename)s:%(lineno)s] %(message)s'
        )
    )
    # (4)给logger添加handler
    logger.addHandler(file_handler)
    return logger

import time
logger = setup_log("nihao")
while True:
    logger.debug('This is debug message.')
    logger.info('This is info message.')
    logger.warning('This is warning message.')
    logger.error('This is error message.')
    logger.critical('This is critical message.')
    time.sleep(0.5)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

皮皮冰燃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值