vars() 查看當前文件中內置全局變量以字典方式返回內置全局變量
- __doc__ :獲取文件的注釋
- __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
- 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']
- __file__ ,一般配合os模塊的os.path.dirname(),os.path.basename() ,os.path.join() 模塊函數來使用
- __package__ :獲取導入文件的路徑,多層目錄以點分割,注意:對當前文件返回None
- __cached__ :獲取導入文件的緩存路徑
- __name__ :獲取導入文件的路徑加文件名稱,路徑以點分割,但是對象是導入的類名的話,只顯示短類名。注意:獲取當前文件返回的是__main__
- __name__ 全局變量寫在入口文件里,只有執行入口文件時的返回值才是__main__ ,如果入口文件被導入到別的文件里,此時入口文件的__name__返回值為模塊名稱
- __builtins__ 【重點】內置函數在這里面
原文鏈接:https://blog.csdn.net/henku449141932/article/details/80823654