I'm trying to get a substring from a string, it has to be specific though,
if you use this function and print it you'd get a long string with all the currently unresponsive processes and their infos, I need the PID from a specific process.
r = os.popen('tasklist /FI "STATUS eq Not Responding"').read().strip()
print r
example if chrome.exe is not responding it would be in the list and I would like to get the PID associated with it. I tried split() and pop() to single out what I needed without success.
Edit :
I have 10+ processes that all share the same application name.
It's necessary for me to use PID and that it belongs to the correct application. I don't want my script to kill everything either.
So in short I need to find the PID that is on the same row as the specified 'process_name' and then only keep that 'PID'
Hope that makes sense.
You can simplify your life by having tasklist return to you the list as a 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"
Exploiting this with the csv module, 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 /NH switch (No Header) to get dictionaries from the csv module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With