Home > database >  How to make a Windows shortcut to run a function in a Python script?
How to make a Windows shortcut to run a function in a Python script?

Time:07-04

I am trying to find a way to create a Windows shortcut that executes a function from a Python file. The function being run would look something like this (it runs a command in the shell):

def function(command):
    subprocess.run(command, shell = True, check = True)

I am aware that you can run cmd functions and commands directly with a shortcut, but I would like it to be controlled by Python.

I have little experience working with Windows shorcuts, so the best I can do is show you the following:

screenshot of shortcut properties dialog box

This is what I imagine it would like like.

After a quick Google search, the only help I can find is how to make a shortcut with Python, not how to run a function from it. So hopefully what I am asking is even possible?

CodePudding user response:

Generally speaking AFAIK, you can't do it, however it could be done if the target script is written a certain way and is passed the name of the function to run as an argument. You could even add arguments to be passed to the function by listing them following its name in the shortcut.

The target script has to be set up with an if __name__ == '__main__': section similar to what is shown below which executes the named function it is passed as a command line argument. The input() call at the end is there just to make the console window stay open so what is printed can be seen.

target_script.py:

def func1():
    print('func1() running')

def func2():
    print('func2() running')


if __name__ == '__main__':

    from pathlib import Path
    import sys

    print('In module', Path(__file__).name)

    funcname = sys.argv[1]
    vars()[funcname]()  # Call named function.

    input('\npress Enter key to continue...')

To make use of it you would need to create a shortcut with a Target: set to something like:

python D:\path_to_directory\target_script.py func1

Output:

In module target_script.py
func1() running

press Enter key to continue...
  • Related