'__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__.py
文件的用途是什么?创建Python模块时,通常会使模块在作为程序入口点运行时执行某些功能(通常包含在
main
函数中)。这通常是通过放置在大多数Python文件底部的以下常用习惯用法完成的:可以使用
__main__.py
为Python包获取相同的语义。这是一个linux shell提示符,$
,如果Windows上没有Bash(或另一个Posix shell),只需在demo/__<init/main>__.py
处创建这些文件,其中的内容在EOF
之间:(在Posix/Bash shell中,您可以不使用
<< EOF
s并在每个cat命令的末尾输入文件结尾字符Ctrl+D来结束上述操作)现在:
你可以从文件中得到这个。documentation说:
拉链
您还可以将其打包成一个文件,并从命令行运行,如下所示-但请注意,压缩包不能执行子包或子模块作为入口点:
通常,Python程序是通过在命令行上命名.py文件来运行的:
您还可以创建一个目录或充满代码的zipfile,并包含一个
__main__.py
。然后,您可以在命令行中简单地命名目录或zipfile,它会自动执行__main__.py
:你必须自己决定你的应用程序是否能从这样的执行中受益。
注意,
__main__
模块通常不是来自__main__.py
文件。它可以,但通常不会。当您运行类似python my_program.py
的脚本时,该脚本将作为__main__
模块而不是my_program
模块运行。对于以python -m my_module
或其他几种方式运行的模块,也会发生这种情况。如果您在错误消息中看到名称
__main__
,这并不一定意味着您应该查找__main__.py
文件。__main__.py
用于zip文件中的python程序。运行zip文件时将执行__main__.py
文件。例如,如果zip文件是这样的:而
__main__.py
的含量是如果我们运行
python test.zip world
,我们将得到hello world
。因此,当对zip文件调用python时,
__main__.py
文件将运行。相关问题 更多 >
编程相关推荐