1
2:mod:`__main__` --- Top-level script environment
3================================================
4
5.. module:: __main__
6   :synopsis: The environment where the top-level script is run.
7
8--------------
9
10``'__main__'`` is the name of the scope in which top-level code executes.
11A module's __name__ is set equal to ``'__main__'`` when read from
12standard input, a script, or from an interactive prompt.
13
14A module can discover whether or not it is running in the main scope by
15checking its own ``__name__``, which allows a common idiom for conditionally
16executing code in a module when it is run as a script or with ``python
17-m`` but not when it is imported::
18
19   if __name__ == "__main__":
20       # execute only if run as a script
21       main()
22
23For a package, the same effect can be achieved by including a
24``__main__.py`` module, the contents of which will be executed when the
25module is run with ``-m``.
26