参见史蒂文斯(Stevens)以及在activestate上的一条冗长的线程,我个人认为这既不正确,又非常冗长,我想到了这一点:
from os import fork, setsid, umask, dup2from sys import stdin, stdout, stderrif fork(): exit(0)umask(0) setsid() if fork(): exit(0)stdout.flush()stderr.flush()si = file('/dev/null', 'r')so = file('/dev/null', 'a+')se = file('/dev/null', 'a+', 0)dup2(si.fileno(), stdin.fileno())dup2(so.fileno(), stdout.fileno())dup2(se.fileno(), stderr.fileno())如果您需要再次停止该过程,则需要知道该pid,通常的解决方案是pidfiles。如果您需要一个
from os import getpidoutfile = open(pid_file, 'w')outfile.write('%i' % getpid())outfile.close()出于安全原因,您可以在妖魔化后考虑其中的任何一种
from os import setuid, setgid, chdirfrom pwd import getpwnamfrom grp import getgrnamsetuid(getpwnam('someuser').pw_uid)setgid(getgrnam('somegroup').gr_gid)chdir('/')您也可以使用nohup,但是不能与python的子进程模块一起很好地工作



