如何找出当前正在执行的脚本的路径?

时间:2009-01-14 19:40:25

标签: python

重复:In Python, how do I get the path and name of the file that is currently executing?

我想找出当前正在执行的脚本的路径。 我已经尝试过os.getcwd(),但只返回我运行脚本的目录,而不是脚本存储的实际目录。

2 个答案:

答案 0 :(得分:8)

在Python中,__file__标识当前的Python文件。因此:

print "I'm inside Python file %s" % __file__

将打印当前的Python文件。请注意,这适用于导入的Python模块以及脚本。

答案 1 :(得分:1)

如何使用sys.path [0]

你可以做类似的事情 'print os.path.join(sys.path [0],sys.argv [0])'

https://docs.python.org/library/sys.html