Ok here is what I do
sys.argv is always what you type into the terminal or use as the file path when executing it with python.exe or pythonw.exe
For example you can run the file text.py several ways, they each give you a different answer they always give you the path that python was typed.
C:\Documents and Settings\Admin>python test.py sys.argv[0]: test.py C:\Documents and Settings\Admin>python "C:\Documents and Settings\Admin\test.py" sys.argv[0]: C:\Documents and Settings\Admin\test.py
Ok so know you can get the file name, great big deal, now to get the application directory you can know use os.path, specifically abspath and dirname
import sys, os print os.path.dirname(os.path.abspath(sys.argv[0]))
That will output this:
C:\Documents and Settings\Admin\
it will always output this no matter if you type python test.py or python "C:\Documents and Settings\Admin\test.py"
The problem with using __file__ Consider these two files test.py
import sys import os def paths(): print "__file__: %s" % __file__ print "sys.argv: %s" % sys.argv[0] a_f = os.path.abspath(__file__) a_s = os.path.abspath(sys.argv[0]) print "abs __file__: %s" % a_f print "abs sys.argv: %s" % a_s if __name__ == "__main__": paths()
import_test.py
import test import sys test.paths() print "--------" print __file__ print sys.argv[0]
Output of "python test.py"
C:\Documents and Settings\Admin>python test.py __file__: test.py sys.argv: test.py abs __file__: C:\Documents and Settings\Admin\test.py abs sys.argv: C:\Documents and Settings\Admin\test.py
Output of "python test_import.py"
C:\Documents and Settings\Admin>python test_import.py __file__: C:\Documents and Settings\Admin\test.pyc sys.argv: test_import.py abs __file__: C:\Documents and Settings\Admin\test.pyc abs sys.argv: C:\Documents and Settings\Admin\test_import.py -------- test_import.py test_import.py
So as you can see file gives you always the python file it is being run from, where as sys.argv[0] gives you the file that you ran from the interpreter always. Depending on your needs you will need to choose which one best fits your needs.