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 | |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 8 | -------------- |
| 9 | |
R David Murray | fe0e108 | 2014-04-14 18:53:51 -0400 | [diff] [blame] | 10 | ``'__main__'`` is the name of the scope in which top-level code executes. |
| 11 | 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] | 12 | standard input, a script, or from an interactive prompt. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 13 | |
R David Murray | 061cb3b | 2014-04-14 15:04:47 -0400 | [diff] [blame] | 14 | 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] | 15 | checking its own ``__name__``, which allows a common idiom for conditionally |
| 16 | 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] | 17 | -m`` but not when it is imported:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 18 | |
| 19 | if __name__ == "__main__": |
R David Murray | 061cb3b | 2014-04-14 15:04:47 -0400 | [diff] [blame] | 20 | # execute only if run as a script |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 21 | main() |
| 22 | |
R David Murray | 061cb3b | 2014-04-14 15:04:47 -0400 | [diff] [blame] | 23 | 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] | 24 | ``__main__.py`` module, the contents of which will be executed when the |
| 25 | module is run with ``-m``. |