Search code examples
pythonshellterminalsubprocessgnome-shell

Python Execute Shell commands without having a terminal open


I'm writing a script that should focus a given application if its already running otherwise launch the application.

I'm using the run() method of the subprocess module to run a few shell commands to check whether an instance is currently running and if not to start a new one.

The script works perfectly fine if executed from a terminal, however isn't doing anything if launched via a keyboard shortcut from Gnome Shell.

My Question is how do I execute the shell commands without having a terminal open?

Here is a snippet of the code I use to the the shell commands:

def focus_instance_of(application):
    # Moves the window to the current desktop, raises it und gives it focus
    print("Put " + application + " in focus...")
    subprocess.run(["wmctrl", "-R", application])

Solution

  • This is how you execute commands (no shell necessary) "without having a terminal open".

    If it executes correctly from a terminal - command line, I assume - and not from the Gnome Shell, then some feature of the different environment is likely causing it to fail.

    I suggest you redirect stdout and stderr to a log file so you can start to debug this. Check for unhandled exceptions. Also check the output and return code of the wmctrl execution, it may be reporting an error.