blob: a64faf1bbe3c849f0ba5dc2e4b210558bba6d430 [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
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04008--------------
9
R David Murrayfe0e1082014-04-14 18:53:51 -040010``'__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
R David Murray061cb3b2014-04-14 15:04:47 -040012standard input, a script, or from an interactive prompt.
Georg Brandl116aa622007-08-15 14:28:22 +000013
R David Murray061cb3b2014-04-14 15:04:47 -040014A module can discover whether or not it is running in the main scope by
R David Murrayfe0e1082014-04-14 18:53:51 -040015checking 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
Berker Peksag5021cb52014-07-05 11:10:16 +030017-m`` but not when it is imported::
Georg Brandl116aa622007-08-15 14:28:22 +000018
19 if __name__ == "__main__":
R David Murray061cb3b2014-04-14 15:04:47 -040020 # execute only if run as a script
Georg Brandl116aa622007-08-15 14:28:22 +000021 main()
22
R David Murray061cb3b2014-04-14 15:04:47 -040023For a package, the same effect can be achieved by including a
R David Murrayfe0e1082014-04-14 18:53:51 -040024``__main__.py`` module, the contents of which will be executed when the
25module is run with ``-m``.