如何判断进程是否在Windows上的Python中响应

时间:2013-05-16 06:18:55

标签: python process operating-system

我正在编写一个python脚本来保持一个错误的程序打开,我需要弄清楚程序是否没有重新编码并在Windows上关闭它。我无法弄清楚如何做到这一点。

2 个答案:

答案 0 :(得分:3)

在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

答案 1 :(得分:0)

基于@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,则相差不大。

希望它可以提供帮助。