Question

What is the line

#!/usr/bin/env python

in the first line of a python script used for?

Was it helpful?

Solution

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

OTHER TIPS

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:

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

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.

'/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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top