Find out the file name of a module from inside the module?
a.neudecker at uni-bonn.de
Mon Aug 9 17:21:56 CEST 2004
Danke, Christian! Hat mir sehr geholfen! :-)
Christian Tismer schrieb:
> Andreas Neudecker wrote:
>> I know you can read the filename of a program as sys.argv. 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.
> 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
More information about the Python-list