Skip to main content
 首页 » 编程设计

python-daemon 启动同一程序的多个实例并传入特定于实例的参数

2024年11月01日8yjmyzz

我有一个我写的日志挖掘工具。我可以使用 nohup 启动它并传入参数,例如要解析的文件(它使用我用 Python 编写的独立于平台的尾部类)。但是我希望它作为初始化脚本或从命令行(作为守护进程)启动。如果在同一台服务器上要查看多个日志文件,我希望能够启动多个实例。

我看过 python-daemon package但在引用文档中不清楚是否可以传入进程/实例特定参数。例如就像程序的每个守护进程实例应该扫描的日志文件一样。

我试图解决的问题之一是如何停止或重新启动创建的各个守护程序实例。

请您参考如下方法:

我今天不得不做完全相同的事情,多个(相同的)应用程序需要作为守护进程运行。 我没有使用新的 python-daemon 包,因为我从未使用过它,但我以前多次使用过 Sander Marechal (A simple unix/linux daemon in Python) 的守护进程。

我创建了一个简单的测试应用程序,不是最好的 python 代码,但它按预期工作。该示例使用一个额外的参数,可以像这样使用:./runsample.py start <param>

您将看到一个新的日志文件,以及在/tmp 中为每个正在运行的守护进程创建的 pid 文件。

您可以从这里获取守护程序类: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) 

我希望这对你也有用。