blob: a46993d55ed24b4b68d2e2d3c211d339d7070191 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001
2:mod:`__main__` --- Top-level script environment
3================================================
4
5.. module:: __main__
6 :synopsis: The environment where the top-level script is run.
7
R David Murrayfe0e1082014-04-14 18:53:51 -04008``'__main__'`` is the name of the scope in which top-level code executes.
9A module's __name__ is set equal to ``'__main__'`` when read from
R David Murray061cb3b2014-04-14 15:04:47 -040010standard input, a script, or from an interactive prompt.
Georg Brandl116aa622007-08-15 14:28:22 +000011
R David Murray061cb3b2014-04-14 15:04:47 -040012A module can discover whether or not it is running in the main scope by
R David Murrayfe0e1082014-04-14 18:53:51 -040013checking its own ``__name__``, which allows a common idiom for conditionally
14executing code in a module when it is run as a script or with ``python
Berker Peksag5021cb52014-07-05 11:10:16 +030015-m`` but not when it is imported::
Georg Brandl116aa622007-08-15 14:28:22 +000016
17 if __name__ == "__main__":
R David Murray061cb3b2014-04-14 15:04:47 -040018 # execute only if run as a script
Georg Brandl116aa622007-08-15 14:28:22 +000019 main()
20
R David Murray061cb3b2014-04-14 15:04:47 -040021For a package, the same effect can be achieved by including a
R David Murrayfe0e1082014-04-14 18:53:51 -040022``__main__.py`` module, the contents of which will be executed when the
23module is run with ``-m``.