__file__
is NOT what you are looking for. Don't use accidental side-effects
sys.argv[0]
is always the path to the script (if in fact a script has been invoked) -- see http://docs.python.org/library/sys.html#sys.argv
__file__
is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0]
.
Example:
C:junkso>type junksoscriptpathscript1.py
import sys, os
print "script: sys.argv[0] is", repr(sys.argv[0])
print "script: __file__ is", repr(__file__)
print "script: cwd is", repr(os.getcwd())
import whereutils
whereutils.show_where()
C:junkso>type python26libsite-packageswhereutils.py
import sys, os
def show_where():
print "show_where: sys.argv[0] is", repr(sys.argv[0])
print "show_where: __file__ is", repr(__file__)
print "show_where: cwd is", repr(os.getcwd())
C:junkso>python26python scriptpathscript1.py
script: sys.argv[0] is 'scriptpath\script1.py'
script: __file__ is 'scriptpath\script1.py'
script: cwd is 'C:\junk\so'
show_where: sys.argv[0] is 'scriptpath\script1.py'
show_where: __file__ is 'C:\python26\lib\site-packages\whereutils.pyc'
show_where: cwd is 'C:\junk\so'
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…