即让Python脚本在后台运行
1 方式1
Linux下通过nohup+&方式
nohup python test.py &> run.log &
2 方式2
Linux下通过os.fork实现
3 方式3*
通过第三方包[pep3143daemon]()
import os
import time
import syslog
from pep3143daemon import DaemonContext, PidFile
def main():
with open('out.txt', 'w') as out:
for i in range(30):
out.write('write number {}\n'.format(i))
time.sleep(1)
out.write('done\n')
pid = 'test.pid'
pidfile = PidFile(pid)
daemon = DaemonContext(
pidfile=pidfile,
working_directory=os.getcwd()) # 设置工作目录为当前目录
print('pidfile is: {0}'.format(pid))
print('daemonizing...')
daemon.open()
main()
参考: