在Linux中守护python脚本的最简单方法是什么?

在Linux中守护python脚本的最简单方法是什么?

问题描述:

在Linux中守护python脚本的最简单方法是什么?我需要它适用于各种Linux版本,因此只能使用基于python的工具。

What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools.

请参见史蒂文斯(Stevens),还有这个 activestate上的长线程,我个人认为这两者都是主要原因不正确且很冗长,我想出了这一点:

See Stevens and also this lengthy thread on activestate which I found personally to be both mostly incorrect and much to verbose, and I came up with this:

from os import fork, setsid, umask, dup2
from sys import stdin, stdout, stderr

if 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。如果需要一个

If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one

from os import getpid
outfile = open(pid_file, 'w')
outfile.write('%i' % getpid())
outfile.close()

出于安全原因,您可能需要在妖魔化之后考虑其中的任何一个

For security reasons you might consider any of these after demonizing

from os import setuid, setgid, chdir
from pwd import getpwnam
from grp import getgrnam
setuid(getpwnam('someuser').pw_uid)
setgid(getgrnam('somegroup').gr_gid)
chdir('/') 

您还可以使用 nohup ,但不适用于 python的子进程模块

You could also use nohup but that does not work well with python's subprocess module