python __file__ 与argv[0]
来源:互联网 发布:visual foxpro是编程吗 编辑:程序博客网 时间:2024/05/19 00:37
转自http://andylin02.iteye.com/blog/933237
在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 pythonprint __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'
0 0
- python __file__ 与argv[0]
- python __file__ 与argv[0]
- python __file__ 与argv[0]
- python __file__ 与argv[0]
- python __file__ 与argv[0]
- __file__ 与 argv[0]
- python中关于__file__ 和 sys.argv[0]的使用
- Python基础-__name和__file__和argv[0]
- python __init__.py __name__ __doc__ __file__ argv[0] 浅析
- Python获取当前文件名分两种方法:__file__、sys.argv[0]
- python __file__ 与相对路径
- python的argc与argv
- [转]python __file__ 与相对路径
- python:9:os模块与sys.argv
- python argv
- 关于(*++argv)[0]与argc
- python __file__的绝对路径与import的搜索路径
- *++argv *++argv[0]
- 在Windows服务器上开启SNMP代理程序
- 号称最快android虚拟机的genymotion安装出现virtualization engine not found plugin loading aborted另外一个原因
- TestNG中case之间的依赖关系
- OC学习笔记05--分类的使用
- CLRS第二章思考题
- python __file__ 与argv[0]
- 使用Eclipse搭建简易Android服务器
- Concurrency vs Parallelism From Stackoverflow
- android:匿名启动系统Activity方式(系统浏览器、相册、短信、电话)
- 用jdbc连接mysql数据库(c3p0连接池篇)
- zsh – 給你的Mac不同體驗的Terminal!
- 黑马程序员——(面试题)银行业务调度系统
- avi文件格式详解【转】
- 首次登陆mysql,密码修改