检查Python脚本是否在运行

129 投票
21 回答
218243 浏览
提问于 2025-04-15 11:14

我有一个用Python写的后台程序,它是我网页应用的一部分。我想知道怎么能快速检查一下(用Python)我的这个后台程序是否在运行,如果没有的话,怎么启动它?

我这么做是为了能修复后台程序的崩溃问题,而且这样我的脚本就不需要手动去运行,只要一调用它就会自动运行,并且保持运行状态。

那我该怎么用Python检查一下我的这个脚本是否在运行呢?

21 个回答

27

pid这个库可以做到这一点。

from pid import PidFile

with PidFile():
  do_something()

它还会自动处理一种情况:就是当pid文件存在但进程并没有在运行时。

177

在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的内容,了解到套接字在被垃圾回收时会自动关闭。

109

把一个叫做pidfile的文件放到某个地方(比如说/tmp)。这样你就可以通过查看这个文件里的PID(进程ID)来判断这个程序是否还在运行。记得在程序正常关闭的时候把这个文件删掉,启动的时候也要检查一下这个文件。

#/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工具可以帮你完成这个检查,或者你也可以写一个简单的脚本,利用ps命令的返回结果来检查。

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

如果想更进一步,你可以使用atexit模块,确保你的程序在任何情况下都能清理掉pidfile(比如被杀掉、出现异常等情况)。

撰写回答