How to run python script as global command from any terminal instance similar to pip or howdoi command?

Viewed 279

Problem to solve

I have a python script called myscript.py in a directory.
To run myscript.py, I have to open terminal in the same directory and do python myscript.py or python path_to_the_py_file

What I want to achieve

I can open a instance of terminal anywhere, anytime and do myscript or myscript arguments -options. By doing this, I should be able to run the script.

I want to implement something like pip command or the howdoi package.


When I enter myscript in terminal I should not get:
myscript: The term 'myscript' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.



If you have any confusion please ask in comments. if the title needs improvement, feel free to edit the question.

1 Answers

There seems to be quite a few things in this question.

First, you want to make you file executable.

chmod +x /path/to/your/script.py

Then, since this is an interpreted language, you’ll have to specify the interpreter in a shebang at the top of the file.

#!/usr/bin/env python

OR

#!/usr/bin/env python3

Finally, you’ll have to put it in your PATH environment variable, which can be done in a variety of ways, simplest might be symlink in ~/bin or ~/.local/bin, depending on what you have.

Also, this will make script.py available as an executable, you can rename it or rename its symlink to just script if you don’t want .py.

Related