]> granicus.if.org Git - python/commitdiff
Bug #1637365: add subsection about "__name__ == __main__" to the
authorGeorg Brandl <georg@python.org>
Thu, 12 Jul 2007 09:37:49 +0000 (09:37 +0000)
committerGeorg Brandl <georg@python.org>
Thu, 12 Jul 2007 09:37:49 +0000 (09:37 +0000)
Python tutorial.

Doc/tut/tut.tex
Misc/NEWS

index c3c6bf6c60473f52fbe102ac29a7076218a2aa87..ee3d21c1be988523808bbf9c1699e232f43e60bb 100644 (file)
@@ -2522,6 +2522,44 @@ There is even a variant to import all names that a module defines:
 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}}
 
index 9bf357b6a5ef59416315d90bbb79d9329d336568..c40cf78ceaf76aa0421ebcaea6e7da0819c57485 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -851,6 +851,9 @@ Tools
 Documentation
 -------------
 
+- Bug #1637365: add subsection about "__name__ == __main__" to the
+  Python tutorial.
+
 - Patch #1698768: updated the "using Python on the Mac" intro.
 
 - Bug #1569057: Document that calling file.next() when the file is open for