如何通过python脚本检查程序是否为运行?
How to check if program is running by python script?
现在我有 udp_server.py 到 运行。
根据我的经验,我会在crontab中做一个python脚本,如下所示。
import commands
output = commands.getoutput("ps aux | grep udp_server.py")
'''print output
user 8695 0.0 0.3 50948 14196 pts/0 S 10:21 0:00 python udp_server.py
user 9486 0.0 0.0 4400 584 pts/0 S+ 10:34 0:00 sh -c { ps aux | grep 'udp_server.py'; } 2>&1
user 9488 0.0 0.0 9384 888 pts/0 R+ 10:34 0:00 grep udp_server.py
'''
if 'python udp_server.py' in output:
print "The server is active."
这样对吗?
如果你想像在 unix 控制台中一样输入命令行,那就对了。
假设你将代码打包成一个文件,也许你会遇到一个问题:无法执行
命令。是因为你在linux的账号权限不够,建议你按以下方式操作:
sudo python command_file.py
顺便说一下,如果你真的在 python2.6+ 工作,请注意 api,自 2.6 版以来已弃用:命令模块已在 Python 3 中删除. 改为使用 subprocess 模块。
所以我建议你把它替换成subprocess
。
参考超级链接:commands
现在我有 udp_server.py 到 运行。
根据我的经验,我会在crontab中做一个python脚本,如下所示。
import commands
output = commands.getoutput("ps aux | grep udp_server.py")
'''print output
user 8695 0.0 0.3 50948 14196 pts/0 S 10:21 0:00 python udp_server.py
user 9486 0.0 0.0 4400 584 pts/0 S+ 10:34 0:00 sh -c { ps aux | grep 'udp_server.py'; } 2>&1
user 9488 0.0 0.0 9384 888 pts/0 R+ 10:34 0:00 grep udp_server.py
'''
if 'python udp_server.py' in output:
print "The server is active."
这样对吗?
如果你想像在 unix 控制台中一样输入命令行,那就对了。
假设你将代码打包成一个文件,也许你会遇到一个问题:无法执行 命令。是因为你在linux的账号权限不够,建议你按以下方式操作:
sudo python command_file.py
顺便说一下,如果你真的在 python2.6+ 工作,请注意 api,自 2.6 版以来已弃用:命令模块已在 Python 3 中删除. 改为使用 subprocess 模块。
所以我建议你把它替换成subprocess
。
参考超级链接:commands