Home | History | Annotate | Download | only in library
      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 
      8 --------------
      9 
     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
     12 standard input, a script, or from an interactive prompt.
     13 
     14 A module can discover whether or not it is running in the main scope by
     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
     17 -m`` but not when it is imported::
     18 
     19    if __name__ == "__main__":
     20        # execute only if run as a script
     21        main()
     22 
     23 For a package, the same effect can be achieved by including a
     24 ``__main__.py`` module, the contents of which will be executed when the
     25 module is run with ``-m``.
     26