Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python source header comment

What is the line

#!/usr/bin/env python

in the first line of a python script used for?

like image 293
Alex Avatar asked Apr 01 '09 20:04

Alex


4 Answers

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
like image 112
vartec Avatar answered Sep 22 '22 08:09

vartec


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:

like image 45
Paolo Bergantino Avatar answered Sep 25 '22 08:09

Paolo Bergantino


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

like image 35
andri Avatar answered Sep 24 '22 08:09

andri


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.

like image 33
hughdbrown Avatar answered Sep 24 '22 08:09

hughdbrown