36

I'm using Debian Linux.

I was wondering if there was a way to configure to run all Python scripts in the terminal by typing script.py (instead of python script.py).

56

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.

  • 32
    Generally it's a better idea to use #!/usr/bin/env python, in case the user has a local build of python (eg, in /usr/local/bin) which they'd rather run the script with. – sapi Oct 20 '14 at 3:30
  • 3
    @sapi Not according to Debian it isn't, at least in their dev policies. If you are writing your own scripts, you can accept the risk of course, it is just better to be explicit. If you want the local one, choose it in the shebang. – Paul Oct 20 '14 at 4:12
  • 3
    It's not bash that reads the file when executing... – souser12345 Oct 20 '14 at 5:52
  • @progo This is true - note that if you see an answer that you think would benefit from improvement, go ahead and edit it, improvements are always welcome – Paul Oct 20 '14 at 9:24
  • And you'll have to do ./script.py, not script.py – Paul Draper Oct 21 '14 at 12:56
32

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] 
1

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.

0

Use a shebang line at top of your script as below:

!/usr/bin/python

Update appropriate python version on which you want to execute the script. e.g. For python 3.6 its

!/usr/bin/python3.6

for default interpreter

!/usr/bin/python

Note: Make sure script has executable permission.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.