how to get the path of a module (myself) ?

MRAB python at mrabarnett.plus.com
Tue Jun 2 02:14:22 CEST 2009


Stef Mientki wrote:
> MRAB wrote:
>> Stef Mientki wrote:
>>> hello,
>>>
>>> I've pictures stored in a path relative to my python source code.
>>> To get a picture, I need to know what path I'm on in each python module.
>>> I thought __file__ would do the job,
>>> but apparently I didn't read the documentation carefully enough,
>>> because file is the path to the module that called my module.
>>>
>>> Any ways to get the path of "myself" ?
>>>
>> I'm not sure what you mean. I just did a quick test.
>>
>> # File: C:\Quick test\child.py
>> print "name is %s" % __name__
>> print "file is %s" % __file__
>>
>> # File: C:\Quick test\parent.py
>> import child
>>
>> print "name is %s" % __name__
>> print "file is %s" % __file__
>>
>> # Output:
>> name is child
>> file is C:\Quick test\child.py
>> name is __main__
>> file is C:\Quick test\parent.py
> Yes, that's what I (and many others) thought,
> but now put your code in a file, let's say the file "test.py",
> and now run this file by :
>    execfile ( 'test.py' )
> 
You didn't say you were using execfile.

# File: C:\Quick test\main.py
parent_path = r"C:\Quick test\parent.py"
execfile(parent_path, {"__file__": parent_path})

# Output:
name is child
file is C:\Quick test\child.pyc
name is __builtin__
file is C:\Quick test\parent.py


Notice how the extension of the child is now .pyc because it has already
been compiled.




More information about the Python-list mailing list