在Ubuntu下后台持续运行Python程序

参考链接:https://blog.csdn.net/weixin_37887248/article/details/80727627

测试程序

先写一个测试程序,用于输出日志和打印到控制台。

#-*- coding: utf-8 -*-
import logging
import time
from logging.handlers import RotatingFileHandler
 
 
def func():
    init_log()
    while True:
        print "output to the console"
        logging.debug("output the debug log")
        logging.info("output the info log")
        time.sleep(3);
 
 
def init_log():
    logging.getLogger().setLevel(logging.DEBUG)
    console = logging.StreamHandler()
    console.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
    console.setFormatter(formatter)
    logging.getLogger().addHandler(console)
 
    # add log ratate
    Rthandler = RotatingFileHandler("backend_run.log", maxBytes=10 * 1024 * 1024, backupCount=100,
                                    encoding="gbk")
    Rthandler.setLevel(logging.INFO)
    # formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s')
    Rthandler.setFormatter(formatter)
    logging.getLogger().addHandler(Rthandler)
 
 
 
if __name__ == '__main__':
    func()

后台启动Python脚本

可以使用下面的命令来启动上面的脚本,让Python在后台运行。

nohup python -u test.py > test.log 2>&1 &

运行命令后,会返回一个pid。像下面这样:https://blog.csdn.net/tswisdom/article/details/8548710

[1] 9208

来解释一下这几个命令的参数 ,参考链接:

其中 0、1、2分别代表如下含义:
 0 – stdin (standard input)
 1 – stdout (standard output)
 2 – stderr (standard error)
nohup python -u test.py > test.log 2>&1 &
nohup+最后面的& 是让命令在后台执行
>test.log是将信息输出到test.log日志中
2>&1 是将标准错误信息转变成标准输出,这样就可以将错误信息输出到test.log 日志里面来。

跟踪输出文件变化

为了验证脚本可以在后台继续运行,我们退出当前会话。然后重新连接一个Session,然后输入下面的命令来跟踪文件的输出:

tail -f test.log

输出内容:

output to the console
2017-03-21 20:15:02,632 test.py[line:11] DEBUG output the debug log
2017-03-21 20:15:02,632 test.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:05,635 test.py[line:11] DEBUG output the debug log
2017-03-21 20:15:05,636 test.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:08,637 test.py[line:11] DEBUG output the debug log
2017-03-21 20:15:08,638 test.py[line:12] INFO output the info log
output to the console
2017-03-21 20:15:11,640 test.py[line:11] DEBUG output the debug log
2017-03-21 20:15:11,642 test.py[line:12] INFO output the info log

说明我们的脚本确实在后台持续运行。ps

结束程序

可以直接通过之前的那个pid杀掉脚本,或者可以通过下面的命令查找pid。

ps -ef | grep python

可以看到我们的pid是9208,调用kill杀掉就可以了。

kill -9 18191

从结果中可以看到,进程已经被kill了 

编写启动及停止脚本

启动脚本

#!/bin/sh
 
pid=`ps -ef|grep "python -u test.py"| grep -v "grep"|awk '{print $2}'`
 
if [ "$pid" != "" ]
then
        echo "test.py already run, stop it first"
        kill -9 ${pid}
fi
 
echo "starting now..."
 
nohup python -u test.py > test.log 2>&1 &
 
pid=`ps -ef|grep "python -u test.py"| grep -v "grep"|awk '{print $2}'`
 
echo ${pid} > pid.out
echo "test.py started at pid: "${pid}

停止脚本

#!/bin/sh
 
pid=`ps -ef|grep "python -u test.py"| grep -v "grep"|awk '{print $2}'`
 
if [ "$pid" != "" ]
then
        kill -9 ${pid}
        echo "stop test.py complete"
else
        echo "test.py is not run, there's no need to stop it"
fi

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值