118

我有一个 python 守护程序作为我的 web 应用程序的一部分运行/如何快速检查(使用 python)我的守护程序是否正在运行,如果没有,启动它?

我想这样做来修复守护程序的任何崩溃,因此脚本不必手动运行,它会在调用后立即自动运行,然后继续运行。

如果我的脚本正在运行,我如何检查(使用 python)?

4

20 回答 20

168

在 Linux 系统上很方便的一种技术是使用域套接字:

import socket
import sys
import time

def get_lock(process_name):
    # Without holding a reference to our socket somewhere it gets garbage
    # collected when the function exits
    get_lock._lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)

    try:
        # The null byte (\0) means the socket is created 
        # in the abstract namespace instead of being created 
        # on the file system itself.
        # Works only in Linux
        get_lock._lock_socket.bind('\0' + process_name)
        print 'I got the lock'
    except socket.error:
        print 'lock exists'
        sys.exit()


get_lock('running_test')
while True:
    time.sleep(3)

它是原子的,并且可以避免在您的进程收到 SIGKILL 时出现锁定文件的问题

您可以在文档中阅读socket.close垃圾收集时套接字会自动关闭的信息。

于 2011-10-13T17:36:26.663 回答
107

将 pidfile 放到某处(例如 /tmp)。然后你可以通过检查文件中的PID是否存在来检查进程是否正在运行。干净关闭时不要忘记删除文件,并在启动时检查它。

#/usr/bin/env python

import os
import sys

pid = str(os.getpid())
pidfile = "/tmp/mydaemon.pid"

if os.path.isfile(pidfile):
    print "%s already exists, exiting" % pidfile
    sys.exit()
file(pidfile, 'w').write(pid)
try:
    # Do some actual work here
finally:
    os.unlink(pidfile)

然后,您可以通过检查 /tmp/mydaemon.pid 的内容是否是现有进程来检查进程是否正在运行。Monit(上面提到的)可以为您执行此操作,或者您可以编写一个简单的 shell 脚本来使用 ps 的返回码为您检查它。

ps up `cat /tmp/mydaemon.pid ` >/dev/null && echo "Running" || echo "Not running"

为了获得额外的功劳,您可以使用 atexit 模块来确保您的程序在任何情况下(当被杀死、引发异常等)都清理其 pidfile。

于 2009-04-25T17:37:56.267 回答
27

pid库可以做到这一点。

from pid import PidFile

with PidFile():
  do_something()

它还将自动处理 pidfile 存在但进程未运行的情况。

于 2015-10-09T17:55:11.447 回答
11

当然,Dan 的例子不会像它应该的那样工作。

事实上,如果脚本崩溃、出现异常或没有清理 pid 文件,脚本将运行多次。

我建议基于另一个网站的以下内容:

这是为了检查是否已经存在一个锁文件

\#/usr/bin/env python
import os
import sys
if os.access(os.path.expanduser("~/.lockfile.vestibular.lock"), os.F_OK):
        #if the lockfile is already there then check the PID number
        #in the lock file
        pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "r")
        pidfile.seek(0)
        old_pid = pidfile.readline()
        # Now we check the PID from lock file matches to the current
        # process PID
        if os.path.exists("/proc/%s" % old_pid):
                print "You already have an instance of the program running"
                print "It is running as process %s," % old_pid
                sys.exit(1)
        else:
                print "File is there but the program is not running"
                print "Removing lock file for the: %s as it can be there because of the program last time it was run" % old_pid
                os.remove(os.path.expanduser("~/.lockfile.vestibular.lock"))

这是我们将 PID 文件放入锁定文件的代码的一部分

pidfile = open(os.path.expanduser("~/.lockfile.vestibular.lock"), "w")
pidfile.write("%s" % os.getpid())
pidfile.close()

此代码将检查 pid 与现有正在运行的进程相比的值,避免重复执行。

我希望它会有所帮助。

于 2010-11-27T10:41:19.593 回答
9

在 UNIX 上有非常好的重启进程的包。有一个关于构建和配置它的很棒的教程是monit。通过一些调整,您可以获得可靠的成熟技术来保持您的守护进程。

于 2009-04-25T07:16:06.637 回答
9

我的解决方案是检查在 windows 和 ubuntu linux 上测试的进程和命令行参数

import psutil
import os

def is_running(script):
    for q in psutil.process_iter():
        if q.name().startswith('python'):
            if len(q.cmdline())>1 and script in q.cmdline()[1] and q.pid !=os.getpid():
                print("'{}' Process is already running".format(script))
                return True

    return False


if not is_running("test.py"):
    n = input("What is Your Name? ")
    print ("Hello " + n)
于 2018-04-27T13:11:47.250 回答
7

有无数种选择。一种方法是使用系统调用或 python 库为您执行此类调用。另一种是简单地产生一个过程,如:

ps ax | grep processName

并解析输出。很多人选择这种方法,在我看来这不一定是一个坏方法。

于 2009-04-25T07:05:50.670 回答
7

遇到这个老问题,我自己正在寻找解决方案。

使用psutil

import psutil
import sys
from subprocess import Popen

for process in psutil.process_iter():
    if process.cmdline() == ['python', 'your_script.py']:
        sys.exit('Process found: exiting.')

print('Process not found: starting it.')
Popen(['python', 'your_script.py'])
于 2017-06-06T18:21:29.343 回答
2

我是管理守护进程的超级粉丝。它是用 Python 编写的,因此有很多关于如何与 Python 交互或扩展它的示例。出于您的目的,XML-RPC 过程控制 API应该可以很好地工作。

于 2009-04-26T07:36:54.317 回答
2

试试这个其他版本

def checkPidRunning(pid):        
    '''Check For the existence of a unix pid.
    '''
    try:
        os.kill(pid, 0)
    except OSError:
        return False
    else:
        return True

# Entry point
if __name__ == '__main__':
    pid = str(os.getpid())
    pidfile = os.path.join("/", "tmp", __program__+".pid")

    if os.path.isfile(pidfile) and checkPidRunning(int(file(pidfile,'r').readlines()[0])):
            print "%s already exists, exiting" % pidfile
            sys.exit()
    else:
        file(pidfile, 'w').write(pid)

    # Do some actual work here
    main()

    os.unlink(pidfile)
于 2012-10-02T00:09:37.410 回答
1

与其开发你自己的 PID 文件解决方案(它比你想象的有更多的微妙之处和极端情况),不如看看supervisord——这是一个过程控制系统,它可以很容易地围绕现有的 Python 包装作业控制和守护进程行为脚本。

于 2014-09-04T10:21:17.737 回答
0

其他答案非常适合 cron 作业之类的事情,但是如果您正在运行守护程序,则应该使用daemontools之类的东西对其进行监视。

于 2012-06-12T15:31:37.570 回答
0
ps ax | grep processName

如果你在 pycharm 中的调试脚本总是退出

pydevd.py --multiproc --client 127.0.0.1 --port 33882 --file processName
于 2014-02-28T18:27:36.293 回答
0

试试这个:

#/usr/bin/env python
import os, sys, atexit

try:
    # Set PID file
    def set_pid_file():
        pid = str(os.getpid())
        f = open('myCode.pid', 'w')
        f.write(pid)
        f.close()

    def goodby():
        pid = str('myCode.pid')
        os.remove(pid)

    atexit.register(goodby)
    set_pid_file()
    # Place your code here

except KeyboardInterrupt:
    sys.exit(0)
于 2016-08-08T05:48:24.443 回答
0

这是更有用的代码(检查是否正是 python 执行脚本):

#! /usr/bin/env python

import os
from sys import exit


def checkPidRunning(pid):
    global script_name
    if pid<1:
        print "Incorrect pid number!"
        exit()
    try:
        os.kill(pid, 0)
    except OSError:
        print "Abnormal termination of previous process."
        return False
    else:
        ps_command = "ps -o command= %s | grep -Eq 'python .*/%s'" % (pid,script_name)
        process_exist = os.system(ps_command)
        if process_exist == 0:
            return True
        else:
            print "Process with pid %s is not a Python process. Continue..." % pid
            return False


if __name__ == '__main__':
    script_name = os.path.basename(__file__)
    pid = str(os.getpid())
    pidfile = os.path.join("/", "tmp/", script_name+".pid")
    if os.path.isfile(pidfile):
        print "Warning! Pid file %s existing. Checking for process..." % pidfile
        r_pid = int(file(pidfile,'r').readlines()[0])
        if checkPidRunning(r_pid):
            print "Python process with pid = %s is already running. Exit!" % r_pid
            exit()
        else:
            file(pidfile, 'w').write(pid)
    else:
        file(pidfile, 'w').write(pid)

# main programm
....
....

os.unlink(pidfile)

这是字符串:

ps_command = "ps -o command= %s | grep -Eq 'python .*/%s'" % (pid,script_name)

如果“grep”成功,则返回 0,并且进程“python”当前正在以脚本名称作为参数运行。

于 2016-09-22T08:30:38.970 回答
0

一个简单的例子,如果你只是在寻找一个进程名称是否存在:

import os

def pname_exists(inp):
    os.system('ps -ef > /tmp/psef')
    lines=open('/tmp/psef', 'r').read().split('\n')
    res=[i for i in lines if inp in i]
    return True if res else False

Result:
In [21]: pname_exists('syslog')
Out[21]: True

In [22]: pname_exists('syslog_')
Out[22]: False
于 2017-04-27T08:09:49.883 回答
0

我一直在寻找这个问题的答案,就我而言,我认为这是一个非常简单且非常好的解决方案(因为不可能存在误报,我猜 - TXT 上的时间戳怎么能如果程序不这样做,则更新):

--> 根据您的需要,在某个时间间隔内继续在 TXT 上写入当前时间戳(这里每半小时是完美的)。

如果您检查时 TXT 上的时间戳相对于当前时间戳已过时,则程序存在问题,应该重新启动它或您更喜欢做什么。

于 2021-03-05T23:18:58.743 回答
-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)

我建议使用此脚本,因为它只能执行一次。

于 2012-07-12T18:29:35.883 回答
-1

使用 bash 查找具有当前脚本名称的进程。没有额外的文件。

import commands
import os
import time
import sys

def stop_if_already_running():
    script_name = os.path.basename(__file__)
    l = commands.getstatusoutput("ps aux | grep -e '%s' | grep -v grep | awk '{print $2}'| awk '{print $2}'" % script_name)
    if l[1]:
        sys.exit(0);

要测试,请添加

stop_if_already_running()
print "running normally"
while True:
    time.sleep(3)
于 2013-06-14T20:35:09.400 回答
-1

这是我在 Linux 中用来避免启动脚本(如果已经运行)的方法:

import os
import sys


script_name = os.path.basename(__file__)
pidfile = os.path.join("/tmp", os.path.splitext(script_name)[0]) + ".pid"


def create_pidfile():
    if os.path.exists(pidfile):
        with open(pidfile, "r") as _file:
            last_pid = int(_file.read())

        # Checking if process is still running
        last_process_cmdline = "/proc/%d/cmdline" % last_pid
        if os.path.exists(last_process_cmdline):
            with open(last_process_cmdline, "r") as _file:
                cmdline = _file.read()
            if script_name in cmdline:
                raise Exception("Script already running...")

    with open(pidfile, "w") as _file:
        pid = str(os.getpid())
        _file.write(pid)


def main():
    """Your application logic goes here"""


if __name__ == "__main__":
    create_pidfile()
    main()

这种方法在不依赖外部模块的情况下效果很好。

于 2018-06-21T17:38:54.847 回答