How to get a substring from a string in python 2

I am trying to get a substring from a string, it should be specific, if
if you use this function and print it, you get a long string with all the current non-responsive processes and their information, I need the PID from a specific process.

r = os.popen('tasklist /FI "STATUS eq Not Responding"').read().strip()  
print r 

For example, if chrome.exe does not respond, it will be in the list, and I would like to get the PID associated with it. I tried split()and pop()highlight what I needed without success.

Edit:
I have 10 processes, they all have the same application name. I need to use the PID and that it belongs to the correct application. I do not want my script to kill everything either.

In short, I need to find the PID that is on the same line as the specified "process_name", and then save only the "PID"

Hope this makes sense.

+3
source share
3 answers

You can simplify your life by returning the task list to the CSV list:

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"

Using this with the module csv, you now have:

>>> 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'

I got rid of the switch /NH(No Header) to get dictionaries from the csv module.

+5
source

I believe there is a way to get only the pid of the process, but if you want to know how to extract a specific substring from a string, use regex

Sample regex for pid matching: \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)

Conclusion:

['4024']
0
source

Windows:

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

All Articles