How to handle errors?

Steve D'Aprano steve+python at pearwood.info
Fri Oct 21 01:14:41 EDT 2016


On Fri, 21 Oct 2016 11:03 am, Wildman wrote:

> On Thu, 20 Oct 2016 12:48:28 -0700, SS wrote:
> 
>> The following script works fine:
>> 
>> #!/bin/python
> 
> I meant to include this with my other post but I forgot it.
> 
> Using a direct path to the Python interpreter can cause problems
> on some systems because it is not always installed to the same
> directory.

Then you change the path and fix it.


> On my Debian-based system Python is installed in 
> /usr/bin.  So your code as written will not run on my system.
> A workaround for this is to use env in the shebang/hashbang.

That's not a work-around. That's a bug waiting to happen.

One of the problems with of env is that it will use whatever python
executable appears first in the user's $PATH, regardless of whether it is
the right Python or not -- or even whether it is actually Python, or just
some random executable file called "python". For example, you might have
compiled your own experimental Python executable, and adjusted your PATH
environment variable to find it. Now your env scripts will use your
unstable, experimental Python interpreter instead of the system Python.

Another serious problem with using env in the hash-bang line is that you
cannot pass commandline options to the Python executable.

Using env in this way is a hack that happens to mostly work. Its arguably an
abuse of env, and its not as portable as people often think (not all older
Unix systems even have env).


> For Python 2:  #!/usr/bin/env python
> For Python 3:  #!/usr/bin/env python3
> 
> It will not matter where Python is installed.  'env' will always
> know where it is.

That's not correct: env only searches the PATH, so if your python is not in
the path, it won't be found. Here's env on my system with the default PATH:

[steve at ando ~]$ /usr/bin/env python -c "import sys; print(sys.version)"
2.4.3 (#1, Jan  9 2013, 06:49:54)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)]


But if I change the search path (or if I move the Python executable
somewhere off the path):

[steve at ando ~]$ PATH="/tmp" /usr/bin/env python -c "import sys;
print(sys.version)"
/usr/bin/env: python: No such file or directory


Even if env finds something called "python", you can't be sure that it is
the right version of Python, or even Python at all. All you know is that it
is something called "python" on the search path.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list