为什么要使用def main()? [重复]

本文翻译自:Why use def main()? [duplicate]

Possible Duplicate: 可能重复:
What does if __name__== "__main__" do? if __name__== "__main__"怎么办?

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

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? 我只是想知道主要有没有押韵?


#1楼

参考:https://stackoom.com/question/GxJG/为什么要使用def-main-重复


#2楼

如果没有主要的标记,即使脚本作为模块导入,代码也会被执行。


#3楼

Consider the second script. 考虑第二个脚本。 If you import it in another one, the instructions, as at "global level", will be executed. 如果您在另一个中导入它,将执行“全局级别”的指令。


#4楼

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. 使用此功能之一在同一模块中编写各种单元测试。


#5楼

" What does if __name__==“__main__”: do? " has already been answered. if __name__==“__main__”:做什么? ”已经回答了。

Having a main() function allows you to call its functionality if you import the module. 如果import模块,则使用main() 函数可以调用其功能。 The main (no pun intended) benefit of this (IMHO) is that you can unit test it. 这个(恕我直言)的主要(没有双关语)的好处是你可以对它进行单元测试。


#6楼

Everyone else has already answered it, but I think I still have something else to add. 其他人已经回答了,但我想我还有别的东西需要补充。

Reasons to have that if statement 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. 其他语言(如C和Java)有一个main()函数,在执行程序时调用。 Using this if , we can make Python behave like them, which feels more familiar for many people. 使用这个if ,我们可以让Python表现得像他们一样,这对许多人来说更为熟悉。

  • Code will be cleaner , easier to read, and better organized. 代码将更清晰 ,更易于阅读和更有条理。 (yeah, I know this is subjective) (是的,我知道这是主观的)

  • It will be possible to import that python code as a module without nasty side-effects. 可以将该python代码作为模块import而不会产生令人讨厌的副作用。

    • 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. 这意味着我们可以将该代码导入交互式python shell并测试/调试/运行它。

  • Variables inside def main are local , while those outside it are global . def main中的变量是本地变量,而外部的变量是全局变量。 This may introduce a few bugs and unexpected behaviors. 这可能会引入一些错误和意外行为。

But, you are not required to write a main() function and call it inside an if statement. 但是,您不需要编写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 bash scripts. 当我编写bash脚本时也会发生这种情况。

Even if you put code inside the main function, you are not required to write it exactly as that. 即使您将代码放在main函数中,也不需要完全按照它编写代码。 A neat variation could be: 一个整洁的变化可能是:

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. 这意味着您可以从其他脚本(或交互式shell)调用main()来传递自定义参数。 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. 但请记住,上面的代码需要解析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. 所以,随意编写更适合您的代码。 :) :)

你可能感兴趣的:(为什么要使用def main()? [重复])