Get list of running windows applications using python
Asked Answered
K

3

7

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)
Knowling answered 22/2, 2019 at 13:10 Comment(0)
P
8

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())

Getting an empty table?

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'

Need more columns/information in the output?

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
Polydeuces answered 22/2, 2019 at 19:8 Comment(2)
if i wanted to close one of those programs using python how would i be able to do that?Broadway
@Shavow, check my answer below. You only have to add 'for win in windows: win.close() 'Nariko
C
3

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
Cockneyism answered 20/6, 2022 at 23:44 Comment(0)
N
0

@JerryT answer is totally right.

Just for other users trying to accomplish something similar, PyWinCtl has a function which allows to retrieve windows with a given title only called getWindowsWithTitle(), so the code can be even simpler:

import pywinctl as pwc
from time import sleep

    mytitle = 'notepad'
    while True:
        windows = pwc.getWindowsWithTitle(mytitle, condition=pwc.Re.CONTAINS, flags=pwc.Re.IGNORECASE)
        if not windows:
            break
        print('Waiting for current window to be closed...')
        sleep(3)

In addtion to that, PyWinCtl has a feature which allows to watch a window status in a separate thread, so your script can do other stuff in the mean time (e.g. if your script is inside a UI loop when using PyQt, Tkinter or similar), not getting blocked into a while loop, like this:

import time

import pywinctl as pwc
from time import sleep


def isAliveCB(isAlive: bool):
    print("WINDOW HAS BEEN CLOSED")


# For this example, notepad must be open before the script starts
mytitle = 'notepad'
windows = pwc.getWindowsWithTitle(mytitle, condition=pwc.Re.CONTAINS, flags=pwc.Re.IGNORECASE)
for win in windows:
    print(win.title)
    win.watchdog.start(isAliveCB=isAliveCB)

# Continue with your script stuff or a UI loop
while True:
    try:
        print("I KEEP DOING THINGS")
        time.sleep(2)
    except KeyboardInterrupt:
        break
Nariko answered 22/9, 2024 at 9:7 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.