如何从python 2中的字符串中获取子字符串

时间:2014-02-20 05:31:48

标签: python windows string list python-2.7

我正在尝试从字符串中获取子字符串,但它必须具体,但是 如果您使用此功能并打印它,您将获得一个包含所有当前无响应进程及其信息的长字符串,我需要来自特定进程的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'

希望这是有道理的。

3 个答案:

答案 0 :(得分:5)

您可以通过让任务列表以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开关(No Header)以从csv模块中获取字典。

答案 1 :(得分:0)

我认为有一种方法只能获取进程pid,但是如果你想知道如何从字符串中提取特定的子字符串,请使用正则表达式

与pid匹配的正则表达式模式:\w+\.\w+\s+(\d+)\s

import os
import re

r = os.popen('tasklist /FI "STATUS eq Not Responding"').read().strip()
print re.findall('\w+\.\w+\s+(\d+)\s',r)

输出:

['4024']

答案 2 :(得分:0)

基于How to extract a specific field from output of tasklist on the windows command line

print os.popen('for /f "tokens=2 delims=," %F in (\'tasklist /nh /fi "STATUS eq Not Responding" /fo csv\') do @echo %~F').read().strip()