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.

This is being achieved by involving an external tool (windowlist.exe). (An alternative is to use tasklist.exe which is shipping with Windows, but tasklist.exe does not list all windows unfortunately.)

import subprocess

def main():
    pids = get_pids_for_title("Internet Explorer")
    pids = get_pids_for_process_name("iexplore.exe")

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)
    stdout = p.communicate()[0]
    last_pid = None
    pids = []
    for l in stdout.split("\r\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)
    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

Requirements:

Related Information: