Whenever the Python interpreter reads a source file, it does two things:
- it sets a few special variables like
__name__
, and then - it executes all of the code found in the file.
__main__
is the name of the scope in which top-level code executes. A module's __name__
is set equal to __main__
when read from standard input, a script, or from an interactive prompt.
A module can discover whether or not it is running in the main scope by checking its own __name__
, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:
if __name__ == "__main__":
# execute only if run as a script
main()
For a package, the same effect can be achieved by including a __main__.py
module, the contents of which will be executed when the module is run with -m
.
When will you need this?
- Your module is a library, but you want to have a script mode where it runs some unit tests or a demo.
- Your module is only used as a main program, but it has some unit tests, and the testing framework works by importing .py files like your script and running special test functions. You don't want it to try running the script just because it's importing the module.
- Your module is mostly used as a main program, but it also provides a programmer-friendly API for advanced users.
网友评论