blob: 9020aab70163a8d684f08aeffeb56d44df79d2c2 [file] [log] [blame]
Guido van Rossum5d42b5b1998-10-22 21:56:44 +00001"""Utilities needed to emulate Python's interactive interpreter.
Guido van Rossum5227f0f1998-09-22 20:38:53 +00002
Guido van Rossum5227f0f1998-09-22 20:38:53 +00003"""
Guido van Rossum1557a731997-07-18 16:57:52 +00004
Guido van Rossum98d9fd32000-02-28 15:12:25 +00005# Inspired by similar code by Jeff Epler and Fredrik Lundh.
6
Guido van Rossum5d42b5b1998-10-22 21:56:44 +00007
Guido van Rossuma93b8481998-06-23 19:31:19 +00008import sys
Guido van Rossuma93b8481998-06-23 19:31:19 +00009import traceback
Tim Peters6cd6a822001-08-17 22:11:27 +000010from codeop import CommandCompiler, compile_command
Guido van Rossum90981e01997-10-07 14:47:24 +000011
Tim Peters6cd6a822001-08-17 22:11:27 +000012__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000013 "compile_command"]
14
Guido van Rossum5227f0f1998-09-22 20:38:53 +000015class InteractiveInterpreter:
16 """Base class for InteractiveConsole.
Guido van Rossuma93b8481998-06-23 19:31:19 +000017
Guido van Rossum5227f0f1998-09-22 20:38:53 +000018 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).
21
Guido van Rossuma93b8481998-06-23 19:31:19 +000022 """
23
Guido van Rossum5227f0f1998-09-22 20:38:53 +000024 def __init__(self, locals=None):
Guido van Rossuma93b8481998-06-23 19:31:19 +000025 """Constructor.
26
Guido van Rossum5227f0f1998-09-22 20:38:53 +000027 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.
Guido van Rossuma93b8481998-06-23 19:31:19 +000031
32 """
Guido van Rossuma93b8481998-06-23 19:31:19 +000033 if locals is None:
Guido van Rossum5227f0f1998-09-22 20:38:53 +000034 locals = {"__name__": "__console__", "__doc__": None}
Guido van Rossuma93b8481998-06-23 19:31:19 +000035 self.locals = locals
Tim Peters6cd6a822001-08-17 22:11:27 +000036 self.compile = CommandCompiler()
Guido van Rossum5227f0f1998-09-22 20:38:53 +000037
38 def runsource(self, source, filename="<input>", symbol="single"):
39 """Compile and run some source in the interpreter.
40
41 Arguments are as for compile_command().
42
43 One several things can happen:
44
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.
48
49 2) The input is incomplete, and more input is required;
50 compile_command() returned None. Nothing happens.
51
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).
55
Tim Petersbc0e9102002-04-04 22:55:58 +000056 The return value is True in case 2, False in the other cases (unless
Guido van Rossum5227f0f1998-09-22 20:38:53 +000057 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
59 line.
60
61 """
62 try:
Tim Peters6cd6a822001-08-17 22:11:27 +000063 code = self.compile(source, filename, symbol)
Guido van Rossum48450cf2001-01-15 18:13:35 +000064 except (OverflowError, SyntaxError, ValueError):
Guido van Rossum5227f0f1998-09-22 20:38:53 +000065 # Case 1
66 self.showsyntaxerror(filename)
Tim Petersbc0e9102002-04-04 22:55:58 +000067 return False
Guido van Rossum5227f0f1998-09-22 20:38:53 +000068
69 if code is None:
70 # Case 2
Tim Petersbc0e9102002-04-04 22:55:58 +000071 return True
Guido van Rossum5227f0f1998-09-22 20:38:53 +000072
73 # Case 3
74 self.runcode(code)
Tim Petersbc0e9102002-04-04 22:55:58 +000075 return False
Guido van Rossum5227f0f1998-09-22 20:38:53 +000076
77 def runcode(self, code):
78 """Execute a code object.
79
80 When an exception occurs, self.showtraceback() is called to
81 display a traceback. All exceptions are caught except
82 SystemExit, which is reraised.
83
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.
87
88 """
89 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +000090 exec(code, self.locals)
Guido van Rossum5227f0f1998-09-22 20:38:53 +000091 except SystemExit:
92 raise
93 except:
94 self.showtraceback()
95
96 def showsyntaxerror(self, filename=None):
97 """Display the syntax error that just occurred.
98
99 This doesn't display a stack trace because there isn't one.
100
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).
104
105 The output is written by self.write(), below.
106
107 """
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000108 type, value, tb = sys.exc_info()
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000109 sys.last_type = type
110 sys.last_value = value
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000111 sys.last_traceback = tb
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000112 if filename and type is SyntaxError:
113 # Work hard to stuff the correct filename in the exception
114 try:
Guido van Rossum33d26892007-08-05 15:29:28 +0000115 msg, (dummy_filename, lineno, offset, line) = value.args
116 except ValueError:
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000117 # Not the format we expect; leave it alone
118 pass
119 else:
120 # Stuff in the right filename
Skip Montanaro0679a732002-03-25 21:44:07 +0000121 value = SyntaxError(msg, (filename, lineno, offset, line))
Fred Drakec7745d42001-05-03 04:58:49 +0000122 sys.last_value = value
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000123 if sys.excepthook is sys.__excepthook__:
124 lines = traceback.format_exception_only(type, value)
125 self.write(''.join(lines))
126 else:
127 # If someone has set sys.excepthook, we let that take precedence
128 # over self.write
129 sys.excepthook(type, value, tb)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000130
131 def showtraceback(self):
132 """Display the exception that just occurred.
133
134 We remove the first stack item because it is our own code.
135
136 The output is written by self.write(), below.
137
138 """
139 try:
140 type, value, tb = sys.exc_info()
141 sys.last_type = type
142 sys.last_value = value
143 sys.last_traceback = tb
144 tblist = traceback.extract_tb(tb)
145 del tblist[:1]
Guido van Rossum33d26892007-08-05 15:29:28 +0000146 lines = traceback.format_list(tblist)
147 if lines:
148 lines.insert(0, "Traceback (most recent call last):\n")
149 lines.extend(traceback.format_exception_only(type, value))
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000150 finally:
151 tblist = tb = None
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000152 if sys.excepthook is sys.__excepthook__:
153 self.write(''.join(lines))
154 else:
155 # If someone has set sys.excepthook, we let that take precedence
156 # over self.write
157 sys.excepthook(type, value, tb)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000158
159 def write(self, data):
160 """Write a string.
161
162 The base implementation writes to sys.stderr; a subclass may
163 replace this with a different implementation.
164
165 """
166 sys.stderr.write(data)
167
168
169class InteractiveConsole(InteractiveInterpreter):
170 """Closely emulate the behavior of the interactive Python interpreter.
171
172 This class builds on InteractiveInterpreter and adds prompting
173 using the familiar sys.ps1 and sys.ps2, and input buffering.
174
175 """
176
177 def __init__(self, locals=None, filename="<console>"):
178 """Constructor.
179
180 The optional locals argument will be passed to the
181 InteractiveInterpreter base class.
182
183 The optional filename argument should specify the (file)name
184 of the input stream; it will show up in tracebacks.
185
186 """
187 InteractiveInterpreter.__init__(self, locals)
188 self.filename = filename
Guido van Rossuma93b8481998-06-23 19:31:19 +0000189 self.resetbuffer()
190
191 def resetbuffer(self):
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000192 """Reset the input buffer."""
Guido van Rossuma93b8481998-06-23 19:31:19 +0000193 self.buffer = []
194
195 def interact(self, banner=None):
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000196 """Closely emulate the interactive Python console.
197
Guido van Rossum33d26892007-08-05 15:29:28 +0000198 The optional banner argument specifies the banner to print
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000199 before the first interaction; by default it prints a banner
200 similar to the one printed by the real Python interpreter,
201 followed by the current class name in parentheses (so as not
202 to confuse this with the real interpreter -- since it's so
203 close!).
204
205 """
Guido van Rossuma93b8481998-06-23 19:31:19 +0000206 try:
207 sys.ps1
208 except AttributeError:
209 sys.ps1 = ">>> "
210 try:
211 sys.ps2
212 except AttributeError:
213 sys.ps2 = "... "
Skip Montanaroacb29ae2002-03-25 22:04:23 +0000214 cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
Guido van Rossuma93b8481998-06-23 19:31:19 +0000215 if banner is None:
216 self.write("Python %s on %s\n%s\n(%s)\n" %
Guido van Rossumc5f15b02001-01-14 23:04:22 +0000217 (sys.version, sys.platform, cprt,
Guido van Rossuma93b8481998-06-23 19:31:19 +0000218 self.__class__.__name__))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000219 else:
Guido van Rossuma93b8481998-06-23 19:31:19 +0000220 self.write("%s\n" % str(banner))
221 more = 0
222 while 1:
223 try:
224 if more:
225 prompt = sys.ps2
226 else:
227 prompt = sys.ps1
228 try:
229 line = self.raw_input(prompt)
230 except EOFError:
231 self.write("\n")
232 break
233 else:
234 more = self.push(line)
235 except KeyboardInterrupt:
236 self.write("\nKeyboardInterrupt\n")
237 self.resetbuffer()
238 more = 0
239
240 def push(self, line):
241 """Push a line to the interpreter.
242
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000243 The line should not have a trailing newline; it may have
244 internal newlines. The line is appended to a buffer and the
245 interpreter's runsource() method is called with the
246 concatenated contents of the buffer as source. If this
247 indicates that the command was executed or invalid, the buffer
248 is reset; otherwise, the command is incomplete, and the buffer
249 is left as it was after the line was appended. The return
250 value is 1 if more input is required, 0 if the line was dealt
251 with in some way (this is the same as runsource()).
Guido van Rossuma93b8481998-06-23 19:31:19 +0000252
253 """
254 self.buffer.append(line)
Eric S. Raymond6b71e742001-02-09 08:56:30 +0000255 source = "\n".join(self.buffer)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000256 more = self.runsource(source, self.filename)
257 if not more:
Guido van Rossuma93b8481998-06-23 19:31:19 +0000258 self.resetbuffer()
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000259 return more
Guido van Rossuma93b8481998-06-23 19:31:19 +0000260
261 def raw_input(self, prompt=""):
262 """Write a prompt and read a line.
263
264 The returned line does not include the trailing newline.
265 When the user enters the EOF key sequence, EOFError is raised.
266
Guido van Rossum83210b92008-01-02 02:55:27 +0000267 The base implementation uses the built-in function
268 input(); a subclass may replace this with a different
269 implementation.
Guido van Rossuma93b8481998-06-23 19:31:19 +0000270
271 """
Guido van Rossum83210b92008-01-02 02:55:27 +0000272 return input(prompt)
Neal Norwitzce96f692006-03-17 06:49:51 +0000273
Guido van Rossuma93b8481998-06-23 19:31:19 +0000274
275
Guido van Rossumd90ae191998-10-19 18:42:53 +0000276def interact(banner=None, readfunc=None, local=None):
Guido van Rossuma93b8481998-06-23 19:31:19 +0000277 """Closely emulate the interactive Python interpreter.
278
279 This is a backwards compatible interface to the InteractiveConsole
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000280 class. When readfunc is not specified, it attempts to import the
281 readline module to enable GNU readline if it is available.
Guido van Rossuma93b8481998-06-23 19:31:19 +0000282
283 Arguments (all optional, all default to None):
284
285 banner -- passed to InteractiveConsole.interact()
286 readfunc -- if not None, replaces InteractiveConsole.raw_input()
Guido van Rossumd90ae191998-10-19 18:42:53 +0000287 local -- passed to InteractiveInterpreter.__init__()
Guido van Rossuma93b8481998-06-23 19:31:19 +0000288
289 """
Guido van Rossumd90ae191998-10-19 18:42:53 +0000290 console = InteractiveConsole(local)
Guido van Rossuma93b8481998-06-23 19:31:19 +0000291 if readfunc is not None:
292 console.raw_input = readfunc
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000293 else:
294 try:
295 import readline
Skip Montanaro0679a732002-03-25 21:44:07 +0000296 except ImportError:
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000297 pass
Guido van Rossuma93b8481998-06-23 19:31:19 +0000298 console.interact(banner)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000299
300
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000301if __name__ == "__main__":
302 interact()