Python4--模組和包
阿新 • • 發佈:2020-08-24
1. __name__
與 __main__
- 如果你經常看
python
的程式碼,很多指令碼後面都會用到if __name__ == '__main__':
,對於剛接觸python
的小夥伴開始肯定會不大理解這是什麼意思,為何這麼使用。會糾結的理不清頭緒,今天就這個痛點來簡單的分解講述下 __name__
其實是python
內建的系統變數,我們來首先來看看系統變數
中有哪些內容
# 伊洛Yiluo # https://yiluotalk.com/ >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
- 很多內容直接找到
__name__
吧
- 可見
__name__
就是內建的系統變數
而已
2. 舉個栗子
- 來建個新的指令碼
# 伊洛Yiluo
# https://yiluotalk.com/
(yiluo) ➜ Code touch build.py
(yiluo) ➜ Code vim build.py
- 指令碼中寫入
#!/usr/bin/env python3
# 伊洛Yiluo
print('__name__究竟是什麼? ')
print('該指令碼的 __name__值是:{}'.format(__name__))
- 執行一下
(yiluo) ➜ Code python build.py __name__究竟是什麼? 該指令碼的 __name__值是:__main__
- 打印出的內容很清晰的說明當下指令碼的
__name__
值是__main__
- 這就說明單獨執行指令碼的時候,
__name__
值就是是__main__
3.作為模組匯入時
- 在
Python
中一個.py 檔案
就是一個模組
(yiluo) ➜ Code python3 Python 3.7.5 (default, Nov 29 2019, 14:32:46) [Clang 9.0.0 (clang-900.0.39.2)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import build __name__究竟是什麼? 該指令碼的 __name__值是:build
__name__
的值變成了build
4.實際應用
- 那麼利用這點,我們如何實際應用,使匯入程式碼的時候不被執行
#!/usr/bin/env python3
# 伊洛Yiluo
print('__name__究竟是什麼? ')
print('該指令碼的 __name__值是:{}'.format(__name__))
if __name__ == '__main__':
print('我很倔強,我被匯入的時候不會被列印!')
- 來單獨執行下
build
指令碼
(yiluo) ➜ Code python build.py
__name__究竟是什麼?
該指令碼的 __name__值是:__main__
我很倔強,我被匯入的時候不會被列印!
- 看到最後的
print
列印了出來 - 如果被匯入呢?
# 公眾號:伊洛的小屋
(yiluo) ➜ Code python3
Python 3.7.5 (default, Nov 29 2019, 14:32:46)
[Clang 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import build
__name__究竟是什麼?
該指令碼的 __name__值是:build
- 當
__name__
的值不是__main__
的時候就不會打印出來了 - 再新建一個其它的檔案最後驗證下
(yiluo) ➜ Code touch test.py
(yiluo) ➜ Code vim test.py
- 鍵入程式碼
#!/usr/bin/env python3
# 伊洛Yiluo
import build
print('test指令碼自己列印')
``
- 命令列執行下
(yiluo) ➜ Code python test.py
__name__究竟是什麼?
該指令碼的 __name__值是:build
test指令碼自己列印
- 可見並沒有打印出
“我很倔強,我被匯入的時候不會被列印!”
5. 總結
- 當指令碼下面
if __name__ == "__main__":
碼入程式碼時,被匯入到其它指令碼中的時候不會被執行
6. 模組
- Python 的一個優勢就是擁有豐富的庫,庫是具有相關功能模組的集合,也就是常提到的標準庫、第三方庫以及自定義模組,在寫程式碼的過程中會經常被引用到
7. 引入模組
- 一個 .py 檔案就被稱為一個模組(Module)
import module
from module import *
8. 推薦引入順序
標準庫 > 第三方 > 自定義
9. 模組搜尋路徑
- Python 直譯器先在當前包中查詢模組,如果找不到就會在內建模組中查詢,如果依然找不到就會按 sys.path 給定的路徑查詢對應的模組檔案
10. 模組與包
- 包是一個資料夾,在其中可以定義多個模組或是多個子包。通常 Python 的第三方工具或是應用都是以包的形式釋出的
- 在 Python 中資料夾可以被識別成一個包,前提是這個資料夾中有一個
__init__.py
檔案 - Python 的
-m
引數用於將一個模組或包當作一個指令碼執行