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:

  1. Find which python you use with which python or which python3 for python3
  2. Copy the path and paste it at the start of the file, preceded by this: #!
    Example: #! /usr/bin/python
  3. Make the file executable:
    chmod +x tester.py
  4. Make a directory to put the executables in:
    mkdir ~/bin/
  5. Move the script file in the bin folder:
    mv tester.py ~/bin/
  6. Edit .bash_profile or .bashrc:
    nano ~/.bash_profile OR nano ~/.bashrc
  7. Add the folowing line:
    export PATH="$PATH:$HOME/bin"
  8. Refresh the bash file:
    source ~/.bash_profile OR source ~/.bashrc
  9. 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).

  1. 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
  2. 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