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
For cross-platform solutions, now you can use pywinctl
or pygetwindow
. pywinctl
is a fork of pygetwindow
with enhancement in MacOS and Linux environments. Sample codes below:
import pywinctl as pwc
from time import sleep
mytitle = 'notepad'
while True:
try:
titles = pwc.getAllTitles()
if mytitle not in titles:
break
print('Waiting for current window to be closed...')
sleep(3)
except KeyboardInterrupt:
break
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