发布时间:2019-09-19 08:02:03编辑:auto阅读(1592)
nohup 可以使程序后台运行不受终端影响,但想使程序运行后就脱离终端Python需要用到os.fork来实现,例子如下:
daemonize.py
- #!/usr/bin/python
- #coding:utf-8
- import sys
- import os
- def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
- try:
- pid = os.fork()
- if pid > 0:
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #1 failed: (%d) %s\n" % (e.errorno, e.strerror))
- sys.exit(1)
- os.chdir('/')
- os.umask(0)
- os.setsid()
- try:
- pid = os.fork()
- if pid > 0:
- sys.exit(0)
- except OSError, e:
- sys.stderr.write("fork #2 failed: (%d) %s\n" % (e.errorno, e.strerror))
- sys.exit(1)
- for f in sys.stdout, sys.stderr:
- f.flush()
- si = file(stdin, 'r')
- so = file(stdout, 'a+')
- se = file(stderr, 'a+', 0)
- os.dup2(si.fileno(), sys.stdin.fileno())
- os.dup2(so.fileno(), sys.stdout.fileno())
- os.dup2(se.fileno(), sys.stderr.fileno())
然后我们来调用daemonize接口,使脚本后台运行:
test.py
- #!/usr/bin/python
- #coding:utf-8
- from daemonize import daemonize
- import sys
- import time
- def test():
- while True:
- sys.stdout.write("Hello!")
- time.sleep(1)
- if __name__ == "__main__":
- daemonize(stdout='/home/wisp/test_print.log', stderr='/home/wisp/test_print.log')
- test()
运行test.py后,test.py就会后台运行!~~
上一篇: python—连接mongodb
下一篇: Python file 方法
47840
46386
37279
34729
29312
25970
24909
19948
19541
18020
5790°
6411°
5926°
5960°
7063°
5910°
5942°
6437°
6404°
7776°