argv[0] manipulation

James Kew james.kew at btinternet.com
Wed Dec 11 17:59:58 EST 2002


<P_spam_ at draigBrady.com> wrote in message
news:1SFJ9.34546$zX3.77851 at news.indigo.ie...

> So shouldn't python change argv[0] to
> './myscript' instead of 'myscript' in this case:
>
>    python myscript

-1: sys.argv should reflect exactly how the script was started. Python
shouldn't do any "magic" transformations on sys.argv -- this will confuse
more than it helps.

As an example: the scripts I write for internal use install a default
exception handler which assembles various information about the exception,
the installation, and the environment and email a report to me for
maintenance. Amongst the information I collect is the command-line with
which the script was invoked -- essentially a " ".join(sys.argv), albeit
with a slight tweak to quote any arguments with embedded spaces. Having
Python rewrite the command line doesn't entirely help...

I also think "argv[0] contains slash means debug mode" overloads how the
script is invoked with how it should _behave_ -- I run a script at least
once a day with an absolute path (to automate a telnet login to a corporate
firewall) which I wouldn't want to run in debug.

As others have suggested, how about a standard -d switch consistent across
all scripts you write?

I've also found using environment variables useful for switching on
debugging behaviour -- again, I have common script startup code which does
either a normal run, a timed run, or a profiled run based on absence,
presence, and value of an environment variable.

> Usually the current directory is not in the
> $PATH for security reasons

Unless you're on Windows in which case the current directory is always
implicitly searched first.

>   if '/' in argv[0]: #explicit path so debug
>       debugging = 1

I believe in any case that this can't be portable: the docs state "argv[0]
is the script name (it is operating system dependent whether this is a full
pathname or not)" so you can't rely on it containing anything other than the
name of the script.

That test also assumes paths contain forward-slashes, which the docs for
sys.argv don't guarantee either -- in the Windows distribution I run, python
temp\test.py results in an argv[0] of "temp\\test.py". Safer to test
os.path.normcase(sys.argv[0]). But safer still to use an explicit debugging
switch.

James





More information about the Python-list mailing list