How to obtain python file path

Dan Grassi dan at grassi.org
Wed Apr 2 11:56:15 EST 2003


This works only if the python script is imported, not if it is executed 
directly.

Gee, I'm surprised that this is such a difficult thing to do yet 
conceptually simple.

Dan

In <slrnb8lr3q.15s.do-not-spam-ben.hutchings at tin.bwsint.com> Ben 
Hutchings  wrote:
> In article <20030401165546102-0500 at news.covad.net>, Dan Grassi wrote:
>> Not quite, that only provides the path to the initial .py file.
>> 
>> With a directory structure:
>> fa
>>     a.py
>>     fb
>>         b.py
>> 
>> cd .../fa
>> execute a.py
>> where a adds fb to sys.path
>> a imports b.py
>> 
>> I need b.py to report it's path which would be .../fa/fb
> 
> Assuming the current directory hasn't changed since the file was
> loaded, or the file was loaded with an absolute filename:
> 
>     def mydir():
>         import os.path
>         return os.path.abspath(os.path.dirname(__file__))
> 




More information about the Python-list mailing list