Use /usr/bin/env python ... why?

Erik Max Francis max at alcyone.com
Fri Jan 10 00:55:16 CET 2003


Tim Cargile wrote:

> Use '#!/python' when:

This cannot be what you really have meant.

> Use '#!env python' when:

It's unlikely that this was either.

> Oh well, at least I have not seen these:
> 
>  #!env /usr/bin/python
> 
>    and
> 
> #!/usr/bin/env /usr/bin/python
> 
> These works also, but have yet to observe them in the wild.

Because they defeat the purpose of using env in the first place.

A few points here:

You're not guaranteed that env will be in /usr/bin, although admittedly
it's pretty rare that it is not.

/usr/bin/env python searches the PATH for the first executable named
`python' and sets up the environment appropriately.  This has the
benefit of having a good chance of finding a Python interpreter, but has
the downside that you don't have much choice in which one is chosen (if
there are multiple installed on the same system).  Furthermore, which
one it finds is dependent on the PATH, and the PATH can vary quite a bit
between interactive shells, CGI scripts, and cron jobs.  For instance,
if you are in the (not uncommon) situation where a legacy interpreter is
in /usr/bin (possibly one that the installation requires, like in the
case of Red Hat) and a newer one is /usr/local/bin, you're almost
certain to find that scripts requiring the more recent interpreter will
work in interactive shells but won't work in cron jobs or CGI scripts
(because env will find the legacy interpreter, not the new one).

A slightly better way is searching for the version you want, e.g.
/usr/bin/env python2.2, but that presents its own share of problems,
namely limiting yourself in precisely which interpreter gets found (that
is, env exists to find it for you, and you're now limiting it).

A hard-coded path such as /usr/bin/python or /usr/local/bin/python is
restrictive but will be guaranteed to get what you want, should what you
want be in those locations.

As I said in another thread, there's really no "magic bullet," since
PATHs can vary from invocation to invocation.  I personally tend to
prefer /usr/local/bin/... in the bangpath simply because I default to
assuming that one has control over what's in /usr/local/bin and thus can
rely on that being more likely to be the version that is desired. 
Obviously, that can't always be true, but one can always manually change
the bangpath.  I find that the often surprising unpredictability of
using env on systems with multiple Python interpreters far outweighs the
helpfulness of having things "work out of the box."

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The great floodgates of the wonder-world swung open.
\__/ Herman Melville
    CatCam / http://www.catcam.com/
 What do your pets do all day while you're at work?  Find out.




More information about the Python-list mailing list