简体   繁体   English

如何检查程序是否正在通过python脚本运行?

[英]How to check if program is running by python script?

Now I have a udp_server.py to run. 现在,我有一个udp_server.py可以运行。

According to my less experience, I will do a python script in crontab as bellow. 根据我的经验,我将在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."

is this right? 这是正确的吗?

If you want to type command line as like typing in unix console, it's right. 如果您要像在unix控制台中一样键入命令行,那是对的。

Suppose you will package the code in a file, maybe you will encounter a problem: it can't excute command. 假设您将代码打包在一个文件中,也许您会遇到一个问题:它不能执行命令。 It's because your account in linux hasn't enough authority, I suggest you do as the following: 这是因为您在Linux中的帐户没有足够的权限,因此建议您按照以下步骤操作:

sudo python command_file.py

By the way, if you really work in python2.6+, please notice the api, deprecated since version 2.6: The commands module has been removed in Python 3. Use the subprocess module instead. 顺便说一句,如果您确实在python2.6 +中工作,请注意自2.6版以来已弃用的api:在Python 3中已删除了commands模块。请改用subprocess模块​​。 So I suggest you replace it form subprocess . 因此,我建议您将其替换为subprocess Reference hypelink: commands 参考hypelink: 命令

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM