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:
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?
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. Theinput()
call at the end is there just to make the console window stay open so what is printed can be seen.target_script.py
: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:
Generalizing
It would also be possible to write a script that could be applied to other scripts that weren't written like
target_script
.run_func_in_module.py
:To make use of this version you would need to create a shortcut with a
Target:
set to something like:python D:\path_to_directory\run_func_in_module.py D:\another_directory\target_script.py func2
Note that the
target_script.py
would no longer need theif __name__ == '__main__':
section at the end (although having one would do no harm).