cinap_lenrekadd hg and python4bb9e2215 years agoHistory
173 lines · 7.2 KB · TeX
RawDownload
\section{\module{code} ---         Interpreter base classes}\declaremodule{standard}{code} \modulesynopsis{Base classes for interactive Python interpreters.}  The \code{code} module provides facilities to implementread-eval-print loops in Python.  Two classes and conveniencefunctions are included which can be used to build applications whichprovide an interactive interpreter prompt.  \begin{classdesc}{InteractiveInterpreter}{\optional{locals}}This class deals with parsing and interpreter state (the user'snamespace); it does not deal with input buffering or prompting orinput file naming (the filename is always passed in explicitly).The optional \var{locals} argument specifies the dictionary inwhich code will be executed; it defaults to a newly createddictionary with key \code{'__name__'} set to \code{'__console__'}and key \code{'__doc__'} set to \code{None}.\end{classdesc} \begin{classdesc}{InteractiveConsole}{\optional{locals\optional{, filename}}}Closely emulate the behavior of the interactive Python interpreter.This class builds on \class{InteractiveInterpreter} and addsprompting using the familiar \code{sys.ps1} and \code{sys.ps2}, andinput buffering.\end{classdesc}  \begin{funcdesc}{interact}{\optional{banner\optional{,                           readfunc\optional{, local}}}}Convenience function to run a read-eval-print loop.  This creates anew instance of \class{InteractiveConsole} and sets \var{readfunc}to be used as the \method{raw_input()} method, if provided.  If\var{local} is provided, it is passed to the\class{InteractiveConsole} constructor for use as the defaultnamespace for the interpreter loop.  The \method{interact()} methodof the instance is then run with \var{banner} passed as the bannerto use, if provided.  The console object is discarded after use.\end{funcdesc} \begin{funcdesc}{compile_command}{source\optional{,                                  filename\optional{, symbol}}}This function is useful for programs that want to emulate Python'sinterpreter main loop (a.k.a. the read-eval-print loop).  The trickypart is to determine when the user has entered an incomplete commandthat can be completed by entering more text (as opposed to acomplete command or a syntax error).  This function\emph{almost} always makes the same decision as the real interpretermain loop. \var{source} is the source string; \var{filename} is the optionalfilename from which source was read, defaulting to \code{'<input>'};and \var{symbol} is the optional grammar start symbol, which shouldbe either \code{'single'} (the default) or \code{'eval'}. Returns a code object (the same as \code{compile(\var{source},\var{filename}, \var{symbol})}) if the command is complete andvalid; \code{None} if the command is incomplete; raises\exception{SyntaxError} if the command is complete and contains asyntax error, or raises \exception{OverflowError} or\exception{ValueError} if the command contains an invalid literal.\end{funcdesc}  \subsection{Interactive Interpreter Objects            \label{interpreter-objects}} \begin{methoddesc}{runsource}{source\optional{, filename\optional{, symbol}}}Compile and run some source in the interpreter.Arguments are the same as for \function{compile_command()}; thedefault for \var{filename} is \code{'<input>'}, and for\var{symbol} is \code{'single'}.  One several things can happen: \begin{itemize}\itemThe input is incorrect; \function{compile_command()} raised anexception (\exception{SyntaxError} or \exception{OverflowError}).  Asyntax traceback will be printed by calling the\method{showsyntaxerror()} method.  \method{runsource()} returns\code{False}. \itemThe input is incomplete, and more input is required;\function{compile_command()} returned \code{None}.\method{runsource()} returns \code{True}. \itemThe input is complete; \function{compile_command()} returned a codeobject.  The code is executed by calling the \method{runcode()} (whichalso handles run-time exceptions, except for \exception{SystemExit}).\method{runsource()} returns \code{False}.\end{itemize} The return value can be used to decide whether to use\code{sys.ps1} or \code{sys.ps2} to prompt the next line.\end{methoddesc} \begin{methoddesc}{runcode}{code}Execute a code object.When an exception occurs, \method{showtraceback()} is called todisplay a traceback.  All exceptions are caught except\exception{SystemExit}, which is allowed to propagate. A note about \exception{KeyboardInterrupt}: this exception may occurelsewhere in this code, and may not always be caught.  The callershould be prepared to deal with it.\end{methoddesc} \begin{methoddesc}{showsyntaxerror}{\optional{filename}}Display the syntax error that just occurred.  This does not displaya stack trace because there isn't one for syntax errors.If \var{filename} is given, it is stuffed into the exception insteadof the default filename provided by Python's parser, because italways uses \code{'<string>'} when reading from a string.The output is written by the \method{write()} method.\end{methoddesc} \begin{methoddesc}{showtraceback}{}Display the exception that just occurred.  We remove the first stackitem because it is within the interpreter object implementation.The output is written by the \method{write()} method.\end{methoddesc} \begin{methoddesc}{write}{data}Write a string to the standard error stream (\code{sys.stderr}).Derived classes should override this to provide the appropriate outputhandling as needed.\end{methoddesc}  \subsection{Interactive Console Objects            \label{console-objects}} The \class{InteractiveConsole} class is a subclass of\class{InteractiveInterpreter}, and so offers all the methods of theinterpreter objects as well as the following additions. \begin{methoddesc}{interact}{\optional{banner}}Closely emulate the interactive Python console.The optional banner argument specify the banner to print before thefirst interaction; by default it prints a banner similar to the oneprinted by the standard Python interpreter, followed by the classname of the console object in parentheses (so as not to confuse thiswith the real interpreter -- since it's so close!).\end{methoddesc} \begin{methoddesc}{push}{line}Push a line of source text to the interpreter.The line should not have a trailing newline; it may have internalnewlines.  The line is appended to a buffer and the interpreter's\method{runsource()} method is called with the concatenated contentsof the buffer as source.  If this indicates that the command wasexecuted or invalid, the buffer is reset; otherwise, the command isincomplete, and the buffer is left as it was after the line wasappended.  The return value is \code{True} if more input is required,\code{False} if the line was dealt with in some way (this is the same as\method{runsource()}).\end{methoddesc} \begin{methoddesc}{resetbuffer}{}Remove any unhandled source text from the input buffer.\end{methoddesc} \begin{methoddesc}{raw_input}{\optional{prompt}}Write a prompt and read a line.  The returned line does not includethe trailing newline.  When the user enters the \EOF{} key sequence,\exception{EOFError} is raised.  The base implementation uses thebuilt-in function \function{raw_input()}; a subclass may replace thiswith a different implementation.\end{methoddesc}