打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
python
python __file__ 与argv[0]
在python下,获取当前执行主脚本的方法有两个:sys.argv[0]和__file__。
sys.argv[0]
获取主执行文件路径的最佳方法是用sys.argv[0],它可能是一个相对路径,所以再取一下abspath是保险的做法,像这样:
import os,sysdirname, filename = os.path.split(os.path.abspath(sys.argv[0]))print "running from", dirnameprint "file is", filename
__file__
__file__ 是用来获得模块所在的路径的,这可能得到的是一个相对路径,比如在脚本test.py中写入:
#!/usr/bin/env python
print __file__
按相对路径./test.py来执行,则打印得到的是相对路径,
按绝对路径执行则得到的是绝对路径。
而按用户目录来执行(~/practice/test.py),则得到的也是绝对路径(~被展开)
所以为了得到绝对路径,我们需要 os.path.realpath(__file__)。
而在Python控制台下,直接使用print __file__是会导致  name ‘__file__’ is not defined错误的,因为这时没有在任何一个脚本下执行,自然没有 __file__的定义了。
__file__和argv[0]差异
在主执行文件中时,两者没什么差异,不过要是在不同的文件下,就不同了,下面示例:
C:\junk\so>type \junk\so\scriptpath\script1.pyimport sys, osprint "script: sys.argv[0] is", repr(sys.argv[0])print "script: __file__ is", repr(__file__)print "script: cwd is", repr(os.getcwd())import whereutilswhereutils.show_where() C:\junk\so>type \python26\lib\site-packages\whereutils.pyimport sys, osdef 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.pyscript: 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'
所以一般来说,argv[0]要更可靠些。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python获取程序执行文件路径方法
实用工具:在工作中我是如何执行python文件的
Python / 如何获得Python脚本所在目录的位置 | Elias的个人主页
python获取当前路径
盘点Python编程语言sys库中的12个变量
python, shell, C/C++ 从命令行获得参数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服