Run Python scripts without explicitly invoking `python`

There are two things you need to do:

  • Make sure the file is executable: chmod +x script.py
  • Use a shebang to let the kernel know what interpreter to use. The top line of the script should read:

    #!/usr/bin/python
    

    This assumes that your script will run with the default python. If you need a specific version, just specify in the shebang:

    #!/usr/bin/python2.7
    

Now you can type:

    ./script.py

if the script is in your current directory, or:

    script.py

if the location of the script happens to be in your PATH, or:

    path/to/script.py

otherwise.


Under linux you can simply use the hashbang(aka shebang). Add the line

#!/usr/bin/python

if you want to execute the default python interpreter.

#!/path/to/python[x.x]

to use some specific version, or

#!/usr/bin/env python

If you want the environment to find python for you.

You will also be required to make the script executable

chmod +x script[.py] 

Use:

#!/usr/bin/env python

This will ensure that the python the user expects to be used will be the one that runs the script. This is especially important if the user is using virtualenv to have a specific version of python in a given environment.

Tags:

Python

Linux