6

So far to execute a Python program, I'm using

> python file.py

I want to run the Python script simply using file name, like

> file.py 

similar to shell scripts like

> sh file.sh
> chmod +x file.sh
> ./file.sh 

or move file.sh to bin and then run

> file.sh
Chris
1,42618 silver badges29 bronze badges
asked Mar 24, 2010 at 9:18
0

2 Answers 2

17

Put this at the top of your Python script:

#!/usr/bin/env python

The #! part is called a shebang, and the env command will simply locate python on your $PATH and execute the script through it. You could hard-code the path to the python interpreter, too, but calling /usr/bin/env is a little more flexible. (For instance, if you're using virtualenv, that python interpreter will be found on your $PATH.)

answered Mar 24, 2010 at 9:19
Sign up to request clarification or add additional context in comments.

1 Comment

You can also target specific versions with "#! /usr/bin/env python2.6" or "#! /usr/bin/env python3.0" which might be a good idea given the 2.6+ and 3.0+ split.
2

You ca also target the specific location of the python interpreter you wan to use, if you need to specify it (e.g, you're using different versions) Just add to the shebang line (the one starting with #!) the complete path of the interpreter you wan to use, for example

#!/home/user/python2.6/bin/python

But, in general, is better just to take the default using /usr/bin/env, as Mike says, as you don't have to rely on a particular path.

answered Mar 24, 2010 at 9:22

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.