2008-09-22 52 views
10

什么是最简单的守护Linux中的python脚本的方法?我需要它能适用于Linux的各种风格,所以它应该只使用基于python的工具。在Linux中守护python脚本的最简单方法是什么?

+1

一注 - 请提供一种方法来在前台运行您的程序,既为调试和谁喜欢过程的监督工具(如runit人[HTTP:/ /smarden.org/runit]或daemontools [http://cr.yp.to/daemontools.html])来运行你的程序作为监督服务而不是守护进程。 – 2009-09-21 18:32:25

+0

是的,我同意(我正在使用daemontools) – edomaur 2009-09-21 21:34:58

+0

相关:[你如何在Python中创建一个守护进程?](http://stackoverflow.com/q/473620/4279) – jfs 2012-10-27 02:13:15

回答

21

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

1

如果你不关心实际的讨论(这些讨论往往偏离主题而不提供权威的回答),你可以选择一些库,这会让你的讨论更加容易。我会推荐看看ll-xist,这个库包含大量救命的代码,比如cron作业助手,守护进程框架,(对你来说什么都不感兴趣,但真的很棒)面向对象的XSL( ll-xist本身)。

2

我最近使用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) 
相关问题