python-daemon实现后台守护进程

我们可以使用很多种方式让python脚本再后台运行,其中最简单的方式是使用linux下的nohup命令

1.nohup命令

nohup python test.py &

这样test.py脚本就脱离了当前终端的控制,我们如果可以使用ps命令查找进程并关闭

2.tmux终端

tmux是一个提供后台终端窗口的会话服务,我们只需要开启tmux,然后再tmux窗口中运行脚本,然后退出tmux即可

3.python-daemon模块

这个模块可以使我们的脚本变为后台守护进程,这个模块需要安装

pip install python-daemon

下面我们有个简单例子

#!/usr/bin/python3
#coding:utf-8
import daemon
import time

with daemon.DaemonContext():
    f = open("/root/r.log", "a+")
    while True:
        f.write("test time: {}\n".format(time.time()))
        f.flush()
        time.sleep(3)

我们执行python3 test.py运行后,查看r.log文件

tail -f r.log
test time: 1572086679.2347727
test time: 1572086682.2360961
test time: 1572086685.2392597
test time: 1572086688.2424757

持续刷新新的记录

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://sulao.cn/post/734.html

我要评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。