argv[0] manipulation

Bernhard Herzog bh at intevation.de
Sat Dec 14 11:55:13 EST 2002


"James Kew" <james.kew at btinternet.com> writes:

> "Bernhard Herzog" <bh at intevation.de> wrote in message
> news:6qpts5epgw.fsf at salmakis.intevation.de...
> > sys.argv[0] [...] must be the filename of the script in such a way that
> passing it
> > open opens the correct file.
> 
> Don't rely on this being portable: the sys module documentation
> (http://www.python.org/doc/current/lib/module-sys.html) makes no such
> guarantees about sys.argv[0].

Then the documentation is wrong, or at least misleading :)

Let's assume the simple case of a script that lies somewhere in $PATH
and that use the hash-bang machinery to invoke python. E.g. it starts with

#! /usr/bin/python

When that script is invoked without arguments python is started with
something like

/usr/bin/python /path/to/script

What's uncertain about that is the first item which might be simply
"python" (and on Linux that's indeed what it is IIRC) and the exact
contents of the second item. In any case the second item must be the
name of the file in such a form that it can be passed to open() to open
the file otherwise the python interpreter could not execute the script.

In the case described above, sys.argv will be ["/path/to/script"] (or
whatever was supplied as the second item) because python simple copies
all command line arguments it did not parse itself to sys.argv. I'm not
sure whether its documented that python does ineed not modify those
argument, though.

As the documentation mentions there are cases where sys.argv[0] is not a
filename, e.g. when the interpreter is started with the -c option or in
interactive mode when started without a filename argument.

I think what the documentation really wants to warn about is whether
sys.argv[0], if it is a filename, is an absolute filename and of course
to beware of sys.argv[0] being "-c", but the latter doesn't apply to
scripts.


   Bernhard

-- 
Intevation GmbH                                 http://intevation.de/
Sketch                                 http://sketch.sourceforge.net/
MapIt!                                           http://www.mapit.de/



More information about the Python-list mailing list