This may seam a newbie question but it is not. It looks that common approaches are not always working:
Currently I know only two options but none of them looks to work an all cases.
sys.argv[0]
This means using path = os.path.abspath(os.path.dirname(sys.argv[0]))
but this does not work if you are running from another python script from another directory, and this can really happen in real life.
__file__
this means that path = os.path.abspath(os.path.dirname(__file__))
but I found that this doesn't work:
py2exe
that doesn't have a__file__
attribute but there is an workaround.- when you run from IDLE with
execute()
there is no__file__
attribute - OS X 10.6 where I get
NameError: global name '__file__' is not defined
Related questions with incomplete answers:
- http://stackoverflow.com/questions/1296501/python-find-path-to-file-being-run
- http://stackoverflow.com/questions/1483827/python-path-to-current-file-depends-on-how-i-execute-the-program
- http://stackoverflow.com/questions/2259503/how-to-know-the-path-of-the-running-script-in-python
- http://stackoverflow.com/questions/509742/python-chdir-to-dir-the-py-script-is-in
I'm looking for a generic solution, one that would work in all above use cases.
Update
Here is the result of a testcase:
output of python a.py (on Windows)
a.py: __file__= a.py a.py: os.getcwd()= C:\zzz b.py: sys.argv[0]= a.py b.py: __file__= a.py b.py: os.getcwd()= C:\zzz
a.py
#! /usr/bin/env python import os, sys print "a.py: sys.argv[0]=", sys.argv[0] print "a.py: __file__=", __file__ print "a.py: os.getcwd()=", os.getcwd() print execfile("subdir/b.py")
subdir/b.py
#! /usr/bin/env python import os, sys print "b.py: sys.argv[0]=", sys.argv[0] print "b.py: __file__=", __file__ print "b.py: os.getcwd()=", os.getcwd() print
tree
C:. | a.py \---subdir b.py