I wanted to be able to detect in a python program if it was already running (pygtk) and bring it to the front if so. Thought this code could be useful to others:
#!/usr/bin/env python2.6 import sys, re, subprocess as sp, os if __name__ == "__main__": program_name = os.path.basename(sys.argv[0]) window_title_starts_with = 'My Application' # Change to the window title of your application p = sp.Popen([ '/usr/bin/pgrep', program_name ], stdout = sp.PIPE) out = p.communicate()[0] if p.returncode == 0: p = sp.Popen([ '/usr/bin/wmctrl', '-lp' ], stdout = sp.PIPE) out = p.communicate()[0] if p.returncode == 0: result = [ a[0] for a in [ re.split('\s+', l, 4) for l in re.split('\n', out) ] if len(a) == 5 and a[4].startswith(window_title_starts_with) ] if len(result): print 'Application is already running, bringing to front' sp.check_call([ '/usr/bin/wmctrl', '-ia', result[0] ]) sys.exit(0)
Note that paths are the ones used by Ubuntu. Requires pgrep and wmctrl to be installed.
© Copyright 2009 - Andrew Robinson.
Please feel free to use in your applications under the LGPL license (http://www.gnu.org/licenses/lgpl.html).