Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
R David Murray | fe0e108 | 2014-04-14 18:53:51 -0400 | [diff] [blame] | 8 | ``'__main__'`` is the name of the scope in which top-level code executes. |
| 9 | A module's __name__ is set equal to ``'__main__'`` when read from |
R David Murray | 061cb3b | 2014-04-14 15:04:47 -0400 | [diff] [blame] | 10 | standard input, a script, or from an interactive prompt. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | |
R David Murray | 061cb3b | 2014-04-14 15:04:47 -0400 | [diff] [blame] | 12 | A module can discover whether or not it is running in the main scope by |
R David Murray | fe0e108 | 2014-04-14 18:53:51 -0400 | [diff] [blame] | 13 | checking its own ``__name__``, which allows a common idiom for conditionally |
| 14 | executing code in a module when it is run as a script or with ``python |
Berker Peksag | 5021cb5 | 2014-07-05 11:10:16 +0300 | [diff] [blame] | 15 | -m`` but not when it is imported:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | |
| 17 | if __name__ == "__main__": |
R David Murray | 061cb3b | 2014-04-14 15:04:47 -0400 | [diff] [blame] | 18 | # execute only if run as a script |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 19 | main() |
| 20 | |
R David Murray | 061cb3b | 2014-04-14 15:04:47 -0400 | [diff] [blame] | 21 | For a package, the same effect can be achieved by including a |
R David Murray | fe0e108 | 2014-04-14 18:53:51 -0400 | [diff] [blame] | 22 | ``__main__.py`` module, the contents of which will be executed when the |
| 23 | module is run with ``-m``. |