Name of the Script

Tim Hochberg tim.hochberg at ieee.org
Wed Mar 7 15:41:13 EST 2001


"David Bolen" <db3l at fitlinxx.com> wrote in message
news:upuft9z0s.fsf at ctwd0143.fitlinxx.com...
> Paul Moore <paul.moore at uk.origin-it.com> writes:
[SNIP]
> > Interestingly, although the __name__ symbol has the value __main__ in
> > a script being run as a "main program", the __file__ symbol doesn't
> > exist. That's a pity, as it would probably be what I wanted...
>
> Right - if you're being imported you can reference __file__, but a top
> level script really only has argv[0], I believe.
>
> But argv[0] always references the path used to start the script which,
> at the point of startup, should always be a path that you can use to
> reference the same location.

Another approach, if __file__ is what you want is to have a module import
itself and grab the __file__ from the imported copy. Here's a (contrived)
example:

# file test.py
if __name__ == "__main__":
    import test
    print `test.__file__`

Unfortunately, this whole __file__ approach fails when using files from an
archive (such as produced with Gordon McMillan's installer), so this isn't
always useful.

> I'd just suggest that if you need this sort of thing later that you
> identify your location at startup, and then make that information
> available in a standard way to the rest of the application independent
> of sys.argv.  And if you know you might be moving directories, store
> the os.path.abspath() of sys.argv[0] at startup rather than just
> sys.argv[0].

Good advice I think.

-tim





More information about the Python-list mailing list