【发布时间】:2013-05-10 22:11:01
【问题描述】:
我正在编写一个 python 脚本来保持一个有缺陷的程序打开,我需要确定该程序是否没有响应并在 Windows 上关闭它。我不知道该怎么做。
【问题讨论】:
标签: python process operating-system
我正在编写一个 python 脚本来保持一个有缺陷的程序打开,我需要确定该程序是否没有响应并在 Windows 上关闭它。我不知道该怎么做。
【问题讨论】:
标签: python process operating-system
在 Windows 上,您可以这样做:
import os
def isresponding(name):
os.system('tasklist /FI "IMAGENAME eq %s" /FI "STATUS eq running" > tmp.txt' % name)
tmp = open('tmp.txt', 'r')
a = tmp.readlines()
tmp.close()
if a[-1].split()[0] == name:
return True
else:
return False
不过,使用 PID 更健壮:
def isrespondingPID(PID):
os.system('tasklist /FI "PID eq %d" /FI "STATUS eq running" > tmp.txt' % PID)
tmp = open('tmp.txt', 'r')
a = tmp.readlines()
tmp.close()
if int(a[-1].split()[1]) == PID:
return True
else:
return False
您可以从tasklist 获得更多信息。要直接获取“NOT RESPONDING”流程,只需在给定函数中将“running”更改为“notresponsive”即可。 See more info here.
【讨论】:
subprocess 打开软件(推荐),您可以轻松地执行以下操作:p = subprocess.Popen('calc.exe') 并使用PID=p.pid 访问PID
Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> isrespondingPID(9064) File "<pyshell#8>", line 6, in isrespondingPID if int(a[-1].split()[1]) == PID: ValueError: invalid literal for int() with base 10: 'Es' 然后我只是将它包裹在try: ... except ValueError: ...
根据@Saullo GP Castro 的精彩回答,这是一个使用subprocess.Popen 而不是os.system 以避免创建临时文件的版本。
import subprocess
def isresponding(name):
"""Check if a program (based on its name) is responding"""
cmd = 'tasklist /FI "IMAGENAME eq %s" /FI "STATUS eq running"' % name
status = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read()
return name in str(status)
对应的PID版本为:
def isresponding_PID(pid):
"""Check if a program (based on its PID) is responding"""
cmd = 'tasklist /FI "PID eq %d" /FI "STATUS eq running"' % pid
status = subprocess.Popen(cmd, stdout=subprocess.PIPE).stdout.read()
return str(pid) in str(status)
timeit 的使用表明subprocess.Popen 的使用速度是原来的两倍(主要是因为我们不需要遍历文件):
+-----------------------------+---------------------------+
| Function | Time in s (10 iterations) |
+-----------------------------+---------------------------+
| isresponding_os | 8.902 |
+-----------------------------+---------------------------+
| isrespondingPID_os | 8.318 |
+-----------------------------+---------------------------+
| isresponding_subprocess | 4.852 |
+-----------------------------+---------------------------+
| isresponding_PID_subprocess | 4.868 |
+-----------------------------+---------------------------+
令人惊讶的是,如果我们使用 PID,os.system 的实现会慢一些,但如果我们使用 subprocess.Popen,则差别不大。
希望对你有帮助。
【讨论】: