zoukankan      html  css  js  c++  java
  • python模块内置变量及其作用

    1.__file__

    所在模块:os

    变量作用:指向当前文件

    当前文件的完整路径:os.path.abspath(__file__)

    当前文件所属目录:os.path.dirname(os.path.abspath(__file__))

    当前文件所属目录的上级目录:os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    cat filelocation.py
    import os
    print(__file__)
    print(os.path.abspath("filelocation.py"))
    print(os.path.abspath(__file__))
    print(os.path.dirname(os.path.abspath(__file__)))
    print(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    运行:
    python3 filelocation.py
    filelocation.py
    /home/test/CodeProjects/PythonProjects/test/filelocation.py /home/test/CodeProjects/PythonProjects/test/filelocation.py /home/test/CodeProjects/PythonProjects/test /home/test/CodeProjects/PythonProjects

     2.sys.path

     所在模块:sys

    python程序中使用import导入模块时,python解析器会在当前目录、已安装和第三方模块中搜索要导入的模块,更准确的说是从sys.path这个列表变量包含的路径中搜索的,因为sys.path是一个列表变量,所以可以使用append()和insert()函数更新列表中元素的值。

    cat syspath.py
    import sys
    print(isinstance(sys.path,list))
    print(sys.path)
    运行:
    python3 syspath.py
    True
    ['/home/test/CodeProjects/PythonProjects/test', '/usr/local/python36/lib/python36.zip', '/usr/local/python36/lib/python3.6', 
    '/usr/local/python36/lib/python3.6/lib-dynload', '/home/test/.local/lib/python3.6/site-packages', '/usr/local/python36/lib/python3.6/site-packages']

     3.__name__

    这是python内置的系统变量。

    当python程序被执行时,入口文件即python解释器紧跟的那个py文件,在这个文件中__name__的值为__main__,在其它py文件中的__name__的值都等于所在文件的文件名(不包含.py后缀)。通常,我们使用if __name__ == "__main__"来判断当前文件是否是入口文件,以便判断是否要执行这个if语句中的代码块。

    有趣的例子:

    cat /root/test.py
    def test():
        print("this is test code!")
    if __name__ == "test":
        test()
    cat /root/main.py 
    import test
    print("test.__name__  : %s"%(test.__name__))
    if __name__ == "__main__":
        print("this is main code!")
    [root@controller ~]# python /root/main.py 
    this is test code!
    test.__name__  : test
    this is main code!

     

    人生短,迷茫路一程又一程。 脚步重,雨雪天踟蹰也踟蹰。 滴水聚,久无成效伊人不见。 该如何,敲击敲击昼夜不停。
  • 相关阅读:
    使用helm管理复杂kubernetes应用
    helm repository 相关
    PSQLException: An I/O error occurred while sending to the backend.
    使用helm进行kubernetes包管理
    Slave作为其它Slave的Master时使用
    ext3是对ext2文件系统的一个扩展高性能日志文件系统
    ready是先执行的,load后执行,DOM文档的加载步骤
    jQuery上定义插件并重设插件构造函数
    在PHP与HTML混合输入的页面或者模板中就需要对PHP代码进行闭合
    decode 函数将字符串从某种编码转为 unicode 字符
  • 原文地址:https://www.cnblogs.com/DesignerA/p/11618601.html
Copyright © 2011-2022 走看看