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!

     

    人生短,迷茫路一程又一程。 脚步重,雨雪天踟蹰也踟蹰。 滴水聚,久无成效伊人不见。 该如何,敲击敲击昼夜不停。
  • 相关阅读:
    自建 IPA 分发平台
    一个优雅的占位图解决方案。适用于 UITableView 和 UICollectionView。
    Vuejs2.0购物车和地址选配学习笔记
    UIWebView 加 MJRefresh 同时解决底部黑影问题
    UIWebView 不自动全屏播放视频
    左右分页按钮的集合视图控件。用于快速编写出集合视图上分页多按钮点击事件!
    课程总结
    IO流实训
    事件处理
    变色
  • 原文地址:https://www.cnblogs.com/DesignerA/p/11618601.html
Copyright © 2011-2022 走看看