What is the line
#!/usr/bin/env python
in the first line of a python script used for?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With