How would I use Python to determine what programs are currently running. I am on Windows.
Thanks to @hb2pencil for the WMIC command! Here's how you can pipe the output without a file:
import subprocess
cmd = 'WMIC PROCESS get Caption,Commandline,Processid'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
print line
import os
os.system('WMIC /OUTPUT:C:\ProcessList.txt PROCESS get Caption,Commandline,Processid')
f = open("C:\ProcessList.txt")
plist = f.readlines()
f.close()
Now plist contains a formatted whitespace-separated list of processes:
This should be simple to parse with python. Note that the first row of data are labels for the columns, and not actual processes.
Note that this method only works on windows!
Piping information from sub process commands is not ideal compared to an actual python tool meant for getting processes. Try the psutil module. To get a list of process numbers, do:
psutil.get_pid_list()
I'm afraid you have to download this module online, it is not included in python distributions, but this is a better way to solve your problem. To access the name of the process you have a number for, do:
psutil.Process(<number>).name
This should be what you are looking for. Also, here is a way to find if a specific process is running:
def process_exists(name):
i = psutil.get_pid_list()
for a in i:
try:
if str(psutil.Process(a).name) == name:
return True
except:
pass
return False
This uses the name of the executable file, so for example, to find a powershell window, you would do this:
process_exists("powershell.exe")
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