1 """Utilities needed to emulate Python's interactive interpreter.
5 # Inspired by similar code by Jeff Epler and Fredrik Lundh.
10 from codeop
import CommandCompiler
, compile_command
12 __all__
= ["InteractiveInterpreter", "InteractiveConsole", "interact",
15 class InteractiveInterpreter
:
16 """Base class for InteractiveConsole.
18 This class deals with parsing and interpreter state (the user's
19 namespace); it doesn't deal with input buffering or prompting or
20 input file naming (the filename is always passed in explicitly).
24 def __init__(self
, locals=None):
27 The optional 'locals' argument specifies the dictionary in
28 which code will be executed; it defaults to a newly created
29 dictionary with key "__name__" set to "__console__" and key
30 "__doc__" set to None.
34 locals = {"__name__": "__console__", "__doc__": None}
36 self
.compile = CommandCompiler()
38 def runsource(self
, source
, filename
="<input>", symbol
="single"):
39 """Compile and run some source in the interpreter.
41 Arguments are as for compile_command().
43 One several things can happen:
45 1) The input is incorrect; compile_command() raised an
46 exception (SyntaxError or OverflowError). A syntax traceback
47 will be printed by calling the showsyntaxerror() method.
49 2) The input is incomplete, and more input is required;
50 compile_command() returned None. Nothing happens.
52 3) The input is complete; compile_command() returned a code
53 object. The code is executed by calling self.runcode() (which
54 also handles run-time exceptions, except for SystemExit).
56 The return value is True in case 2, False in the other cases (unless
57 an exception is raised). The return value can be used to
58 decide whether to use sys.ps1 or sys.ps2 to prompt the next
63 code
= self
.compile(source
, filename
, symbol
)
64 except (OverflowError, SyntaxError, ValueError):
66 self
.showsyntaxerror(filename
)
77 def runcode(self
, code
):
78 """Execute a code object.
80 When an exception occurs, self.showtraceback() is called to
81 display a traceback. All exceptions are caught except
82 SystemExit, which is reraised.
84 A note about KeyboardInterrupt: this exception may occur
85 elsewhere in this code, and may not always be caught. The
86 caller should be prepared to deal with it.
90 exec(code
, self
.locals)
96 def showsyntaxerror(self
, filename
=None):
97 """Display the syntax error that just occurred.
99 This doesn't display a stack trace because there isn't one.
101 If a filename is given, it is stuffed in the exception instead
102 of what was there before (because Python's parser always uses
103 "<string>" when reading from a string).
105 The output is written by self.write(), below.
108 type, value
, sys
.last_traceback
= sys
.exc_info()
110 sys
.last_value
= value
111 if filename
and type is SyntaxError:
112 # Work hard to stuff the correct filename in the exception
114 msg
, (dummy_filename
, lineno
, offset
, line
) = value
.args
116 # Not the format we expect; leave it alone
119 # Stuff in the right filename
120 value
= SyntaxError(msg
, (filename
, lineno
, offset
, line
))
121 sys
.last_value
= value
122 lines
= traceback
.format_exception_only(type, value
)
123 self
.write(''.join(lines
))
125 def showtraceback(self
):
126 """Display the exception that just occurred.
128 We remove the first stack item because it is our own code.
130 The output is written by self.write(), below.
134 type, value
, tb
= sys
.exc_info()
136 sys
.last_value
= value
137 sys
.last_traceback
= tb
138 tblist
= traceback
.extract_tb(tb
)
140 lines
= traceback
.format_list(tblist
)
142 lines
.insert(0, "Traceback (most recent call last):\n")
143 lines
.extend(traceback
.format_exception_only(type, value
))
146 self
.write(''.join(lines
))
148 def write(self
, data
):
151 The base implementation writes to sys.stderr; a subclass may
152 replace this with a different implementation.
155 sys
.stderr
.write(data
)
158 class InteractiveConsole(InteractiveInterpreter
):
159 """Closely emulate the behavior of the interactive Python interpreter.
161 This class builds on InteractiveInterpreter and adds prompting
162 using the familiar sys.ps1 and sys.ps2, and input buffering.
166 def __init__(self
, locals=None, filename
="<console>"):
169 The optional locals argument will be passed to the
170 InteractiveInterpreter base class.
172 The optional filename argument should specify the (file)name
173 of the input stream; it will show up in tracebacks.
176 InteractiveInterpreter
.__init
__(self
, locals)
177 self
.filename
= filename
180 def resetbuffer(self
):
181 """Reset the input buffer."""
184 def interact(self
, banner
=None):
185 """Closely emulate the interactive Python console.
187 The optional banner argument specifies the banner to print
188 before the first interaction; by default it prints a banner
189 similar to the one printed by the real Python interpreter,
190 followed by the current class name in parentheses (so as not
191 to confuse this with the real interpreter -- since it's so
197 except AttributeError:
201 except AttributeError:
203 cprt
= 'Type "help", "copyright", "credits" or "license" for more information.'
205 self
.write("Python %s on %s\n%s\n(%s)\n" %
206 (sys
.version
, sys
.platform
, cprt
,
207 self
.__class
__.__name
__))
209 self
.write("%s\n" % str(banner
))
218 line
= self
.raw_input(prompt
)
223 more
= self
.push(line
)
224 except KeyboardInterrupt:
225 self
.write("\nKeyboardInterrupt\n")
229 def push(self
, line
):
230 """Push a line to the interpreter.
232 The line should not have a trailing newline; it may have
233 internal newlines. The line is appended to a buffer and the
234 interpreter's runsource() method is called with the
235 concatenated contents of the buffer as source. If this
236 indicates that the command was executed or invalid, the buffer
237 is reset; otherwise, the command is incomplete, and the buffer
238 is left as it was after the line was appended. The return
239 value is 1 if more input is required, 0 if the line was dealt
240 with in some way (this is the same as runsource()).
243 self
.buffer.append(line
)
244 source
= "\n".join(self
.buffer)
245 more
= self
.runsource(source
, self
.filename
)
250 def raw_input(self
, prompt
=""):
251 """Write a prompt and read a line.
253 The returned line does not include the trailing newline.
254 When the user enters the EOF key sequence, EOFError is raised.
256 The base implementation uses the built-in function
257 input(); a subclass may replace this with a different
265 def interact(banner
=None, readfunc
=None, local
=None):
266 """Closely emulate the interactive Python interpreter.
268 This is a backwards compatible interface to the InteractiveConsole
269 class. When readfunc is not specified, it attempts to import the
270 readline module to enable GNU readline if it is available.
272 Arguments (all optional, all default to None):
274 banner -- passed to InteractiveConsole.interact()
275 readfunc -- if not None, replaces InteractiveConsole.raw_input()
276 local -- passed to InteractiveInterpreter.__init__()
279 console
= InteractiveConsole(local
)
280 if readfunc
is not None:
281 console
.raw_input = readfunc
287 console
.interact(banner
)
290 if __name__
== '__main__':
292 pdb
.run("interact()\n")