Getting PIDs for window titles, executables on Windows

Last edited on

This example shows how to retrieve a list of windows and the PIDs of their processes on Windows. It is written for Python 3.

This is achieved using an external tool, ( windowlist.exe ) which must be placed in the folder of the test suite. (An alternative is to use tasklist.exe, which ships with Windows - but it does not list all windows.)

Wildcards such as * are not supported — they're matched as literal characters, not as pattern placeholders. Instead, matching works by simple substring: the text you pass in just needs to appear somewhere inside the actual window title or process name, not match it exactly. For example, "Address Book" will match a window titled Address Book - Unnamed, but "Address Book *" will fail to match unless that literal asterisk is actually present in the title.

# -*- coding: utf-8 -*-

import subprocess

def main():
    
    pids = get_pids_for_window_title("Address Book")
    test.log(str(pids))
    pids = get_pids_for_process_name("Addressbook.exe")
    test.log(str(pids))

def get_pids_for_window_title(window_title_excerpt):
    p = subprocess.Popen(
        args=squishinfo.testCase + "/../windowlist",
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True)
    stdout = p.communicate()[0]
    last_pid = None
    pids = []
    for l in stdout.split("\n"):
        if l.startswith("PID: "):
            last_pid = l[5:]
            continue
        elif l.startswith("Window Title: ") \
                and not last_pid in pids:
            t = l.split(": ", 1)[1]
            if window_title_excerpt in t:
                pids.append(last_pid)
    return pids

def get_pids_for_process_name(process_name_excerpt):
    p = subprocess.Popen(
        args=squishinfo.testCase + "/../windowlist.exe",
        shell=True,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True)
    stdout = p.communicate()[0]
    last_pid = None
    pids = []
    for l in stdout.split("\n"):
        if l.startswith("PID: "):
            last_pid = l[5:]
            continue
        elif l.startswith("Process Name: ") \
                and not last_pid in pids:
            n = l.split(": ", 1)[1]
            if process_name_excerpt in n:
                pids.append(last_pid)
    return pids
test.py

Related Information: