code
— Interpreter base classes¶
Source code: Lib/code.py
The code
module provides facilities to implement read-eval-print loops in Python. code
模块提供了在Python中实现read-eval-print循环的工具。Two classes and convenience functions are included which can be used to build applications which provide an interactive interpreter prompt.包括两个类和便利函数,可用于构建提供交互式解释器提示的应用程序。
-
class
code.
InteractiveInterpreter
(locals=None)¶ This class deals with parsing and interpreter state (the user’s namespace); it does not deal with input buffering or prompting or input file naming (the filename is always passed in explicitly).这个类处理解析和解释器状态(用户的命名空间);它不处理输入缓冲或提示或输入文件命名(文件名总是显式传入的)。The optional locals argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key可选的locals参数指定将在其中执行代码的字典;它默认为新创建的字典,其中键'__name__'
set to'__console__'
and key'__doc__'
set toNone
.'__name__'
设置为'__console__'
,键'__doc__'
设置成None
。
-
class
code.
InteractiveConsole
(locals=None, filename='<console>')¶ Closely emulate the behavior of the interactive Python interpreter.密切模仿交互式Python解释器的行为。This class builds on该类构建在InteractiveInterpreter
and adds prompting using the familiarsys.ps1
andsys.ps2
, and input buffering.InteractiveInterpreter
上,并使用熟悉的sys.ps1
和sys.ps2
以及输入缓冲添加提示。
-
code.
interact
(banner=None, readfunc=None, local=None, exitmsg=None)¶ Convenience function to run a read-eval-print loop.运行读取评估打印循环的便利函数。This creates a new instance of这将创建一个新的InteractiveConsole
and sets readfunc to be used as theInteractiveConsole.raw_input()
method, if provided.InteractiveConsole
实例,并将readfunc设置为用作InteractiveConsole.raw_input()
方法(如果提供)。If local is provided, it is passed to the如果提供了local,它将被传递给InteractiveConsole
constructor for use as the default namespace for the interpreter loop.InteractiveConsole
构造函数,用作解释器循环的默认命名空间。The然后运行实例的interact()
method of the instance is then run with banner and exitmsg passed as the banner and exit message to use, if provided.interact()
方法,并传递banner和exitmsg作为banner和退出消息(如果提供的话)。The console object is discarded after use.控制台对象在使用后将被丢弃。Changed in version 3.6:版本3.6中更改: Added exitmsg parameter.
-
code.
compile_command
(source, filename='<input>', symbol='single')¶ This function is useful for programs that want to emulate Python’s interpreter main loop (a.k.a. the read-eval-print loop).这个函数对于想要模拟Python解释器主循环(也称为read-eval-print循环)的程序非常有用。The tricky part is to determine when the user has entered an incomplete command that can be completed by entering more text (as opposed to a complete command or a syntax error).棘手的部分是确定用户何时输入了一个不完整的命令,该命令可以通过输入更多文本来完成(而不是完整的命令或语法错误)。This function almost always makes the same decision as the real interpreter main loop.这个函数几乎总是做出与真正的解释器主循环相同的决定。source is the source string; filename is the optional filename from which source was read, defaulting tosource是源字符串;filename是从中读取源的可选文件名,默认为'<input>'
; and symbol is the optional grammar start symbol, which should be'single'
(the default),'eval'
or'exec'
.'<input>'
;symbol是可选的语法起始符号,应为'single'
(默认值)、'eval'
或'exec'
。Returns a code object (the same as
compile(source, filename, symbol)
) if the command is complete and valid;None
if the command is incomplete; raisesSyntaxError
if the command is complete and contains a syntax error, or raisesOverflowError
orValueError
if the command contains an invalid literal.
Interactive Interpreter Objects¶
-
InteractiveInterpreter.
runsource
(source, filename='<input>', symbol='single')¶ Compile and run some source in the interpreter. Arguments are the same as for
compile_command()
; the default for filename is'<input>'
, and for symbol is'single'
. One of several things can happen:The input is incorrect;
compile_command()
raised an exception (SyntaxError
orOverflowError
). A syntax traceback will be printed by calling theshowsyntaxerror()
method.runsource()
returnsFalse
.The input is incomplete, and more input is required;
compile_command()
returnedNone
.runsource()
returnsTrue
.The input is complete;
compile_command()
returned a code object. The code is executed by calling theruncode()
(which also handles run-time exceptions, except forSystemExit
).runsource()
returnsFalse
.
The return value can be used to decide whether to use
sys.ps1
orsys.ps2
to prompt the next line.
-
InteractiveInterpreter.
runcode
(code)¶ Execute a code object. When an exception occurs,
showtraceback()
is called to display a traceback. All exceptions are caught exceptSystemExit
, which is allowed to propagate.A note about
KeyboardInterrupt
: this exception may occur elsewhere in this code, and may not always be caught. The caller should be prepared to deal with it.
-
InteractiveInterpreter.
showsyntaxerror
(filename=None)¶ Display the syntax error that just occurred. This does not display a stack trace because there isn’t one for syntax errors. If filename is given, it is stuffed into the exception instead of the default filename provided by Python’s parser, because it always uses
'<string>'
when reading from a string. The output is written by thewrite()
method.
-
InteractiveInterpreter.
showtraceback
()¶ Display the exception that just occurred. We remove the first stack item because it is within the interpreter object implementation. The output is written by the
write()
method.Changed in version 3.5:版本3.5中更改: The full chained traceback is displayed instead of just the primary traceback.
-
InteractiveInterpreter.
write
(data)¶ Write a string to the standard error stream (
sys.stderr
). Derived classes should override this to provide the appropriate output handling as needed.
Interactive Console Objects¶
The InteractiveConsole
class is a subclass of InteractiveInterpreter
, and so offers all the methods of the interpreter objects as well as the following additions.
-
InteractiveConsole.
interact
(banner=None, exitmsg=None)¶ Closely emulate the interactive Python console. The optional banner argument specify the banner to print before the first interaction; by default it prints a banner similar to the one printed by the standard Python interpreter, followed by the class name of the console object in parentheses (so as not to confuse this with the real interpreter – since it’s so close!).
The optional exitmsg argument specifies an exit message printed when exiting. Pass the empty string to suppress the exit message. If exitmsg is not given or
None
, a default message is printed.Changed in version 3.4:版本3.4中更改: To suppress printing any banner, pass an empty string.Changed in version 3.6:版本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 a trailing newline; it may have internal newlines. The line is appended to a buffer and the interpreter’s
runsource()
method is called with the concatenated contents of the buffer as source. If this indicates that the command was executed or invalid, the buffer is reset; otherwise, the command is incomplete, and the buffer is left as it was after the line was appended. The return value isTrue
if more input is required,False
if the line was dealt with in some way (this is the same asrunsource()
).
-
InteractiveConsole.
resetbuffer
()¶ Remove any unhandled source text from the input buffer.