python中文件夾想作為一個模塊被引用,則在文件夾內必須要包含 __init__.py 文件,即使此文件為空。
如果此模塊想要運行則必須要包含 __main__.py 文件。接下來說下兩個文件起到的作用。
拿 robotframework 模塊下的文件舉例:
__init__.py里面一般包含了需要引用的模塊
1 from robot.rebot import rebot, rebot_cli 2 from robot.run import run, run_cli 3 from robot.version import get_version
__all__ 參數意為導出包內模塊,以下連接可以參考,不包含在__all__ 列表的模塊不可被其他程序引用
此處 __version__ 應為一個系統定義的名字, 可在系統內引用
1 from robot.rebot import rebot, rebot_cli 2 from robot.run import run, run_cli 3 from robot.version import get_version 4 5 6 __all__ = ['run', 'run_cli', 'rebot', 'rebot_cli'] 7 __version__ = get_version()
對於 __main__.py 我的理解是一個模塊的入口函數執行模塊
1 import sys 2 3 # Allows running as a script. __name__ check needed with multiprocessing: 4 # https://github.com/robotframework/robotframework/issues/1137 5 if 'robot' not in sys.modules and __name__ == '__main__': 6 import pythonpathsetter 7 8 from robot import run_cli 9 10 11 run_cli(sys.argv[1:])
當我們執行模塊代碼時首先會加載__init__.py 定義的引入模塊,然后進入__mian__.py 文件運行
一下是運行模塊的結果,調到了run_cli 的函數進行解析運行
E:\Software\Software\Python2.7.11\Lib\site-packages>python -m robot --help
Robot Framework -- A generic test automation framework
Version: 3.0 (Python 2.7.11 on win32)
Usage: robot [options] data_sources
or: python -m robot [options] data_sources
or: python path/to/robot [options] data_sources
or: java -jar robotframework.jar [options] data_sources
。。。 。。。 。。。 。。。
Options
=======
-N --name name Set the name of the top level test suite. Underscores
in the name are converted to spaces. Default name is
created from the name of the executed data source.
-D --doc documentation Set the documentation of the top level test suite.
Underscores in the documentation are converted to
spaces and it may also contain simple HTML formatting
(e.g. *bold* and http://url/).
-M --metadata name:value * Set metadata of the top level suite. Underscores
in the name and value are converted to spaces. Value
can contain same HTML formatting as --doc.
參考以下作者博客,敬謝:
https://www.cnblogs.com/alamZ/p/6943869.html
https://blog.zengrong.net/post/2192.html