views:

982

answers:

6

What is the line

#!/usr/bin/env python

in the first line of a python script used for?

+5  A: 

Under UNIX and similar operating systems, this line tells which interpreter is to be used if the file is executed.

andri
-1: Forgot the reference material: http://en.wikipedia.org/wiki/Shebang_(Unix)
S.Lott
not to be confused with http://en.wikipedia.org/wiki/She_Bangs
Pete Kirkham
Pete... you just made my day.
Jarret Hardie
+13  A: 

This is called a shebang line:

In computing, a shebang (also called a hashbang, hashpling, or pound bang) refers to the characters "#!" when they are the first two characters in a text file. Unix-like operating systems take the presence of these two characters as an indication that the file is a script, and try to execute that script using the interpreter specified by the rest of the first line in the file. For instance, shell scripts for the Bourne shell start with the first line:

Paolo Bergantino
For instance, shell scripts for the Bourne shell start with the first line:link|offensive?
Dan
... `#!/bin/bash`.
Xiong Chiamiov
+2  A: 

'/usr/bin/env python' searches $PATH for python and runs it.

Usually env is used to set some environment variables for a program

What that line does is tell your computer what to do with that file, if you simply try to run the file without specifying an interpreter.. more detail

TStamper
+16  A: 

In UNIX and Linux this tells which binary to use as an interpreter (see also Wiki page). For example shell script is interpreted by /bin/sh.

#!/bin/sh

Now with python it's a bit tricky, because you can't assume where the binary is installed, nor which you want to use. Thus the /usr/bin/env trick. It's use whichever python binary is first in the $PATH. You can check that executing which python

With the interpreter line you can run the script by chmoding it to executable. And just running it. Thus with script beginning with

#!/usr/bin/env python

these two methods are equivalent:

$ python script.py

and (assuming that earlier you've done chmod +x script.py)

$ ./script.py


This is useful for creating system wide scripts.

cp yourCmd.py /usr/local/bin/yourCmd
chmod a+rx /usr/local/bin/yourCmd

And then you call it from anywhere just with

yourCmd
vartec
+4  A: 

As Andri said. In Windows, the executable to run a file with when launched from the command line relies on an association:

16:12:40.68 C:\>assoc .py
.py=Python.File

16:13:53.45 C:\>assoc Python.File
Python.File=Python File

16:14:01.70 C:\>ftype Python.File
Python.File="C:\Python30\python.exe" "%1" %*

In Unix, the shell interpreter makes the inference by opening the file and seeing if there is a command named in the file.

hughdbrown
Always useful for those days I work on a windoze box.
Christian Witts
+2  A: 

Just a note, this line is nothing more then a comment to the interpreter in Windows.

jcoon
it is also nothing more than a comment to the interpreter in unix
hop