Python: Getting the title of windows, getting their processes and their commandlines using ctypes and win32

My latest assignment for Commie was to create a plugin for xchat to list running encoding processes in the staff IRC channel. You can write plugins in a few various languages and me knowing a little bit of Python I chose to do it that way.

The problem I was facing was to find all windows of x264, fetch their titles (which included how far the encoding was, time remaining etc), and output each title to the channel when a user would say “.encoding”.  Easy enough, I thought, I’ll just fetch all processes and check if “x264” is in the title. I found some methods and code snippets using pywin32 (win32gui, included in pywin32). Unfortunately, xchat only supports Python 2.6 (which is a rather old version of Python) and the windows installer for pywin32 for Python 2.6 is broken and I didn’t manage to compile from source either, so I had to find an alternate way of doing it without any libraries.

Luckily, I found a way of getting all windows titles using ctypes (which is included in Python by default) and the win32 API (thanks to this blog post). It worked really well and from there I managed to easily get the titles I wanted and send them to the IRC channel. Unfortunately, the titles didn’t contain what was encoding, so it would be pretty useless to know that something is 50% done.

Looking around a bit, I managed to find a way to get what was being encoded. The commandline of the process that started the encoding included the directory name of what was encoding. Now I needed to somehow fetch the commandline, but I only had a window and not a process. Having the window I obviously had the window handle. By reading some documentation I found the GetWindowThreadProcessId, which returns a process id from a window handle. Now that I have that, how do I easily get the CommandLine? The easiest way I could figure out was to use WMIC, a commandline interface to WMI (a type of query language to fetch various stuff from the OS, something in the lines of that). From this on it was only some formatting left to do. Below is the full code. Hopefully others can use it to understand how it works, as I had some troubles searching for the right way to do this (all thought it may be a rare thing to do).