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

Stef Mientki stef.mientki at
Tue Jun 2 02:55:13 CEST 2009

Steven D'Aprano wrote:
> On Tue, 02 Jun 2009 01:46:23 +0200, 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\
>>> print "name is %s" % __name__
>>> print "file is %s" % __file__
>>> # File: C:\Quick test\
>>> import child
>>> print "name is %s" % __name__
>>> print "file is %s" % __file__
>>> # Output:
>>> name is child
>>> file is C:\Quick test\
>>> name is __main__
>>> file is C:\Quick test\
>> Yes, that's what I (and many others) thought, but now put your code in a
>> file, let's say the file "", and now run this file by :
>>     execfile ( '' )
> In that case, is not a module. It's just a file that by accident 
> has a .py extension, which is read into memory and executed.
> If you bypass the module mechanism, don't be surprised that you've 
> bypassed the module mechanism :)
> What are you trying to do? Using execfile is probably not the right 
> solution.
Maybe you're right, and it's not the best solution for my problem.
I've written a program, that contains many files, both python files and 
data files,
and I would like to distribute the program.
For Linux, I'll just bundle the files in a zip-file,
but for windows I want to make a one button installer,
and the files generated by Py2Exe, don't work at all.

Through this discussion, I discovered another problem,
because __file__ isn't the current file,
I can't run 1 module(file) from another module (file) .

The structure of my files is something like this:


The Main_Programs, should be able to "run/launch" other Main_Programs 
and Support_Libraries,
in several ways (wait / nowait, fetch output or not, ... ).
So each Support_Libraries will have a "main-section".
Everything is highly dynamical, just dumping a new py-file in the 
Brick_Path, will make the py-files available ( i.e. directly visible and 
usable to the user) in all Main_Programs.

Moving the complete file-structure to Linux or Windows works good.

Distributing the files through Py2Exe doesn't work at all.
So I was thinking of a hack:
- make dummy programs, that will start through a 
execfile function
- Create executables with Py2Exe of the dummy programs
- add manually the whole directory structure to the files generated by 
- automate the above process by Inno setup

Any suggestions ?




More information about the Python-list mailing list