How can module determine its own path?

Steven D'Aprano steve at
Sat Oct 31 03:15:45 CET 2009

On Sat, 31 Oct 2009 00:40:59 +0100, Stef Mientki wrote:

> Robert Kern wrote:
>> On 2009-10-30 12:19 PM, kj wrote:
>>> How can a module determine the path of the file that defines it? (Note
>>> that this is, in the general case, different from sys.argv[0].)
>> __file__
> but for modules launched with execfile, __file__ doesn't exists.

If you execute a file with execfile, it isn't a module. It's a string 
read from a file being execute, which is not the same thing.

Hint: in Python 3, execfile is gone (thank goodness!). To get the same 
result, you use exec(file('myfile').read()).


More information about the Python-list mailing list