Python基础-_main_

写在前面

如非特别说明,下文均基于Python3

一、__main__的官方解释

参考 _main_ -- Top-level script environment

'_main_' is the name of the scope in which top-level code executes. A module’s _name_ is set equal to '_main_' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own _name_, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == "__main__":
    # execute only if run as a script
    main()

For a package, the same effect can be achieved by including a _main_.py module, the contents of which will be executed when the module is run with -m.

__main__是顶层代码执行环境的名字。当一个模块从标准输入,脚本或者解释器提示行中被读取时,模块的__name__属性被设置成__main__

模块可以依据检查__name__属性是否为__main__的方式自我发现是否在main scope中,这允许了一种在模块中条件执行代码的常见用法,当模块作为脚本或者使用python -m命令运行时执行,而被导入时不执行:

if __name__ == "__main__":
    # 当且仅当模块作为脚本运行时执行main函数
    main()

对于包而言,可以在包中包含一个名为__main__.py的模块到达相同的效果,当模块使用python -m命令运行时,__main__py模块的内容会被执行。

二、__main__实践

第一节中说过,当模块从标准输入,脚本或者解释器命令行中被读取时,其__name__属性被设置为__main__ ,导入时值为模块名字。那么就可以根据这两种不同情况执行不同的代码。

Make a script both importable and executable

让脚本即可执行又可被导入,是对__main__这一特性最好的诠释:


def test():
	print('This is test method in com.richard.other')

def main():
	test()

if __name__ == '__main__':

	print('直接运行时,__name__属性:', __name__)
	main()
else:
	# 导入时被执行
	print('导入时,__name__属性:', __name__)

直接运行时,输出:

直接运行时,__name__属性: __main__
This is test method in com.richard.other

导入时,输出:

>>> import com.richard.other.test as ctest
导入时,__name__属性: com.richard.other.test
>>> 

这样,可以在if __name__ == '__main__':的判断下加入对这个模块的测试代码,就可以在不影响外部模块引用该模块的条件下,调试我们的模块了。

NOTICE: 示例在python 3+解释器中成功运行,的模块名为test.py,其包结构如下:

test.py包层次结构

目录sublime已加入python解释器sys.path变量中。

posted on 2017-05-25 16:42  珞樱缤纷  阅读(3421)  评论(0编辑  收藏  举报