0

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])
Treborium
  • 23
  • 4

2 Answers2

1

You can add the keyword argument shell=True, this will spawn a shell in the background to run the command (but not open the terminal window).

subprocess.run(["wmctrl", "-R", application], shell=True)
Edward Minnix
  • 2,889
  • 1
  • 13
  • 26
  • The fact that the script is working correctly when launched from the CLI suggests the problem is not the absence of a shell. Moreover, there's no reason why `wmctrl` would require a shell. – Dun Peal Jun 19 '18 at 12:48
1

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.

Dun Peal
  • 16,679
  • 11
  • 33
  • 46