python 模块中的 __init__.py __main__.py

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:SoftwareSoftwarePython2.7.11Libsite-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

原文地址:https://www.cnblogs.com/brownz/p/8352415.html