Why do some python scripts declare main() in this manner?
This question already has an answer here:
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.
上一篇: .py在Python 3中不需要包?