查找当前运行文件的路径[重复]

问题描述 投票:0回答:8

如何找到当前运行的Python脚本的完整路径?也就是说,我要做什么才能达到这个目的:

$ pwd
/tmp
$ python baz.py
running from /tmp 
file is baz.py
python reflection filesystems
8个回答
94
投票

__file__
不是您正在寻找的。 不要使用意外的副作用

sys.argv[0]
always 脚本的路径(如果实际上已经调用了脚本)——请参阅 http://docs.python.org/library/sys.html#sys.argv

__file__
当前正在执行的 文件(脚本或模块)的路径。如果从脚本访问的话,这“意外地”与脚本相同!如果您想将有用的东西(例如相对于脚本位置定位资源文件)放入库中,那么您必须使用 sys.argv[0]

示例:

C:\junk\so>type \junk\so\scriptpath\script1.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:\junk\so>type \python26\lib\site-packages\whereutils.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:\junk\so>\python26\python scriptpath\script1.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'



29
投票

import os dirname, filename = os.path.split(os.path.abspath(__file__)) print "running from", dirname print "file is", filename

当我将其放入
c:\src

时,它的行为如下:


> cd c:\src > python so-where.py running from C:\src file is so-where.py > cd c:\ > python src\so-where.py running from C:\src file is so-where.py



10
投票
检查 os.getcwd() (
docs

)


5
投票
__file__


这是一个演示脚本,名为

identify.py


print __file__

这是结果

MacBook-5:Projects slott$ python StackOverflow/identify.py StackOverflow/identify.py MacBook-5:Projects slott$ cd StackOverflow/ MacBook-5:StackOverflow slott$ python identify.py identify.py



4
投票

import os, sys print os.path.split(os.path.abspath(os.path.realpath(sys.argv[0])))[0]

这样您就可以安全地创建到脚本可执行文件的符号链接,并且它仍然会找到正确的目录。


3
投票

import sys print sys.argv[0]

一种更简单的方法来查找正在运行的脚本的路径:

os.path.dirname(sys.argv[0])



1
投票
sys.path

这实际上是一个包含其他路径的数组(列表)。 第一个元素包含脚本所在的完整路径(对于 Windows)。


因此,对于Windows,可以使用:

import sys path = sys.path[0] print(path)

其他人建议使用
sys.argv[0]

,它的工作方式非常相似并且完整。


import sys path = os.path.dirname(sys.argv[0]) print(path)

请注意,
sys.argv[0]

包含完整的工作目录(路径)+文件名,而

sys.path[0]
是不带文件名的当前工作目录。

我已经在 Windows 上测试了

sys.path[0]

并且它有效。我没有在 Windows 之外的其他操作系统上进行过测试,所以有人可能希望对此发表评论。

    


0
投票
sys.argv[0]

之外,还可以使用

__main__
:

import __main__ print(__main__.__file__)

但是请注意,这仅在极少数情况下有用;
并且它总是会创建一个导入循环,这意味着 
__main__

此时不会完全执行。

    

© www.soinside.com 2019 - 2024. All rights reserved.