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!

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM