在Linux中守护python脚本的最简单方法是什么?我需要这与Linux的每一个味道,所以它应该只使用python为基础的工具。
发布于 2008-09-22 16:47:31
请参阅Stevens和这个lengthy thread on activestate,我个人发现它大部分都是不正确的,而且有很多冗长的地方,我想出了这个:
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。如果需要,请执行此操作
from os import getpid
outfile = open(pid_file, 'w')
outfile.write('%i' % getpid())
outfile.close()出于安全原因,你可以在妖魔化之后考虑其中的任何一个。
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's subprocess module中不能很好地工作
发布于 2008-09-22 16:41:18
nohup
Creating a daemon the Python way
发布于 2010-08-31 13:43:09
我最近使用了Turkmenbashi:
$ easy_install turkmenbashi
import Turkmenbashi
class DebugDaemon (Turkmenbashi.Daemon):
def config(self):
self.debugging = True
def go(self):
self.debug('a debug message')
self.info('an info message')
self.warn('a warning message')
self.error('an error message')
self.critical('a critical message')
if __name__=="__main__":
d = DebugDaemon()
d.config()
d.setenv(30, '/var/run/daemon.pid', '/tmp', None)
d.start(d.go)https://stackoverflow.com/questions/115974
复制相似问题