查找当前运行文件的路径 [英] Find path to currently running file

查看:71
本文介绍了查找当前运行文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

$密码/tmp$ python baz.py从/tmp 运行文件是 baz.py

解决方案

__file__ 不是您要找的. 不要使用意外的副作用>

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

__file__当前执行文件(脚本或模块)的路径.如果它是从脚本访问的,那么这意外与脚本相同!如果你想把一些有用的东西,比如定位相对于脚本位置的资源文件放到一个库中,那么你必须使用 sys.argv[0].

示例:

C:\junk\so>输入\junk\so\scriptpath\script1.py导入系统,操作系统打印脚本:sys.argv[0] 是",repr(sys.argv[0])打印脚本:__file__ 是",repr(__file__)打印脚本:cwd 是",repr(os.getcwd())导入 whereutilswhereutils.show_where()C:\junk\so>type \python26\lib\site-packages\whereutils.py导入系统,操作系统def show_where():打印show_where:sys.argv[0] 是",repr(sys.argv[0])打印 "show_where: __file__ is", repr(__file__)打印 "show_where: cwd is", repr(os.getcwd())C:\junk\so>\python26\python scriptpath\script1.py脚本:sys.argv[0] 是 'scriptpath\\script1.py'脚本: __file__ 是 'scriptpath\\script1.py'脚本:cwd 是 'C:\\junk\\so'show_where: sys.argv[0] 是 'scriptpath\\script1.py'show_where: __file__ 是 'C:\\python26\\lib\\site-packages\\whereutils.pyc'show_where: cwd 是 'C:\\junk\\so'

How can I find the full path to the currently running Python script? That is to say, what do I have to do to achieve this:

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

解决方案

__file__ is NOT what you are looking for. Don't use accidental side-effects

sys.argv[0] is always the path to the script (if in fact a script has been invoked) -- see http://docs.python.org/library/sys.html#sys.argv

__file__ is the path of the currently executing file (script or module). This is accidentally the same as the script if it is accessed from the script! If you want to put useful things like locating resource files relative to the script location into a library, then you must use sys.argv[0].

Example:

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'

这篇关于查找当前运行文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆