icyrock.com

Home

GNOME experiments - list active windows and applications using Python

2016-Nov-30 21:50
gnome-experimentspython

GNOME API for Python is called PyGObject. It uses GOBject Introspection to provide access to underlying C libraries that GNOME is based on. PyGObject (or PyGI) API reference can be found here.

In Python, importing gi module provides all needed functionality. This is done in three steps:

For example, here's how we can import Wnck 3.0 module:

1
2
3
import gi
gi.require_version('Wnck', '3.0')
from gi.repository import Wnck

In order to get the windows, we need to get the screen and, since we are using the API synchronously, force the update to get the information filled in:

1
2
3
screen = Wnck.Screen.get_default()
screen.force_update()
windows = screen.get_windows()

After that, it's a simple loop to get the application for each window:

1
2
3
output = []
for window in windows:
  application = window.get_application()

and to get some sample information in the output list:

1
2
3
4
5
6
e = (application.get_xid(),
  application.get_name(),
  application.get_pid(),
  window.get_name())
 
output.append(e)

Finally, print it:

1
2
for e in sorted(output):
  print('%8d %30.30s %6.6s %30.30s' % e)

Sample result:

1
2
3
4
20971521               GNOME Tweak Tool  10900               GNOME Tweak Tool
23068673                       Terminal   2152                [No Name] - VIM
37748737                LibreOffice 5.2  10969  Untitled 1 - LibreOffice Calc
41943042        New Tab - Google Chrome   2352        New Tab - Google Chrome

Note that the application name is found using heuristics, so it is possible it is not accurate, see Application.get_name documentation.

Complete code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import gi
gi.require_version('Wnck', '3.0')
from gi.repository import Wnck
 
screen = Wnck.Screen.get_default()
screen.force_update()
windows = screen.get_windows()
 
output = []
for window in windows:
  application = window.get_application()
 
  e = (application.get_xid(),
    application.get_name(),
    application.get_pid(),
    window.get_name())
 
  output.append(e)
 
for e in sorted(output):
  print('%8d %30.30s %6.6s %30.30s' % e)