2008-09-22 36 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) 
相關問題