检查Python脚本是否正在运行。

129

我有一个作为我的 Web 应用程序一部分运行的 Python 守护进程。如何快速检查是否正在运行,如果没有,则启动它?

我想这样做是为了解决守护进程的任何崩溃,并且脚本不必手动运行,只要调用即可自动运行并保持运行。

我该如何使用 Python 检查我的脚本是否正在运行?


你确定你想用Python编写让一个进程保持另一个进程运行的程序吗? - ojblass
试试 Tendo,它可以创建你的脚本的单例实例,因此如果已经在运行,则脚本将不会再次运行。https://github.com/pycontribs/tendo - JasTonAChair
这不是你的守护进程的工作,而是由“上层”应用程序来启动你的守护进程的工作。使用systemd或类似supervisord的其他工具。不要依赖于写入文件的pid。如果无法使用systemd/supervisord,则使用锁定确保它不会被执行两次。 - guettli
21个回答

-1
考虑以下示例以解决您的问题:
#!/usr/bin/python
# -*- coding: latin-1 -*-

import os, sys, time, signal

def termination_handler (signum,frame):
    global running
    global pidfile
    print 'You have requested to terminate the application...'
    sys.stdout.flush()
    running = 0
    os.unlink(pidfile)

running = 1
signal.signal(signal.SIGINT,termination_handler)

pid = str(os.getpid())
pidfile = '/tmp/'+os.path.basename(__file__).split('.')[0]+'.pid'

if os.path.isfile(pidfile):
    print "%s already exists, exiting" % pidfile
    sys.exit()
else:
    file(pidfile, 'w').write(pid)

# Do some actual work here

while running:
  time.sleep(10)

我建议使用这个脚本,因为它只需要执行一次即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接