Defining main() in python

Possible Duplicate:
What does <if name ==“ main ”:> do?

Often, I see the following code in python programs

if __name__ == '__main__':
main()

I'm following the Python Class on Google code, and it says that it's standard boilerplate code.

Do I really need to write such code in all my scripts?

What functionality would this add to my programs?


No, you don't have to, but it's invaluable for things like unit testing.

You can create a main in every python file so that, if you run it directly, __name__ will be set to "__main__" and it will run a barrage of tests on the code in question.

If you just import it normally from another program, that doesn't happen, because __name__ is set to a different value.


It is helpful, when you're importing the files. You can either run the python file as a standalone program, or import some components of it into another programs.

链接地址: http://www.djcxy.com/p/9324.html

上一篇: 与两个关键字混淆:

下一篇: 在python中定义main()