即让Python脚本在后台运行

1 方式1

Linux下通过nohup+&方式

  1. nohup python test.py &> run.log &

2 方式2

Linux下通过os.fork实现

3 方式3*

通过第三方包[pep3143daemon]()

  1. import os
  2. import time
  3. import syslog
  4. from pep3143daemon import DaemonContext, PidFile
  5. def main():
  6. with open('out.txt', 'w') as out:
  7. for i in range(30):
  8. out.write('write number {}\n'.format(i))
  9. time.sleep(1)
  10. out.write('done\n')
  11. pid = 'test.pid'
  12. pidfile = PidFile(pid)
  13. daemon = DaemonContext(
  14. pidfile=pidfile,
  15. working_directory=os.getcwd()) # 设置工作目录为当前目录
  16. print('pidfile is: {0}'.format(pid))
  17. print('daemonizing...')
  18. daemon.open()
  19. main()

参考: