__main__.rst 888 Bytes
Newer Older
1 2 3 4 5 6 7

:mod:`__main__` --- Top-level script environment
================================================

.. module:: __main__
   :synopsis: The environment where the top-level script is run.

8 9
``'__main__'`` is the name of the scope in which top-level code executes.
A module's __name__ is set equal to ``'__main__'`` when read from
10
standard input, a script, or from an interactive prompt.
11

12
A module can discover whether or not it is running in the main scope by
13 14
checking its own ``__name__``, which allows a common idiom for conditionally
executing code in a module when it is run as a script or with ``python
15
-m`` but not when it is imported::
16 17

   if __name__ == "__main__":
18
       # execute only if run as a script
19 20
       main()

21
For a package, the same effect can be achieved by including a
22 23
``__main__.py`` module, the contents of which will be executed when the
module is run with ``-m``.