Find out the file name of a module from inside the module?

Christian Tismer tismer at stackless.com
Mon Aug 9 15:41:12 CEST 2004


Andreas Neudecker wrote:

> Hi.
> 
> I know you can read the filename of a program as sys.argv[0]. But what 
> about modules? Is there a similar way to find out the file name of a 
> module (called by some other module or program) from inside this module?

If your modules knows that it is a module, it can inspect its
__file__ attribute.
You can find out whether you have been imported by testing
whether there is a __file__ attribute, otherwise you are
probably executed, and there is no name available.

try:
     fname = __file__
except NameError:
     fname = "?"

In cases where you absolutely need a file name, and if you know
that you are also used as a module, you can of course import
yourself, in order to get the file name. This implies the need
to know your module name, which doesn't make things so much better:

# assuming this is MyModule
import MyModule
fname = MyModule.__file__
del MyModule

Or even shorter:

from MyModule import __file__ as fname

ciao - chris
-- 
Christian Tismer             :^)   <mailto:tismer at stackless.com>
Mission Impossible 5oftware  :     Have a break! Take a ride on Python's
Johannes-Niemeyer-Weg 9a     :    *Starship* http://starship.python.net/
14109 Berlin                 :     PGP key -> http://wwwkeys.pgp.net/
work +49 30 89 09 53 34  home +49 30 802 86 56  mobile +49 173 24 18 776
PGP 0x57F3BF04       9064 F4E1 D754 C2FF 1619  305B C09C 5A3B 57F3 BF04
      whom do you want to sponsor today?   http://www.stackless.com/




More information about the Python-list mailing list