• [转]获取当前执行主脚本的方法


    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:junkso>type junksoscriptpathscript1.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:junkso>type python26libsite-packageswhereutils.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:junkso>python26python scriptpathscript1.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]要更可靠些。
    
    See:http://andylin02.iteye.com/blog/933237
  • 相关阅读:
    CAPL编程之播放诊断宏文件
    遍历文件夹中所有文件,查找字符串并输出结果到指定文件
    CAPL编程之通过程序抓Log
    使用Python控制CAN总线
    客户端javascript分页
    企业管理系统应用平台(预览版)
    【Linux】查看项目运行端口号,进程号,文件所在位置
    【MC】我的世界模组开发之环境构建
    PHP中file_get_contents函数获取带BOM的utf8,然后json_decode() 返回null的问题
    win7 64位系统PSD缩略图补丁预览PSD Mystic Thumbs免费版
  • 原文地址:https://www.cnblogs.com/themost/p/7467238.html
Copyright © 2020-2023  润新知