I want to return only those applications which get listed under "Apps" category in the Windows task manager and NOT all of the running processes. The below script returns all processes which I don't want. How can I modify this code as per my requirements?
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)
You could use powershell instead of WMIC to get the desired list of applications:
import subprocess
cmd = 'powershell "gps | where {$_.MainWindowTitle } | select Description'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
if line.rstrip():
# only print lines that are not empty
# decode() is necessary to get rid of the binary string (b')
# rstrip() to remove `\r\n`
print(line.decode().rstrip())
Please note that on some systems this results in an empty table as the description seems to be empty. In that case you might want to try a different column, such as ProcessName
, resulting in the following command:
cmd = 'powershell "gps | where {$_.MainWindowTitle } | select ProcessName'
If you want to have more information, for example process id or path tidying up the output needs a bit more effort.
import subprocess
cmd = 'powershell "gps | where {$_.MainWindowTitle } | select Description,Id,Path'
proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
for line in proc.stdout:
if not line.decode()[0].isspace():
print(line.decode().rstrip())
The output of cmd
is text formatted as a table. Unfortunately it returns more than just the applications we need, so we need to tidy up a bit. All applications that are wanted have an entry in the Description column, thus we just check if the first character is whitespace or not.
This is, what the original table would look like (before the isspace()
if clause):
Description Id Path
----------- -- ----
912
9124
11084
Microsoft Office Excel 1944 C:\Program Files (x86)\Microsoft Office\Office12\EXCEL.EXE