How to get wmctrl output in python

How can I get the output of the terminal code "wmctrl -m"

$ wmctrl -m
Name: GNOME Shell
Class: N/A
PID: N/A
Window manager's "showing the desktop" mode: ON

in python code? I don't know how to invoke that command in a skript. The purpose is, I want to get the value of mode:ON or mode:OFF.

Right now I only imported wmctrl

import wmctrl

and then?

2 Answers

You can either use a subprocess-style way of forking out (essentially running a command and parsing the output) or you can use the wmctrl package properly:

In [1]: from wmctrl import Window
In [2]: Window.get_active()
Out[2]: Window(id='0x07000062', desktop=0, pid=1878, x=657, y=299, w=1042, h=769, wm_class='terminator.Terminator', host='bert', wm_name='oli@bert: ~', wm_window_role='')

There isn't much in the way of documentation, so I'd suggest running help(Window) if you want to know more... Or just look at the source for the class.

In the meantime i figured out how to get the output:

import wmctrl
import subprocess as s
p=s.Popen(["wmctrl","-m"], stdout=s.PIPE)
out, err = p.communicate()
print(out)
if "mode: ON" in str(out): print("Desktop is shown")
if "mode: OFF" in str(out): print("Desktop is not shown")

Now another strange thing occurs, try it out (this code runs):

Run it, watch the printed output.

Then show the desktop.

Run again.

The output changed to "Desktop is shown", as expected.

Click again on "show desktop" icon in the launcher and run the code again.

You see windows, thus the Desktop is NOT shown, but still the output is "Desktop is shown". So it is kind of useless...

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like