Path ... where is my application's home dir?

John Hazen john at hazen.net
Wed Apr 28 18:11:48 EDT 2004


[Marco Aschwanden]
> >But I still wonder: Suppose sys.argv[0] wouldn't work. What 
> >would be the 
> >easiest way to find out where an application lies?
> >
> >Ideas:
> >1. going through sys.path and checking whether the application 
> >file is in 
> >a dir
> >2. or is there a module method, that tells you where it is stored?

[Tim Golden]
> As far as I know, it's effectively impossible: the "application" you're
> running is the Python executable, so even if you were do some fancy
> stuff with the win32 process/thread API and work out who you were
> and where you were running, that'd probably give you:
> c:/pythonxx/python.exe.

After poking around in the interactive python, I found __file__.

I wrote this test script, and created a dummy module "loc" in the same
directory:

--------- loc.py ----------
pass
--------- end loc.py ----------

--------- test.py ----------
#!/usr/bin/python

import loc,os

print __file__

print loc.__file__
print os.path.dirname(loc.__file__)
--------- end test.py ----------


Here's the output:  (MacOS)

lap:john$ ./test.py 
./test.py
/Users/john/loc.pyc
/Users/john
lap:john$ 

(output shows test.py path relative and loc path absolute invoked from
different directories, and by invoking with "python test.py")

Note that, for some reason, the file that was initially loaded by python
uses a relative pathname, but any modules loaded by that module seem to
use fully qualified path.

I'd be interested if there's a reason for this, and if it works in
windows as well.

If it does, and you can package another file with your application
(especially since you talked about having an "application directory"),
then it could be a solution that works without invoking any os-specific
commands.

-John




More information about the Python-list mailing list