Launch just one instance of a Qt application
Problem
I have a Qt application that I only want to run in one instance. If I forget that it’s launched and I start it again, I want the system to put the focus on the already running instance.
Solution
For more details, see this post where the used Unix commands are explained.
#!/usr/bin/env python """ Launch just one instance of an application. If the application is running, the focus is put on its window. Requires the xdotool package (sudo apt-get install xdotool). Tested under Ubuntu GNU/Linux 12.10. Author: Laszlo Szathmary (jabba.laci@gmail.com), 2013 """ __author__ = 'Jabba Laci' __appname__ = "The One and Only" __version__ = "0.1" import os import sys from PySide.QtGui import * from PySide.QtCore import * from subprocess import Popen, PIPE, STDOUT import shlex def get_simple_cmd_output(cmd, stderr=STDOUT): """Execute a simple external command and get its output. The command contains no pipes. Error messages are redirected to the standard output by default. """ args = shlex.split(cmd) return Popen(args, stdout=PIPE, stderr=stderr).communicate()[0] class OneDialog(QDialog): def __init__(self, parent=None): super(OneDialog, self).__init__(parent) self.setWindowTitle("{} {}".format(__appname__, __version__)) self.resize(300,150) #################### if __name__ == "__main__": wid = get_simple_cmd_output('xdotool search --name "{n}"'.format(n=__appname__)).strip() if wid: os.system('xdotool windowactivate {}'.format(wid)) else: app = QApplication(sys.argv) form = OneDialog() form.show() app.exec_()
If you have a better solution, let me know.
Comments (0)
Trackbacks (0)
Leave a comment
Trackback