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

Andreas Neudecker a.neudecker at uni-bonn.de
Mon Aug 9 11:21:56 EDT 2004


Danke, Christian! Hat mir sehr geholfen! :-)


Gruß


Andreas


Christian Tismer schrieb:
> 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



More information about the Python-list mailing list