Stupid question: Making scripts python-scripts

Mike Meyer mwm at mired.org
Thu Jul 21 20:20:26 EDT 2005


Bill Mill <bill.mill at gmail.com> writes:

> On 7/21/05, Jan Danielsson <jan.danielsson at gmail.com> wrote:
>> Hello all,
>> 
>>    How do I make a python script actually a _python_ in unix:ish
>> environments?
>> 
>> I know about adding:
>> #!/bin/sh
>> 
>>    ..as the first row in a shell script, but when I installed python on
>> a NetBSD system, I didn't get a "python" executable; only a "python2.4"
>> executable.
>> 
>>    Adding "#!/usr/pkg/bin/python2.4" as the first row in the script
>> would probably work, but that would be too specific for the system I'm
>> using, imho.
>> 
>>    I saw someone using "#!/usr/bin/env python", but that failed on the
>> system I'm using, so I assume that's something specific too (or is the
>> installation broken?).
>
> The env program [1], which usually exists at least on a linux system,
> executes the program given as its argument. Thus, "/usr/bin/env
> python" tries to executes python, which bash will then use to run the
> python script. As long as env exists, and python is somewhere in the
> PATH, this is a fairly portable way to run python scripts.

env doesn't invoke the shell, it uses execvp, which "duplicates the
actions of the shell in searching for an executable." Further, he's on
NetBSD - he may not have bash installed. My FreeBSD box certainly
doesn't.

> Does BSD really not come with the env program? I bet there's an
> equivalent you could symlink to it. Unfortunately, I've never BSDed,
> so I can't help you find it. To get a workable subset of the normal
> env functionality, you could try (assuming you use bash):

NetBSD comes with an env. His env is failing because he doesn't have a
"python" command installed.

This appears to be wart(?) in the NetBSD packaging system. To allow
multiple versions of FreeBSD to coexist, it doesn't install a "python"
command at all, but instead leaves the versioned one around.

Two solutions: have your scripts use #!/usr/pkg/bin/python2.4. That
way, when you install a new python, they will keep using the old
one. That will insure they won't break when you upgrade.

However, such breakage is pretty rare in practice. I'd pick a favorite
bin directory and symlink from python there to /usr/pkg/bin/python2.4,
then use "#!/usr/bin/env python" in your scripts.

While I'm on the topic, I think I'll share my favorite cool trick.

      #!/usr/opt/bin/mypythonscript

Doesn't work because Unix won't let you use an interpreted script as
the interpreter (is this true for all variants?). However,

    #!/usr/bin/env mypythonscript

works like a charm.

      <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list