我有一个自己写的日志挖掘工具。我可以使用 nohup 启动它并传入参数,例如要解析的文件(它使用我用 Python 编写的独立于平台的尾类)。但是我希望它作为初始化脚本或从命令行(作为守护进程)启动。如果同一台服务器上有多个日志文件需要查看,我希望能够启动多个实例。
我看过python-daemon package但引用文档中并不清楚是否可以传入进程/实例特定的参数。例如就像程序的每个守护进程实例应该扫描什么日志文件一样。
我试图解决的问题之一是如何停止或重新启动创建的各个守护进程实例。
最佳答案
我今天必须做完全相同的事情,多个(相同)应用程序需要作为守护进程运行。 我没有使用新的 python-daemon 包,因为我从未使用过它,但我之前多次使用过 Sander Marechal ( A simple unix/linux daemon in Python ) 的守护进程。
我创建了一个简单的测试应用程序,不是最好的 python 代码,但它按预期工作。该示例使用一个额外参数,可以像这样使用: ./runsample.py start <param>
您将看到一个新的日志文件,以及在/tmp 中为每个正在运行的守护进程创建的 pid 文件。
您可以从这里获取 Daemon 类:A simple unix/linux daemon in Python
测试应用
import sys, time
from daemon import Daemon
#simple test app that writes to a file every second
#this is just to check that the correct daemons are running
class testapp(Daemon):
ID = 0
def __init__(self, id):
print 'Init (ID): ' + id
#set the params
self.ID = id
#set the pid file
pid = '/tmp/testapp-' + str(id) + '.pid'
#init the base with the pid file location
Daemon.__init__(self, pid)
#this is the overwritten method from the article by Sander Marechal
# http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
def run(self):
while True:
#open file, append mode
f = open('/tmp/log-' + self.ID + '.log', 'a')
#write
f.write(str(time.time()))
#close
f.close()
#wait
time.sleep(1)
初始化脚本/守护进程
#!/usr/bin/env python
#
# Multiple daemons for the same app test
#
import sys
from testapp import testapp
#check is anough arguments are passed
if len(sys.argv) != 3:
print "usage: %s start|stop|restart <param>" % sys.argv[0]
sys.exit(2)
#get the extra arguments
id = sys.argv[2]
print 'Param (ID): ' + sys.argv[2]
#start the app with the parameters
daemon = testapp(id)
#from the article by Sander Marechal
# http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/
if len(sys.argv) == 3:
if 'start' == sys.argv[1]:
print 'Start'
daemon.start()
elif 'stop' == sys.argv[1]:
daemon.stop()
print 'Stop'
elif 'restart' == sys.argv[1]:
print 'Restarting...'
daemon.restart()
print 'Restarted'
else:
print "Unknown command"
sys.exit(2)
sys.exit(0)
else:
print "usage: %s start|stop|restart" % sys.argv[0]
sys.exit(2)
我希望这也适合您。
关于python-daemon 启动同一程序的多个实例并传入实例特定的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16488497/