__main__.py 是什么? [英] What is __main__.py?
问题描述
__main__.py
文件是做什么用的,我应该放入什么样的代码,什么时候应该有一个?
What is the __main__.py
file for, what sort of code should I put into it, and when should I have one?
推荐答案
通常,Python 程序是通过在命令行上命名 .py 文件来运行的:
Often, a Python program is run by naming a .py file on the command line:
$ python my_program.py
您还可以创建一个充满代码的目录或压缩文件,并包含一个 __main__.py
.然后你可以在命令行上简单地命名目录或zipfile,它会自动执行__main__.py
:
You can also create a directory or zipfile full of code, and include a __main__.py
. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py
automatically:
$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program
您必须自己决定您的应用程序是否可以从这样执行中受益.
You'll have to decide for yourself whether your application could benefit from being executed like this.
请注意,__main__
module 通常不是来自 __main__.py
文件.它可以,但通常不会.当您运行像 python my_program.py
这样的脚本时,该脚本将作为 __main__
模块而不是 my_program
模块运行.对于以 python -m my_module
或其他几种方式运行的模块,也会发生这种情况.
Note that a __main__
module usually doesn't come from a __main__.py
file. It can, but it usually doesn't. When you run a script like python my_program.py
, the script will run as the __main__
module instead of the my_program
module. This also happens for modules run as python -m my_module
, or in several other ways.
如果您在错误消息中看到名称 __main__
,这并不一定意味着您应该查找 __main__.py
文件.
If you saw the name __main__
in an error message, that doesn't necessarily mean you should be looking for a __main__.py
file.
这篇关于__main__.py 是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!