问题描述
在 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
这篇关于在 Linux 中守护 python 脚本的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!