Run Python script using a hotkey when a specific program is active

71 Views Asked by At

Intended setup:

  • Have .py script saved locally
  • Run required program
  • Use program normally until the need for the script arises
  • Press hotkey that tells Windows to run the python script
  • Close program when the script + my work is done
  • Hotkey should not run the script anymore unless the program is opened again

Till now I've always manually run the script and quickly Alt+Tab'ing into the program before the script manages to start executing, but it's kind of a hassle. What's the general approach to do something like this?

OS: Windows

UPDATE: A method has been found. Though I'm keeping this thread active in case there are better options.

1

There are 1 best solutions below

0
SpectraXCD On

Using AutoHotKey, e.g. setting Ctrl+F5 to run script.py when Window Name is active:

#Requires AutoHotkey v2.0
#SingleInstance

^f5::
{
    if WinActive("Window Name")
        Run "{your script path}\script.py"
}

Optional-1: If you want to run script in background (i.e. without console window appearing) rename your script.py to script.pyw

Optional-2: If you want to run your script with admin privileges without triggering UAC prompt (the admin yes/no prompt), watch this for bypassing UAC prompt and this for running any python scripts with task scheduler.

For the latter video, you will notice the script still runs in foreground (with console window). To prevent this, just type pythonw.exe instead of python.exe when you are filling the 'Program/script:' field.