查找当前运行文件的路径

Chr*_*nch 42 python

如何找到当前运行的Python脚本的完整路径?也就是说,我需要做些什么来实现这个目标:

$ pwd
/tmp
$ python baz.py
running from /tmp 
file is baz.py
Run Code Online (Sandbox Code Playgroud)

Joh*_*hin 70

__file__不是你想要的.不要使用意外的副作用

sys.argv[0]永远的脚本路径(如果事实上脚本已经调用) -见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'
Run Code Online (Sandbox Code Playgroud)

  • 请注意,如果您正在查找包含正在运行的特定代码行的文件的路径,那么`__file__`就是要使用的路径.(例如,`__init __.py`,你不知道它将在哪里存在,并且当导入该模块时需要将它的`dirname()`添加到`sys.path` ...) (2认同)

Ric*_*dle 19

这将打印脚本所在的目录(而不是工作目录):

import os
dirname, filename = os.path.split(os.path.abspath(__file__))
print "running from", dirname
print "file is", filename
Run Code Online (Sandbox Code Playgroud)

当我把它放入时,它的行为方式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
Run Code Online (Sandbox Code Playgroud)


Nat*_*han 6

import sys, os

file = sys.argv[0]
pathname = os.path.dirname(file)
print 'running from %s' % os.path.abspath(pathname)
print 'file is %s' % file
Run Code Online (Sandbox Code Playgroud)

检查os.getcwd()(docs


S.L*_*ott 5

运行文件始终是__file__.

这是一个演示脚本,名为identify.py

print __file__
Run Code Online (Sandbox Code Playgroud)

这是结果

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
Run Code Online (Sandbox Code Playgroud)