code — Interpreter base classes

Source code:Lib/code.py


Thecode module provides facilities to implement read-eval-print loops inPython. Two classes and convenience functions are included which can be used tobuild applications which provide an interactive interpreter prompt.

classcode.InteractiveInterpreter(locals=None)

This class deals with parsing and interpreter state (the user’s namespace); itdoes not deal with input buffering or prompting or input file naming (thefilename is always passed in explicitly). The optionallocals argumentspecifies a mapping to use as the namespace in which code will be executed;it defaults to a newly created dictionary with key'__name__' set to'__console__' and key'__doc__' set toNone.

Note that functions and classes objects created under anInteractiveInterpreter instance will belong to the namespacespecified bylocals.They are only pickleable iflocals is the namespace of an existingmodule.

classcode.InteractiveConsole(locals=None,filename='<console>',local_exit=False)

Closely emulate the behavior of the interactive Python interpreter. This classbuilds onInteractiveInterpreter and adds prompting using the familiarsys.ps1 andsys.ps2, and input buffering. Iflocal_exit is true,exit() andquit() in the console will not raiseSystemExit, butinstead return to the calling code.

Changed in version 3.13:Addedlocal_exit parameter.

code.interact(banner=None,readfunc=None,local=None,exitmsg=None,local_exit=False)

Convenience function to run a read-eval-print loop. This creates a newinstance ofInteractiveConsole and setsreadfunc to be used astheInteractiveConsole.raw_input() method, if provided. Iflocal isprovided, it is passed to theInteractiveConsole constructor foruse as the default namespace for the interpreter loop. Iflocal_exit is provided,it is passed to theInteractiveConsole constructor. Theinteract()method of the instance is then run withbanner andexitmsg passed as thebanner and exit message to use, if provided. The console object is discardedafter use.

Changed in version 3.6:Addedexitmsg parameter.

Changed in version 3.13:Addedlocal_exit parameter.

code.compile_command(source,filename='<input>',symbol='single')

This function is useful for programs that want to emulate Python’s interpretermain loop (a.k.a. the read-eval-print loop). The tricky part is to determinewhen the user has entered an incomplete command that can be completed byentering more text (as opposed to a complete command or a syntax error). Thisfunctionalmost always makes the same decision as the real interpreter mainloop.

source is the source string;filename is the optional filename from whichsource was read, defaulting to'<input>'; andsymbol is the optionalgrammar start symbol, which should be'single' (the default),'eval'or'exec'.

Returns a code object (the same ascompile(source,filename,symbol)) if thecommand is complete and valid;None if the command is incomplete; raisesSyntaxError if the command is complete and contains a syntax error, orraisesOverflowError orValueError if the command contains aninvalid literal.

Interactive Interpreter Objects

InteractiveInterpreter.runsource(source,filename='<input>',symbol='single')

Compile and run some source in the interpreter. Arguments are the same as forcompile_command(); the default forfilename is'<input>', and forsymbol is'single'. One of several things can happen:

The return value can be used to decide whether to usesys.ps1 orsys.ps2to prompt the next line.

InteractiveInterpreter.runcode(code)

Execute a code object. When an exception occurs,showtraceback() is calledto display a traceback. All exceptions are caught exceptSystemExit,which is allowed to propagate.

A note aboutKeyboardInterrupt: this exception may occur elsewhere inthis code, and may not always be caught. The caller should be prepared to dealwith it.

InteractiveInterpreter.showsyntaxerror(filename=None)

Display the syntax error that just occurred. This does not display a stacktrace because there isn’t one for syntax errors. Iffilename is given, it isstuffed into the exception instead of the default filename provided by Python’sparser, because it always uses'<string>' when reading from a string. Theoutput is written by thewrite() method.

InteractiveInterpreter.showtraceback()

Display the exception that just occurred. We remove the first stack itembecause it is within the interpreter object implementation. The output iswritten by thewrite() method.

Changed in version 3.5:The full chained traceback is displayed insteadof just the primary traceback.

InteractiveInterpreter.write(data)

Write a string to the standard error stream (sys.stderr). Derived classesshould override this to provide the appropriate output handling as needed.

Interactive Console Objects

TheInteractiveConsole class is a subclass ofInteractiveInterpreter, and so offers all the methods of theinterpreter objects as well as the following additions.

InteractiveConsole.interact(banner=None,exitmsg=None)

Closely emulate the interactive Python console. The optionalbanner argumentspecify the banner to print before the first interaction; by default it prints abanner similar to the one printed by the standard Python interpreter, followedby the class name of the console object in parentheses (so as not to confusethis with the real interpreter – since it’s so close!).

The optionalexitmsg argument specifies an exit message printed when exiting.Pass the empty string to suppress the exit message. Ifexitmsg is not given orNone, a default message is printed.

Changed in version 3.4:To suppress printing any banner, pass an empty string.

Changed in version 3.6:Print an exit message when exiting.

InteractiveConsole.push(line)

Push a line of source text to the interpreter. The line should not have atrailing newline; it may have internal newlines. The line is appended to abuffer and the interpreter’srunsource() method is called with theconcatenated contents of the buffer as source. If this indicates that thecommand was executed or invalid, the buffer is reset; otherwise, the command isincomplete, and the buffer is left as it was after the line was appended. Thereturn value isTrue if more input is required,False if the line wasdealt with in some way (this is the same asrunsource()).

InteractiveConsole.resetbuffer()

Remove any unhandled source text from the input buffer.

InteractiveConsole.raw_input(prompt='')

Write a prompt and read a line. The returned line does not include the trailingnewline. When the user enters the EOF key sequence,EOFError is raised.The base implementation reads fromsys.stdin; a subclass may replace thiswith a different implementation.