python - 守护进程 : Detecting if a daemon is already running

标签 python python-2.7 python-daemon

我有一个脚本使用 DaemonRunner 创建一个带有 pid 文件的守护进程。问题是,如果有人试图在不停止当前运行的进程的情况下启动它,它会默默地失败。检测现有进程并提醒用户首先停止它的最佳方法是什么?是不是像检查 pid 文件一样简单?

我的代码类似于这个例子:

#!/usr/bin/python
import time
from daemon import runner

class App():
    def __init__(self):
        self.stdin_path = '/dev/null'
        self.stdout_path = '/dev/tty'
        self.stderr_path = '/dev/tty'
        self.pidfile_path =  '/tmp/foo.pid'
        self.pidfile_timeout = 5
    def run(self):
        while True:
            print("Howdy!  Gig'em!  Whoop!")
            time.sleep(10)

app = App()
daemon_runner = runner.DaemonRunner(app)
daemon_runner.do_action()

要查看我的实际代码,请查看 investor.py: https://github.com/jgillick/LendingClubAutoInvestor

最佳答案

由于 DaemonRunner 处理它自己的锁文件,更明智的做法是引用那个锁文件,以确保您不会搞砸。也许这个 block 可以帮助你:

添加
从锁文件导入 LockTimeout
到脚本的开头并像这样包围 daemon_runner.doaction()

try:
    daemon_runner.do_action()
except LockTimeout:
    print "Error: couldn't aquire lock"
    #you can exit here or try something else

关于python - 守护进程 : Detecting if a daemon is already running,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16247002/

相关文章:

python - Python 守护进程中的 Paramiko 导致 IOError

python - wxPython 的建议框?

python - 从单元格中检索完整的富文本数据(单元格内有多种字体颜色/样式)

Python furl 库 - 有没有办法在没有 url 编码的情况下将参数添加到 url?

python - 如何使用 tkinter 测量在 python 中按下按钮之间耗时?

python - 如何在 Python 中读取和删除文件中的前 n 行 - 优雅的解决方案

python - 点前多于 1 位的类科学符号

python - python 守护进程的单个实例(使用 python-daemon)

python - 如果我 fork 一个有守护线程的进程会发生什么?

python - 通过滚动对象将多个滚动函数应用于 Pandas 组的多列?