尽管@zeller已经在这里说明了如何使用
tasklist
,但以下是一个例子。因为我刚刚在寻找
纯正的Python替代方案...。
虽然@zeller已经在这里说明了如何使用tasklist
,但以下是一个例子。因为我刚刚在寻找纯正的Python替代方案...
import subprocess
def process_exists(process_name):
call = 'TASKLIST', '/FI', 'imagename eq %s' % process_name
output = subprocess.check_output(call).decode()
last_line = output.strip().split('\r\n')[-1]
return last_line.lower().startswith(process_name.lower())
现在你可以做:
>>> process_exists('eclipse.exe')
True
>>> process_exists('AJKGVSJGSCSeclipse.exe')
False
为了避免多次调用并获得所有进程的概览,你可以这样做:
import subprocess
output = subprocess.check_output(('TASKLIST', '/FO', 'CSV')).decode()
output = output.replace('"', '').split('\r\n')
keys = output[0].split(',')
proc_list = [i.split(',') for i in output[1:] if i]
proc_dict = dict((i[0], dict(zip(keys[1:], i[1:]))) for i in proc_list)
for name, values in sorted(proc_dict.items(), key=lambda x: x[0].lower()):
print('%s: %s' % (name, values))