我正在尝试从字符串中获取子字符串,但它必须是特定的,
如果你使用这个函数并打印它,你会得到一个长字符串,其中包含所有当前无响应的进程及其信息,我需要来自特定进程的 PID。
r = os.popen('tasklist /FI "STATUS eq Not Responding"').read().strip()
print r
例如,如果 chrome.exe 没有响应,它将出现在列表中,我想获取与其关联的 PID。我尝试了 split()
和 pop()
来挑出我需要的东西,但没有成功。
编辑:
我有 10 多个进程都共享相同的应用程序名称。
我有必要使用 PID 并且它属于正确的应用程序。我也不希望我的脚本杀死一切。
所以简而言之,我需要找到与指定的“process_name”在同一行的 PID,然后只保留该“PID”
希望这是有道理的。
您可以通过让任务列表以 CSV 格式返回列表来简化您的生活:
C:\>tasklist /FI "STATUS eq Not Responding" /FO CSV /NH
"jusched.exe","3596","Console","1","13,352 K"
"chrome.exe","4760","Console","1","181,088 K"
"chrome.exe","3456","Console","1","119,044 K"
"chrome.exe","2432","Console","1","24,236 K"
"chrome.exe","440","Console","1","36,420 K"
"chrome.exe","4964","Console","1","60,596 K"
"chrome.exe","3608","Console","1","21,924 K"
"chrome.exe","4996","Console","1","22,348 K"
"chrome.exe","2580","Console","1","38,432 K"
"chrome.exe","3312","Console","1","32,756 K"
"chrome.exe","4600","Console","1","36,072 K"
"chrome.exe","4180","Console","1","24,436 K"
"chrome.exe","4320","Console","1","31,152 K"
"chrome.exe","4120","Console","1","22,632 K"
利用 csv
模块,您现在拥有:
>>> r = os.popen('tasklist /FI "STATUS eq Not Responding" /FO CSV')
>>> import csv
>>> reader = csv.DictReader(r, delimiter=',')
>>> rows = list(reader)
>>> rows[0]
{'Session Name': 'Console', 'Mem Usage': '13,352 K', 'PID': '3596', 'Image Name'
: 'jusched.exe', 'Session#': '1'}
>>> rows[0]['PID']
'3596'
我摆脱了 /NH
开关(无 header )以从 csv 模块获取字典。