Name of the Script

Paul Moore paul.moore at uk.origin-it.com
Thu Mar 8 10:34:29 CET 2001


On Wed, 7 Mar 2001 20:09:39 +0100 , David Bolen <db3l at fitlinxx.com>
wrote:

>Paul Moore <paul.moore at uk.origin-it.com> writes:
>
>> OK, so you could say "don't do that". But if I'm looking at some code
>> deep in a big program, can I be *sure* that no-one has changed
>> directory on me?
>
>You can't, but then again you really shouldn't be looking at your
>startup arguments (IMHO) inside code deep in a big program.

Agreed, in principle. However, in practice, I do have occasion to need
this sort of thing. As a specific example, suppose I had a module
which provided some form of logging service

def log(msg):
    logfile.write(timestamp + ": ")
    logfile.writeline(msg)

... you know the sort of thing. Now, I want my log file to reside in
the same directory as the calling script (not the same directory as
the logging module), but with an extension of .log instead of .py.

The obvious, and most user-friendly, way of doing this is using the
script name to generate a logfile name. This means looking at
sys.argv[0] from within the module.

A less friendly way is to require the main script to call
logger.init(os.path.abspath(sys.argv[0])) before starting processing.
(Which in turn requires sys and os imports which the main script may
otherwise not use).

This is a real-life case - I had a (VB Script, sorry!) program which
did exactly this. And the initialisation step was a definit pain...

But in the absence of a guaranteed full pathname in sys.argv[0], I
guess it's the only way to go.

Maybe having sys.argv[0] always be the full script pathname would be
something which could be added to Python? The interpreter must know
where the script is, so it would be easy to do from the startup
code...

Paul.




More information about the Python-list mailing list