Python 格式:运行() 还是 main()?
Python format: run() or main()?
对 Python 的世界还很陌生并且来自 MATLAB 我总是被教导使用 run()
函数来执行脚本。
然而,当在 Python 中处理多个 .py
文件时,我注意到使用 __main__.py
和随后的 main()
函数是很常见的(必需的?)每个脚本。
我通读了 PEP8 Style Guide and the Google Style Guide,似乎在每个脚本中都有一个 main()
函数似乎是常见的约定,但是...
我使用 run()
是否不正确(或风格不对)?您首选的命名约定是什么?
However when working with multiple .py files in Python, I've noticed it's common (required?) to use main.py and subsequently a main() function in each script.
不,不需要在您的 Python 包中包含 __main__.py
文件。简而言之,__main__.py
是一个方便的入口点挂钩,如果您要使用 Python 运行 模块,它允许您命名什么代码应该是 运行。例如,如果我有一个名为 foo
的包(文件夹)和一个 __main__.py
文件:
foo
|
+--- __main__.py
|
+--- foo.py
然后我可以直接从命令行 运行 包:
$ python foo
Python 然后会在 foo
中执行 __main__.py
文件。如您所见,这为其他人提供了一种方便的方式来执行您包中的代码。
Am I incorrect (or in bad style) for using run()? What is your preferred naming convention?
您可以自由命名执行代码的主函数,无论您选择什么,包括 run
。人们通常称它为 main
的原因是因为在其他语言中,必须调用名为 main 的函数才能执行程序。 It's the entry point the OS uses to execute your program.
您可以在 Python shell 中使用 execfile(filename)
。
可以找到您的问题的详细解决方案here。
P.S。无需将您的函数命名为 main()
左右。选择您喜欢的任何非保留或内置的内容。
对 Python 的世界还很陌生并且来自 MATLAB 我总是被教导使用 run()
函数来执行脚本。
然而,当在 Python 中处理多个 .py
文件时,我注意到使用 __main__.py
和随后的 main()
函数是很常见的(必需的?)每个脚本。
我通读了 PEP8 Style Guide and the Google Style Guide,似乎在每个脚本中都有一个 main()
函数似乎是常见的约定,但是...
我使用 run()
是否不正确(或风格不对)?您首选的命名约定是什么?
However when working with multiple .py files in Python, I've noticed it's common (required?) to use main.py and subsequently a main() function in each script.
不,不需要在您的 Python 包中包含 __main__.py
文件。简而言之,__main__.py
是一个方便的入口点挂钩,如果您要使用 Python 运行 模块,它允许您命名什么代码应该是 运行。例如,如果我有一个名为 foo
的包(文件夹)和一个 __main__.py
文件:
foo
|
+--- __main__.py
|
+--- foo.py
然后我可以直接从命令行 运行 包:
$ python foo
Python 然后会在 foo
中执行 __main__.py
文件。如您所见,这为其他人提供了一种方便的方式来执行您包中的代码。
Am I incorrect (or in bad style) for using run()? What is your preferred naming convention?
您可以自由命名执行代码的主函数,无论您选择什么,包括 run
。人们通常称它为 main
的原因是因为在其他语言中,必须调用名为 main 的函数才能执行程序。 It's the entry point the OS uses to execute your program.
您可以在 Python shell 中使用 execfile(filename)
。
可以找到您的问题的详细解决方案here。
P.S。无需将您的函数命名为 main()
左右。选择您喜欢的任何非保留或内置的内容。