• python中获取执行脚本路径方法


    1、sys.path[0]:获取执行脚本目录绝对路径

    #每次执行脚本时,python会将执行脚本目录加入PYTHONPATH环境变量中(sys.path获取)
    #!/usr/bin/python3
    
    import os
    import sys
    
    print(sys.path)
    print(sys.path[0])
    执行结果:
    [root@localhost tmp]# ./py_test1/pytest24.py 
    ['/tmp/py_test1', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/site-packages/pip-9.0.1-py3.6.egg']
    /tmp/py_test1

    2、sys.argv[0]:获取脚本执行本身路径

    #!/usr/bin/python3
    
    import os
    import sys
    
    print(sys.argv[0])
    执行1结果:
    [root@localhost tmp]# ./py_test1/pytest24.py   #相对路径执行脚本则会返回相对路径
    ./py_test1/pytest24.py
    执行2结果:
    [root@localhost tmp]# /tmp/py_test1/pytest24.py  #绝对路径执行脚本则返回绝对路径
    /tmp/py_test1/pytest24.py

      注:sys.argv[0]获取得不是脚本目录路径,而是脚本本身执行时的路径!

    3、__file__:同sys.argv[0]相似,获取脚本执行本身路径:

    #!/usr/bin/python3
    
    import os
    import sys
    
    print("sys.argv[0] Output:",sys.argv[0])
    print("__file Output:",__file__)
    执行1结果:
    [root@localhost tmp]# ./py_test1/pytest24.py   #相对路径执行脚本则会返回相对路径
    sys.argv[0] Output: ./py_test1/pytest24.py
    __file Output: ./py_test1/pytest24.p
    
    执行2结果:
    [root@localhost tmp]# /tmp/py_test1/pytest24.py  #绝对路径执行脚本则会返回绝对路径
    sys.argv[0] Output: /tmp/py_test1/pytest24.py
    __file Output: /tmp/py_test1/pytest24.py

      注:__file__获取得不是脚本目录路径,而是脚本本身执行时的路径!

    4、os.path.abspath(__file__)和os.path.realpath(__file__):获取脚本执行本身的绝对路径

      通过获取__file__路径,然后转换成绝对路径

    #!/usr/bin/python3
    
    import os
    import sys
    
    print("__file Output:",__file__)
    print(os.path.abspath(__file__))
    print(os.path.realpath(__file__))
    执行结果:
    [root@localhost tmp]# ./py_test1/pytest24.py 
    __file Output: ./py_test1/pytest24.py
    /tmp/py_test1/pytest24.py
    /tmp/py_test1/pytest24.py

    注:os.path.abspath(__file__)和os.path.realpath(__file__)获取得是脚本本身的绝对路径!

  • 相关阅读:
    框架-.NET:Spring.Net
    杂项-WebService:WebService
    公司-企业内部创业:企业内部创业
    公司-内部创业:内部创业
    架构-软件系统体系结构-B/S架构:B/S架构
    架构-软件系统体系结构-C/S架构:C/S架构
    android google map v1 v2 v3 参考
    选购好的主机和服务器可以有效提高优化效果
    u盘安装ubuntu10.04 、11.04 server
    IOS学习笔记45--UITableView性能优化
  • 原文地址:https://www.cnblogs.com/chengd/p/7100782.html
Copyright © 2020-2023  润新知