Home > python, Qt, ubuntu > Launch just one instance of a Qt application

Launch just one instance of a Qt application

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.

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__))


if __name__ == "__main__":
    wid = get_simple_cmd_output('xdotool search --name "{n}"'.format(n=__appname__)).strip()
    if wid:
        os.system('xdotool windowactivate {}'.format(wid))
        app = QApplication(sys.argv)
        form = OneDialog()

If you have a better solution, let me know.

Categories: python, Qt, ubuntu
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: