找到正在运行的文件路径

56 投票
8 回答
108462 浏览
提问于 2025-04-15 13:41

我该怎么找到正在运行的Python脚本的完整路径呢?也就是说,我需要做些什么才能实现这个目标:

$ pwd
/tmp
$ python baz.py
running from /tmp 
file is baz.py

8 个回答

10
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

查看一下 os.getcwd() 这个函数的用法(文档

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
96

__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'

撰写回答