好的,这是我的步骤
sys.argv 始终是您在终端中键入或在使用 python.exe 或 pythonw.exe 执行时用作文件路径的内容。
例如,您可以以多种方式运行文件 text.py,它们每个都会给您不同的答案,但始终会提供输入 python 的路径。
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
好的,现在你知道如何获取文件名了,很重要,但是接下来要获取应用程序目录,你可以使用 os.path,具体地说是 abspath 和 dirname。
import sys, os
print os.path.dirname(os.path.abspath(sys.argv[0]))
这将会输出:
C:\Documents and Settings\Admin\
无论您键入 python test.py 还是 python "C:\Documents and Settings\Admin\test.py",它始终会输出这个。
使用 __file__ 的问题
考虑这两个文件
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]
"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
"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
因此,正如您所看到的,file总是会给出运行它的Python文件,而sys.argv[0]总是会给出从解释器运行的文件。根据您的需求,您需要选择最适合您需求的选项。