tags:

views:

106

answers:

2

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
+14  A: 

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.)

Mike Mueller
*and* you should set the executable bit: `chmod u+x file.py`...
Boldewyn
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.
Michael Aaron Safyan
+2  A: 

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.

Khelben