Why do some python scripts declare main() in this manner?

This question already has an answer here:

  • What does if __name__ == “__main__”: do? 23 answers

  • This line allows you to make some functionality run by default only when you run the script as the main script (eg python my_script.py ).

    This is useful when the script may be used either as a main program or to be imported in another python module, or python shell. In the latter case you would almost certainly not want main (or other module functionality) to run on import, which is what happens by default when the interpreter loads a script.

    If you'll never import this script in other code, or in a python shell then you don't need this line. However, it's good to design your code to be modular & import friendly; even what may appear as throw away scripts (eg plotting some numbers, parsing some logs etc.) may be useful in a larger context. Particularly in an interactive shell session, eg using ipython . And the cost is small: encapsulate statements in functions and add ifmain .


    That is usefull when you are making a module or in general if you intend to import your scipt when running an other script. __name__ == "__main__" is true only when that script is the main script that is executed , so it avoids running subsequent code when it is ran at an import statement.

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

    上一篇: .py在Python 3中不需要包?

    下一篇: 为什么一些python脚本以这种方式声明main()?