Why use #!/usr/bin/env python rather than #!python?

Donn Cave donn at u.washington.edu
Fri Dec 2 12:29:58 EST 2005


In article <mailman.1501.1133532746.18701.python-list at python.org>,
 Adriano Ferreira <a.r.ferreira at gmail.com> wrote:

> Hey, that's not fair. In your illustration above, does 'python' can be
> found in the PATH? That is,
> 
> $ python /tmp/hello.py
> 
> works? If it does, probably
> 
> #!/usr/bin/python
> #!/usr/bin/env python
> #!python
> 
> would also work if
> (1) 'python' is at '/usr/bin/python' (but that's inflexible)
> (2) 'python' can be found in the environment variable path (if 'env'
> is at '/usr/bin/env')
> (3) 'python' can be found in the environment variable path (no need
> for 'env' utility)

Contrary to popular belief, #! is not intended for the shell,
but rather for the execve(2) system call of the UNIX operating
system.  These two characters form the 16 bit "magic number"
of interpreter files.  Any executable file must start with a
16 bit field that identifies it so the operating system will
know how to execute it.

In the case of a #! interpreter file, the operating system
expects the rest of that line to be the path to the file.
PATH is not searched, and is irrelevant.  The only way
#!python can work, is if it's in the current working directory.

Just to help make it confusing, when this mechanism fails
and execve(2) returns an error, most shells will go on to
try to execute the file themselves, regardless of whether
there's a #! or not.  csh (the shell language that doesn't
look anything like C, Bill Joy's attempt at language design
before he started over with Java) does that only if the first
line is "#"; otherwise it invokes the Bourne shell.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list