【问题标题】:How to check if program is running by python script?如何检查程序是否由python脚本运行?
【发布时间】:2015-10-24 03:10:03
【问题描述】:

现在我有一个 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."

是这样吗?

【问题讨论】:

  • 什么是适合您的?运行udp_server.py 会打印那种输出吗?您是否尝试运行pgrep 命令来检查进程是否已经在运行?这是在udp_server.py 中运行,以查看它是否已经从 cron 作业运行,因此必须在列表中忽略它自己?
  • 另外,你可能想检查这个问题:Process list on Linux via Python
  • 对不起,我输入了错误命令。
  • 你的意思是control a processes
  • 我只想知道进程是否存在。

标签: python python-2.7 crontab


【解决方案1】:

如果你想像在unix控制台输入一样输入命令行,那就对了。

假设你将代码打包成一个文件,也许你会遇到一个问题:无法执行 命令。是因为你的linux账号没有足够的权限,建议你这样做:

sudo python command_file.py

顺便说一句,如果你真的在 python2.6+ 中工作,请注意 api,自 2.6 版起已弃用:命令模块已在 Python 3 中删除。改用 subprocess 模块。 所以我建议你把它替换成subprocess。 参考超链接:commands

【讨论】:

    猜你喜欢
    • 2012-11-14
    • 1970-01-01
    • 2019-03-10
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    相关资源
    最近更新 更多