2 years ago
#24706

Mark Boucher
How do I get the `for` loop to not stop after an os command?
I automate a process with Task Scheduler that occasionally leaves EXCEL.EXE processes hung in the background and these interfere with future processes. I found a way to list these to a file with a .bat
code. The scheduled task starts code that calls a .vbs
file that executes a macro in Excel
. So Task Scheduler can't be set up to cancel the process (PID) if it hangs.
tasklist /V /FO csv /FI "IMAGENAME eq EXCEL.EXE" > C:\[path]\Exceltasks.csv
creates...(example)
"Image Name","PID","Session Name","Session#","Mem Usage","Status","User Name","CPU Time","Window Title"
"EXCEL.EXE","62020","Console","1","622,528 K","Running","[network]\[user]","0:03:31","Work Record.xlsx - Excel"
"EXCEL.EXE","47536","Console","1","78,760 K","Running","[network]\[user]","0:00:00","N/A"
"EXCEL.EXE","61472","Console","1","620,752 K","Running","[network]\[user]","0:03:38","N/A"
"EXCEL.EXE","54156","Console","1","358,648 K","Not Responding","[network]\[user]","0:00:20","HardwareMonitorWindow"
"EXCEL.EXE","54604","Console","1","77,180 K","Running","[network]\[user]","0:00:00","N/A"
"EXCEL.EXE","45948","Console","1","368,400 K","Running","[network]\[user]","0:00:24","Publishing..."
Then I have this python script that will run through that file and uses taskkill
to clear them out.
import csv
import os
FindValue = "EXCEL.EXE"
Substring = "- Excel"
with open("C:/[path]/Exceltasks.csv") as f:
reader = csv.reader(f)
for row in reader:
if (row[0]=="INFO: No tasks are running which match the specified criteria."):
print ("No " + FindValue + " processes running")
break
else:
print ("Check PID" + row[1])
if(row[0]==FindValue):
if(row[8].find("- Excel")!=-1):
print("Don't kill task " + row[1])
else:
Killstring = "taskkill /F /PID " + row[1]
print Killstring
os.system('cmd /k '+ Killstring)
The first if
will break
out if there are no EXCEL.EXE processes.
The second if
works, but only on the first of what is often 3+ EXEL.EXE processes.
How do I get the for
loop to not stop after the first os
taskkill
command?
python
for-loop
cmd
operating-system
taskkill
0 Answers
Your Answer