finding dir of main .py file

John Machin sjmachin at lexicon.net
Tue Dec 11 15:37:53 EST 2007


On Dec 12, 6:50 am, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote:
> ron.longo wrote:
> > Nope, maybe I'm not explaining myself well.
>
> > When I do os.getenv('HOME') I get back None.
>
> > According to the docs, 'HOME' is the user's home directory on some
> > platforms.  Which is not what I want.
>
> > What I want is the directory in which an application's main .py file
> > resides.  That is, when I type: python MyApp.py, I want to know in which
> > directory does MyApp.py reside?
>
> Shane is right.
>
> >>> print __file__
> >>> print modulename.__file__
>

Shane is half-right by accident.

__file__ is the path to the file currently being executed.
The OP wanted to know "the directory in which an application's
main .py file resides". Using __file__  will give the correct result
*only* when used in that "main .py" file. If you have multiple
applications and you want a common "where are my resources" function/
method in an imported module, __file__ is of no use.

sys.argv[0] is your friend.

C:\junk>type calledmodule.py
import sys
def print_filenames():
    print "calledmodule: sys.argv[0] =", sys.argv[0]
    print "calledmodule: __file__ =", __file__

C:\junk>type whereami.py
import sys, calledmodule
print "script: sys.argv[0] =", sys.argv[0]
print "script: __file__ =", __file__
calledmodule.print_filenames()

C:\junk>whereami.py
script: sys.argv[0] = C:\junk\whereami.py
script: __file__ = C:\junk\whereami.py
calledmodule: sys.argv[0] = C:\junk\whereami.py
calledmodule: __file__ = C:\junk\calledmodule.pyc

Note that "calledmodule" could quite easily have been in some other
directory e.g. C:\Python25\Lib\site-packages\calledmodule
\calledmodule.pyc

If you later want to use py2exe, you'll have to work a little bit
harder, but it still doesn't involve __file__.

Cheers,
John




More information about the Python-list mailing list