我写一个python脚本,以保持一个错误的程序打开,我需要弄清楚如果程序不respoding并关闭它在Windows上。我不能完全弄清楚如何做到这一点。
在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
你可以得到比这更多的信息。为了得到“没有响应”的过程直接,只是“没有响应”变“跑”的功能说明。 See more info here。
从@Saullo GP卡斯特罗真棒答案堆积如山,这是使用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 |
+-----------------------------+---------------------------+
令人惊奇的是,它是os.system
执行慢一点,如果我们使用PID,但没有太大的不同,如果我们使用subprocess.Popen
。
希望它可以帮助。