[Python-checkins] r56307 - in python/branches/release25-maint: Doc/tut/tut.tex Misc/NEWS

georg.brandl python-checkins at python.org
Thu Jul 12 11:37:53 CEST 2007


Author: georg.brandl
Date: Thu Jul 12 11:37:53 2007
New Revision: 56307

Modified:
   python/branches/release25-maint/Doc/tut/tut.tex
   python/branches/release25-maint/Misc/NEWS
Log:
Bug #1637365: add subsection about "__name__ == __main__" to the
Python tutorial.
 (backport from rev. 56306)

Modified: python/branches/release25-maint/Doc/tut/tut.tex
==============================================================================
--- python/branches/release25-maint/Doc/tut/tut.tex	(original)
+++ python/branches/release25-maint/Doc/tut/tut.tex	Thu Jul 12 11:37:53 2007
@@ -2522,6 +2522,44 @@
 This imports all names except those beginning with an underscore
 (\code{_}).
 
+\subsection{Executing modules as scripts \label{modulesAsScripts}}
+
+When you run a Python module with
+
+\begin{verbatim}
+python fibo.py <arguments>
+\end{verbatim}
+
+the code in the module will be executed, just as if you imported it, but
+with the \code{__name__} set to \code{"__main__"}.  That means that by
+adding this code at the end of your module:
+
+\begin{verbatim}
+if __name__ == "__main__":
+    import sys
+    fib(int(sys.argv[1]))
+\end{verbatim}
+
+you can make the file usable as a script as well as an importable module,
+because the code that parses the command line only runs if the module is
+executed as the ``main'' file:
+
+\begin{verbatim}
+$ python fibo.py 50
+1 1 2 3 5 8 13 21 34
+\end{verbatim}
+
+If the module is imported, the code is not run:
+
+\begin{verbatim}
+>>> import fibo
+>>>
+\end{verbatim}
+
+This is often used either to provide a convenient user interface to a
+module, or for testing purposes (running the module as a script executes
+a test suite).
+
 
 \subsection{The Module Search Path \label{searchPath}}
 

Modified: python/branches/release25-maint/Misc/NEWS
==============================================================================
--- python/branches/release25-maint/Misc/NEWS	(original)
+++ python/branches/release25-maint/Misc/NEWS	Thu Jul 12 11:37:53 2007
@@ -77,6 +77,9 @@
 Documentation
 -------------
 
+- Bug #1637365: add subsection about "__name__ == __main__" to the
+  Python tutorial.
+
 - Bug #1569057: Document that calling file.next() on a file open for writing
   has undefined behaviour.  Backport of r54712.
 


More information about the Python-checkins mailing list