How can I count number of Window with specific title on Linux by Python?

Here is my solution, but I think it's not a good one. Can anybody suggest me new solution, I want to enumarize windows, and get the Title property to compare by just using core library of python , not wnck or pygtk ...

def linux_CountWindowsByTitle(title):
    import commands
    XWinInfoOutput = commands.getoutput("xwininfo -all -root")
    resArray = XWinInfoOutput.split("\n")
    resRange = len(resArray) - 1
    res = 0
    #Parse each line of output
    for i in range(0, resRange):
        index = resArray[i].find("\"")   #Get index of Double quote
        if (index < 0):
            continue    #This line does not have title we need

        tmp = resArray[i].split("\": (")[0] #Remove tail
        windowName = tmp.split("\"",1)[1]   #Remove head
        if (UTILITY.Compare(title, windowName)):
            res += 1

    return res


You can use the module wnck.

import wnck

screen = wnck.screen_get_default()
window_list = wnck.Screen.get_windows(screen)

window_names = [ w.get_name() for w in window_list ]

In order to count the similar windows, you can create a dictionary:

count = window_names.count
wcounts = { item: item.count(item) for item in set(window_names) }

Where the dictionary will have as key the window title and the value will be the number of times the same name is repeated.

Slightly different, but you might find interesting to use is:

wdict = { w.get_name(): w for w in window_list }

If you need the window later to other processing, you still have a reference handy in the wdict. For instance, you can check properties, maximize it, minimize, and all typical operations that a window manager would do.

Note: For newer versions of wnck (>=3.0) you have to use PyGObject (GObject Introspection), but you get the idea.

Posted on by gpoo