Python 为什么要使用 def main()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4041238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why use def main()?
提问by Wizzard
I've seen some code samples and tutorials that use
我看过一些使用的代码示例和教程
def main():
# my code here
if __name__ == "__main__":
main()
But why? Is there any reason not do define your functions at the top of the file, then just write code under it? ie
但为什么?是否有任何理由不在文件顶部定义您的函数,然后在其下编写代码?IE
def my_function()
# my code here
def my_function_two()
# my code here
# some code
# call function
# print(something)
I just wonder if there is any rhyme to the main?
我只是想知道主要有没有押韵?
采纳答案by Ignacio Vazquez-Abrams
Without the main sentinel, the code would be executed even if the script were imported as a module.
如果没有主哨兵,即使脚本作为模块导入,代码也会被执行。
回答by Noe
Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.
考虑第二个脚本。如果您将其导入另一个,则将执行“全局级别”的指令。
回答by pyfunc
if the content of foo.py
如果 foo.py 的内容
print __name__
if __name__ == '__main__':
print 'XXXX'
A file foo.py can be used in two ways.
文件 foo.py 可以通过两种方式使用。
- imported in another file :
import foo
- 导入到另一个文件中:
import foo
In this case __name__is foo, the code section does not get executed and does not print XXXX.
在这种情况下__name__是foo,该代码段没有得到执行,并且不打印XXXX。
- executed directly :
python foo.py
- 直接执行:
python foo.py
When it is executed directly, __name__is same as __main__and the code in that section is executed and prints XXXX
直接执行时,__name__与__main__该段代码相同,并打印XXXX
One of the use of this functionality to write various kind of unit tests within the same module.
使用此功能在同一模块内编写各种单元测试的一种用途。
回答by Johnsyweb
"What does if __name__==“__main__”:do?" has already been answered.
“做if __name__==“__main__”:什么?”已经回答了。
Having a main()functionallows you to call its functionality if you importthe module. The main (no pun intended) benefit of this (IMHO) is that you can unit test it.
如果你是模块,拥有一个main()函数可以让你调用它的功能import。这个(恕我直言)的主要(无双关语)好处是您可以对其进行单元测试。
回答by Denilson Sá Maia
Everyone else has already answered it, but I think I still have something else to add.
其他人已经回答了,但我想我还有一点要补充。
Reasons to have that ifstatement calling main()(in no particular order):
if调用该语句的原因main()(无特定顺序):
Other languages (like C and Java) have a
main()function that is called when the program is executed. Using thisif, we can make Python behave like them, which feels more familiar for many people.Code will be cleaner, easier to read, and better organized. (yeah, I know this is subjective)
It will be possible to
importthat python code as a module without nasty side-effects.This means it will be possible to run tests against that code.
This means we can import that code into an interactive python shell and test/debug/run it.
Variables inside
def mainare local, while those outside it are global. This may introduce a few bugs and unexpected behaviors.
其他语言(如 C 和 Java)有一个
main()在程序执行时调用的函数。使用 thisif,我们可以让 Python 表现得像它们,这对很多人来说感觉更熟悉。代码将更清晰、更易于阅读且组织得更好。(是的,我知道这是主观的)
可以
import将该 python 代码作为一个模块而没有令人讨厌的副作用。这意味着可以针对该代码运行测试。
这意味着我们可以将该代码导入交互式 python shell 并测试/调试/运行它。
内部
def main的变量是局部的,而外部的变量是全局的。这可能会引入一些错误和意外行为。
But, you are not requiredto write a main()function and call it inside an ifstatement.
但是,您不需要编写main()函数并在if语句中调用它。
I myself usually start writing small throwaway scripts without any kind of function. If the script grows big enough, or if I feel putting all that code inside a function will benefit me, then I refactor the code and do it. This also happens when I write bashscripts.
我自己通常开始编写没有任何功能的小型一次性脚本。如果脚本变得足够大,或者如果我觉得将所有代码放在一个函数中对我有好处,那么我重构代码并执行它。当我编写bash脚本时也会发生这种情况。
Even if you put code inside the main function, you are not required to write it exactly as that. A neat variation could be:
即使您将代码放在 main 函数中,您也不需要完全那样写。一个巧妙的变化可能是:
import sys
def main(argv):
# My code here
pass
if __name__ == "__main__":
main(sys.argv)
This means you can call main()from other scripts (or interactive shell) passing custom parameters. This might be useful in unit tests, or when batch-processing. But remember that the code above will require parsing of argv, thus maybe it would be better to use a different call that pass parameters already parsed.
这意味着您可以main()从传递自定义参数的其他脚本(或交互式 shell)调用。这在单元测试或批处理时可能很有用。但请记住,上面的代码将需要解析 argv,因此使用传递已解析参数的不同调用可能会更好。
In an object-oriented application I've written, the code looked like this:
在我编写的面向对象的应用程序中,代码如下所示:
class MyApplication(something):
# My code here
if __name__ == "__main__":
app = MyApplication()
app.run()
So, feel free to write the code that better suits you. :)
因此,请随意编写更适合您的代码。:)

