Executing Python Scripts Everywhere on Your System (Unix)
Ever written a little Python script that you wanted to execute instantly without cd’ing into the folder or typing out the whole path? Me too.
I use a Mac, so the following methods should be applicable to any Unix or Linux system.
Short Version:
- Find which python you use with
which python
orwhich python3
for python3 - Copy the path and paste it at the start of the file, preceded by this: #!
Example:#! /usr/bin/python
- Make the file executable:
chmod +x tester.py
- Make a directory to put the executables in:
mkdir ~/bin/
- Move the script file in the bin folder:
mv tester.py ~/bin/
- Edit .bash_profile or .bashrc:
nano ~/.bash_profile
ORnano ~/.bashrc
- Add the folowing line:
export PATH="$PATH:$HOME/bin"
- Refresh the bash file:
source ~/.bash_profile
ORsource ~/.bashrc
- Try it. Go to any folder and type the name of your file
tester.py
Full Version with explanations:
#! Shebang it
First of all you need to add a #! Shebang line to the beginning of your Python script.
The Shebang goes at the top of your script and indicates to our system where Python is (and which version we want to use).
- Find out where python lives. Open the terminal and type:
which python
Output:/usr/bin/python
For me, this version of Python is 2.7. I want to use python 3.6, so I will execute the following command:which python3
Output:/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
- Add the path to your script. Here is my test.py script — the first line is the shebang line:
#! /Library/Frameworks/Python.framework/Versions/3.6/bin/python3
print(“If you see this, it works”)
Give it executable permissions
Run the following command in the terminal to make the script executable (make sure you are in the same directory as the file):
chmod +x tester.py
Move it in the bin folder
I created a dir in my home folder called bin (mkdir ~/bin/
) and moved my tester.py script in there:
mv tester.py ~/bin/
Make the bin folder executable
nano ~/.bash_profile
OR (if .bash_profile doesn’t exist)
nano ~/.bashrc
It will open a text editor in the terminal, add the following line at the end and press CTRL-X, then press Y and then ENTER to save and exit:export PATH="$PATH:$HOME/bin"
Now we have to re-source it for the changes to take effect:source ~/.bash_profile
OR source ~/.bashrc
Try it
Go to a random folder and type the name of your file like below:tester.py
Output:If you see this, it works
Done.
Sources
- https://stackoverflow.com/questions/6967331/how-do-i-install-a-script-to-run-anywhere-from-the-command-line?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
- https://stackoverflow.com/questions/3743812/making-python-script-accessible-system-wide?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa