什么是__main__.py?

问题:什么是__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?


回答 0

通常,通过在命令行上命名.py文件来运行Python程序:

$ python my_program.py

您还可以创建一个充满代码的目录或zipfile,并包含一个__main__.py。然后,您只需在命令行上命名目录或zipfile,它就会__main__.py自动执行:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

您必须自己决定应用程序是否可以从这样的执行中受益。


请注意,__main__ 模块通常不是来自__main__.py文件。可以,但是通常不会。当您运行类似python my_program.py的脚本时,脚本将作为__main__模块而不是my_program模块运行。对于以以下方式运行的模块,也会发生这种情况:python -m my_module或以其他方式,。

如果__main__在错误消息中看到该名称,则不一定意味着您应该在寻找__main__.py文件。

Often, a Python program is run by naming a .py file on the command line:

$ python my_program.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.


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.

If you saw the name __main__ in an error message, that doesn’t necessarily mean you should be looking for a __main__.py file.


回答 1

是什么 __main__.py文件是做什么用的?

创建Python模块时,通常在使该模块main作为程序的入口点运行时使其执行某些功能(通常包含在函数中)。通常,通过将以下常见用法放在大多数Python文件的底部来完成此操作:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

您可以使用来获得与Python包相同的语义__main__.py。这是一个Linux Shell提示符,$如果您在Windows上没有Bash(或另一个Posix Shell),只需demo/__<init/main>__.pyEOFs 之间创建以下内容的文件:

$ mkdir demo
$ cat > demo/__init__.py << EOF
print('demo/__init__.py executed')
def main():
    print('main executed')
EOF
$ cat > demo/__main__.py << EOF
print('demo/__main__.py executed')
from __init__ import main
main()
EOF

(在Posix / Bash shell中,可以通过在每个cat命令的末尾输入+ (文件末尾字符)来执行不带<< EOFs和以EOFs 结尾的上述操作)CtrlD

现在:

$ python demo
demo/__main__.py executed
demo/__init__.py executed
main executed

您可以从文档中得出。该文档说:

__main__ —顶级脚本环境

'__main__'是在其中执行顶级代码的作用域的名称。从标准输入,脚本或交互式提示中读取时,模块的__name__设置等于'__main__'

通过检查模块自身__name__,可以发现模块是否在主作用域中运行,这允许使用通用习语在模块中作为脚本运行时或python -m在导入时有条件地在模块中有条件地执行代码:

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

对于包,通过包含一个__main__.py模块可以实现相同的效果 ,当使用来运行该模块时,将执行其内容-m

压缩的

您还可以将其打包到一个文件中,然后从命令行运行,如下所示-但请注意,压缩包不能执行子包或子模块作为入口点:

$ python -m zipfile -c demo.zip demo/*
$ python demo.zip
demo/__main__.py executed
demo/__init__.py executed
main() executed

What is the __main__.py file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

You can get the same semantics for a Python package with __main__.py. This is a linux shell prompt, $, if you don’t have Bash (or another Posix shell) on Windows just create these files at demo/__<init/main>__.py with contents in between the EOFs:

$ mkdir demo
$ cat > demo/__init__.py << EOF
print('demo/__init__.py executed')
def main():
    print('main executed')
EOF
$ cat > demo/__main__.py << EOF
print('demo/__main__.py executed')
from __init__ import main
main()
EOF

(In a Posix/Bash shell, you can do the above without the << EOFs and ending EOFs by entering Ctrl+D, the end-of-file character, at the end of each cat command)

And now:

$ python demo
demo/__main__.py executed
demo/__init__.py executed
main executed

You can derive this from the documention. The documentation says:

__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.

Zipped

You can also package this into a single file and run it from the command line like this – but note that zipped packages can’t execute sub-packages or submodules as the entry point:

$ python -m zipfile -c demo.zip demo/*
$ python demo.zip
demo/__main__.py executed
demo/__init__.py executed
main() executed

回答 2

__main__.py用于zip文件中的python程序。在__main__.py当zip文件中运行文件就会被执行。例如,如果压缩文件是这样的:

test.zip
     __main__.py

和的内容__main__.py

import sys
print "hello %s" % sys.argv[1]

然后,如果我们要跑步,python test.zip world我们就会hello world下车。

因此,__main__.py当在zip文件上调用python时,文件就会运行。

__main__.py is used for python programs in zip files. The __main__.py file will be executed when the zip file in run. For example, if the zip file was as such:

test.zip
     __main__.py

and the contents of __main__.py was

import sys
print "hello %s" % sys.argv[1]

Then if we were to run python test.zip world we would get hello world out.

So the __main__.py file run when python is called on a zip file.


回答 3

创建__main__.pyyourpackage使其可执行文件:

$ python -m yourpackage

You create __main__.py in yourpackage to make it executable as:

$ python -m yourpackage

回答 4

如果您的脚本是目录或ZIP文件而不是单个python文件,__main__.py则在将“脚本”作为参数传递给python解释器时将执行该脚本。

If your script is a directory or ZIP file rather than a single python file, __main__.py will be executed when the “script” is passed as an argument to the python interpreter.