什么是主py?

2024-04-25 17:26:59 发布

您现在位置:Python中文网/ 问答频道 /正文

这个__main__.py文件是用来干什么的,我应该把什么样的代码放进去,什么时候应该有一个?


Tags: 文件代码pymain
3条回答

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

创建Python模块时,通常会使模块在作为程序入口点运行时执行某些功能(通常包含在main函数中)。这通常是通过放置在大多数Python文件底部的以下常用习惯用法完成的:

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

可以使用__main__.py为Python包获取相同的语义。这是一个linux shell提示符,$,如果Windows上没有Bash(或另一个Posix shell),只需在demo/__<init/main>__.py处创建这些文件,其中的内容在EOF之间:

$ 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中,您可以不使用<< EOFs并在每个cat命令的末尾输入文件结尾字符Ctrl+D来结束上述操作)

现在:

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

你可以从文件中得到这个。documentation说:

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

拉链

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

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

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

$ 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文件。

__main__.py用于zip文件中的python程序。运行zip文件时将执行__main__.py文件。例如,如果zip文件是这样的:

test.zip
     __main__.py

__main__.py的含量是

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

如果我们运行python test.zip world,我们将得到hello world

因此,当对zip文件调用python时,__main__.py文件将运行。

相关问题 更多 >