检查python脚本是否正在运行 [英] Check to see if python script is running

查看:330
本文介绍了检查python脚本是否正在运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a python daemon running as a part of my web app/ How can I quickly check (using python) if my daemon is running and, if not, launch it?

我想通过这种方式来修复守护程序的任何崩溃,因此该脚本不必手动运行,它将在调用后立即自动运行,然后保持运行状态。

I want to do it that way to fix any crashes of the daemon, and so the script does not have to be run manually, it will automatically run as soon as it is called and then stay running.

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

How can i check (using python) if my script is running?

推荐答案

将pidfile放在某个地方(例如/ tmp)。然后,您可以通过检查文件中的PID是否存在来检查进程是否正在运行。

Drop a pidfile somewhere (e.g. /tmp). Then you can check to see if the process is running by checking to see if the PID in the file exists. Don't forget to delete the file when you shut down cleanly, and check for it when you start up.

#/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的返回代码为您检查它。

Then you can check to see if the process is running by checking to see if the contents of /tmp/mydaemon.pid are an existing process. Monit (mentioned above) can do this for you, or you can write a simple shell script to check it for you using the return code from ps.

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

要获得额外的信用,可以使用atexit模块来确保您的程序能够清除在任何情况下(当被杀死,引发异常等)时都可以打开其pidfile。

For extra credit, you can use the atexit module to ensure that your program cleans up its pidfile under any circumstances (when killed, exceptions raised, etc.).

这篇关于检查python脚本是否正在运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆