Name of the Script

David Bolen db3l at fitlinxx.com
Thu Mar 8 04:20:04 EST 2001


"Tim Hochberg" <tim.hochberg at ieee.org> writes:

> 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.

And isn't this risky in general since it depends on the fact that the
module itself is going to be somewhere properly on sys.path?  I've had
cases where the main script was in a system bin location that wasn't
on sys.path since it only contained top level scripts meant to be
directly executed.

I think I also had some issues with this approach when running a
module that resided within a package directory, but my memory is a bit
vague.

At a minimum you'd want to protect the import with a try/except block
to catch a possible ImportError and have some fallback scenario in
that case.

--
-- David
-- 
/-----------------------------------------------------------------------\
 \               David Bolen            \   E-mail: db3l at fitlinxx.com  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \
\-----------------------------------------------------------------------/



More information about the Python-list mailing list