pythondaemon启动同一程序的多个实例,并传入特定于实例的参数

2024-04-25 16:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我已经看过python-daemon package,但是在参考文档中不清楚是否可以传入进程/实例特定的参数。e、 例如程序的每个守护进程实例应该扫描的日志文件。在

我想弄清楚的一个问题是如何停止或重新启动创建的各个守护进程实例。在


Tags: 文件工具实例命令行文档服务器脚本package
1条回答
网友
1楼 · 发布于 2024-04-25 16:46:06

今天我不得不做同样的事情,多个(相同的)应用程序需要作为守护程序运行。 我没有使用新的python守护程序包,因为我从未使用过它,但是我以前多次使用sandermarechal(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)

初始化脚本/守护进程

^{pr2}$

我希望这对你也有用。在

相关问题 更多 >