5

I was wondering if it is possible to create a keyboard shortcut to run application if it is not yet running in Ubuntu?

This is a valid example for something like a browser which is normally heavily used, and you wouldn't really want to run another instance of it if there is one running already (rather just activate the window).

Leonid
  • 264

2 Answers2

4
  1. Save the following script to your home folder as launch_chrome.py:

    #!/usr/bin/env python
    
    import subprocess
    import wnck
    import gtk
    import time
    
    
    screen = wnck.screen_get_default()
    while gtk.events_pending():
        gtk.main_iteration()
    
    window_list = screen.get_windows_stacked()
    
    last_active = None
    for window in window_list:
        if window.get_application().get_name() == "Google Chrome":
            last_active = window
    
    if last_active:
    
        timestamp = int(time.time())
        last_active.activate(timestamp)
    
    else:
    
        subprocess.Popen("google-chrome")
    
  2. Make the script executable:

    chmod +x ~/launch_chrome.py
    
  3. Use the command /home/<YOURUSERNAME>/launch_chrome.py when adding a shortcut.

When this shortcut is activated, it will either:

  1. Launch a new Chrome window if there aren't any already running or,
  2. bring the most recently used Chrome window into focus.
Isaiah
  • 59,344
3

In Ubuntu there is a package called run-one that is close to what you ask.

I report the description:

 This utility will run just one instance at a time of some command and
 unique set of arguments (useful for cronjobs, eg).

Regarding the keyboard shortcut, see here How to use a hotkey shortcut to run a launcher?.

Regarding the "if there is one running already, just activate the window", I don't know. Not all applications have a window, they may have zero or more than one window. And even in the case of a single window, I don't know of a simple way to map a process to its window.

enzotib
  • 93,831