Retrieve source filename

Greg Fortune lists at gregfortune.com
Thu Jul 31 17:18:25 EDT 2003


If you are working with an executable script (ie, __name__ == "__main__"), 

import sys
import os
os.path.abspath(sys.argv[0])

will give it to you.

Otherwise,

import imp
imp.find_module(__name__)[1]

will work.

It's pretty simple to detect between the two cases by simply checking
__name__.

Greg Fortune
Fortune Solutions

Irmen de Jong wrote:

> Shrom wrote:
> 
>> I know that you can retrieve main file name with sys.argv[0] and file
>> name for a module with modulename.__file__ but is there a common way to
>> retrieve file name for both main program and modules as the __FILE__
>> constant in PHP ?
> 
> I don't know if it's the "right" way, but this works:
> 
> import inspect
> print inspect.getfile(inspect.currentframe())
> 
> 
> --Irmen





More information about the Python-list mailing list