`

python __file__ 与argv[0]

阅读更多

python __file__ 与argv[0]

在python下,获取当前执行主脚本的方法有两个:sys.argv[0]和__file__。

sys.argv[0]

获取主执行文件路径的最佳方法是用sys.argv[0],它可能是一个相对路径,所以再取一下abspath是保险的做法,像这样:

import os,sys
dirname, filename = os.path.split(os.path.abspath(sys.argv[0]))
print "running from", dirname
print "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.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'

所以一般来说,argv[0]要更可靠些。

分享到:
评论

相关推荐

    python 实现视频流下载保存MP4的方法

    如下所示: ...file_path=os.getcwd() #获取需要转换的路径 def get_user_path(argv_dir): if os.path.isdir(argv_dir): return argv_dir elif os.path.isabs(argv_dir): return argv_dir else: return Fa

    python命令行参数sys.argv使用示例

    > 3: print “Usage: ” + sys.argv[0] + “file1 file2” sys.exit(-1) file1 = sys.argv[1]file2 = sys.argv[2] list1 = {}for line in open(file1): list1[line.split()[0]] = 1 for line in open(file2): ...

    用python实现文件的读取

    如何实现试用python实现...filename = sys.argv[0] f=open(filename,'r',encoding='utf8') line_no=0 with open(filename,'r',encoding='utf8') as f: for line in f: line_no+=1 print(line_no,':',line) f.close()

    详解Python中 sys.argv[]的用法简明解释

    本篇文章主要介绍了详解Python中 sys.argv[]的用法简明解释,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

    python3.6.5参考手册 chm

    Python参考手册,官方正式版参考手册,chm版。以下摘取部分内容:Navigation index modules | next | Python » 3.6.5 Documentation » Python Documentation contents What’s New in Python What’s New In ...

    Beginning Python (2005).pdf

    Navigating the File System with the os Module 178 Try It Out: Listing Files and Playing with Paths 180 Try It Out: Searching for Files of a Particular Type 181 Try It Out: Refining a Search 183 ...

    Python获取当前路径实现代码

    使用sys.path[0]、sys.argv[0]、os.getcwd()、os.path.abspath(__file__)、os.path.realpath(__file__) sys.path是Python会去寻找模块的搜索路径列表,sys.path[0]和sys.argv[0]是一回事因为Python会自动把sys.argv...

    vs_community__1022223156.1578415119.exe

    sys.argv[0] = '"'"'C:\\Users\\z hiqu\\AppData\\Local\\Temp\\pip-install-mw9h8ku4\\Twisted\\setup.py'"'"'; __file__='"'"'C:\\Users\\zhiqu\\AppData\\Local\\Temp\\pip-install-mw9h8ku 4\\Twisted\\setup...

    code_numbering:在创建书籍或文档时分配行号的程序

    代码编号 用法 基本用法python number_tagging.py 텍스트파일 > number_...05: def main(argv, start_num=0): 06: src_file_line_count = bufcount(argv) 07: 08: src_file = open(argv, "r") 09: out_file = None

    Python基础教程(第二版)(第十-十一章).pdf

    sys.argv:包括传递到Python解释器的参数,包括脚本名称。 2. sys.exit(int):⼤多数使⽤默认值0⽤来标识程序成功运⾏,也可以提供字符串信息⽤作错误信息。 3. sys.modules:映射模块名到载⼊模块的字典。 4. sys....

    Python实现替换文件中指定内容的方法

    编写的python程序,文件名是file_replace.py,具体代码如下: #!/usr/bin/env python #_*_ coding:utf-8 _*_ import sys,os if len(sys.argv)<4>5: sys.exit('There needs four or five parameters') elif len(sys...

    Python实现代码统计工具

    本文实例为大家分享了Python实现代码统计工具的具体代码,供大家参考,具体内容如下 思路:首先获取所有文件,然后统计每个文件中代码的行数,最后将行数相加. 实现的功能: 统计每个文件的行数; 统计总行数; 支持...

    批量更新目录下所有CVS和SVN项目的Python脚本

    print os.path.join(sys.path[0], sys.argv[0]) import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(levelname)-8s %(message)s', filename='autoupdate.log', filemode='w...

    一个简单的Python的GUI程序

    self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setObjectName("verticalLayout") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName(...

    python实现大文本文件分割

    本文实例为大家分享了python实现大文本文件分割的具体代码,供大家参考,具体内容如下 ... if(len(sys.argv)==1): print('请输入要切割的文件完整路径:') files_path=raw_input().strip() for str_file_path

    python获取程序执行文件路径的方法(推荐)

    1.获取当前执行主脚本方法:sys.argv[0]和_ file _ (1)sys.argv 一个传给Python脚本的指令参数列表。sys.argv[0]是脚本的名字。一般得到的是相对路径,用os.path.abspath(sys.argv[0])得到执行文件的绝对路径: ...

    笨方法学python15~17文件操作

    from sys import argv script,filename = argv #先打开再读取 txt = open(filename) print(f"heres your file {filename}:") print(txt.read()) print(txt.read()) #另一种方式导入,手动输入文件名 print("Type ...

    [报错解决]安装xgboost报错python setup.py egg_info Check the logs for full command output.

    MacOS下安装xgboost和lightGBM报错,之前安装成功,换了python环境后安装失败 ... sys.argv[0] = ‘”’”’/private/tmp/pip-install-iebpqutp/xgboost/setup.py’”’”’; file=’”’”’/private/tmp/pip-install-

    BeautifulStrup:获取有关Python源文件的信息-python source file

    这是一个库函数的一个简单示例: 给定一个Python文件,其中一个方法的名称以及一个Python项目(一个或多个Python源文件的目录),将在调用该函数的所有位置打印 find_add.cpp # include int main ( int argc, ...

    pcappy:一个纯 Python libpcap 包装器!

    皮卡皮 PcapPy 是一个完全用 Python 编写的 libpcap 的 Python 包装器。 这是正确的! 无需使用丑陋的包装框架(如 Cython、... print 'usage: %s <dump>' % argv [ 0 ] exit ( - 1 ) # Open the file p = open_offli

Global site tag (gtag.js) - Google Analytics