blob: e2d506524d3ab250c84d967aee38eccea59b334f [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 Rossum4ec59c72001-01-13 22:10:41 +000015def softspace(file, newvalue):
16 oldvalue = 0
17 try:
18 oldvalue = file.softspace
19 except AttributeError:
20 pass
21 try:
22 file.softspace = newvalue
23 except TypeError: # "attribute-less object" or "read-only attributes"
24 pass
25 return oldvalue
Guido van Rossum90981e01997-10-07 14:47:24 +000026
Guido van Rossum5227f0f1998-09-22 20:38:53 +000027class InteractiveInterpreter:
28 """Base class for InteractiveConsole.
Guido van Rossuma93b8481998-06-23 19:31:19 +000029
Guido van Rossum5227f0f1998-09-22 20:38:53 +000030 This class deals with parsing and interpreter state (the user's
31 namespace); it doesn't deal with input buffering or prompting or
32 input file naming (the filename is always passed in explicitly).
33
Guido van Rossuma93b8481998-06-23 19:31:19 +000034 """
35
Guido van Rossum5227f0f1998-09-22 20:38:53 +000036 def __init__(self, locals=None):
Guido van Rossuma93b8481998-06-23 19:31:19 +000037 """Constructor.
38
Guido van Rossum5227f0f1998-09-22 20:38:53 +000039 The optional 'locals' argument specifies the dictionary in
40 which code will be executed; it defaults to a newly created
41 dictionary with key "__name__" set to "__console__" and key
42 "__doc__" set to None.
Guido van Rossuma93b8481998-06-23 19:31:19 +000043
44 """
Guido van Rossuma93b8481998-06-23 19:31:19 +000045 if locals is None:
Guido van Rossum5227f0f1998-09-22 20:38:53 +000046 locals = {"__name__": "__console__", "__doc__": None}
Guido van Rossuma93b8481998-06-23 19:31:19 +000047 self.locals = locals
Tim Peters6cd6a822001-08-17 22:11:27 +000048 self.compile = CommandCompiler()
Guido van Rossum5227f0f1998-09-22 20:38:53 +000049
50 def runsource(self, source, filename="<input>", symbol="single"):
51 """Compile and run some source in the interpreter.
52
53 Arguments are as for compile_command().
54
55 One several things can happen:
56
57 1) The input is incorrect; compile_command() raised an
58 exception (SyntaxError or OverflowError). A syntax traceback
59 will be printed by calling the showsyntaxerror() method.
60
61 2) The input is incomplete, and more input is required;
62 compile_command() returned None. Nothing happens.
63
64 3) The input is complete; compile_command() returned a code
65 object. The code is executed by calling self.runcode() (which
66 also handles run-time exceptions, except for SystemExit).
67
68 The return value is 1 in case 2, 0 in the other cases (unless
69 an exception is raised). The return value can be used to
70 decide whether to use sys.ps1 or sys.ps2 to prompt the next
71 line.
72
73 """
74 try:
Tim Peters6cd6a822001-08-17 22:11:27 +000075 code = self.compile(source, filename, symbol)
Guido van Rossum48450cf2001-01-15 18:13:35 +000076 except (OverflowError, SyntaxError, ValueError):
Guido van Rossum5227f0f1998-09-22 20:38:53 +000077 # Case 1
78 self.showsyntaxerror(filename)
79 return 0
80
81 if code is None:
82 # Case 2
83 return 1
84
85 # Case 3
86 self.runcode(code)
87 return 0
88
89 def runcode(self, code):
90 """Execute a code object.
91
92 When an exception occurs, self.showtraceback() is called to
93 display a traceback. All exceptions are caught except
94 SystemExit, which is reraised.
95
96 A note about KeyboardInterrupt: this exception may occur
97 elsewhere in this code, and may not always be caught. The
98 caller should be prepared to deal with it.
99
100 """
101 try:
102 exec code in self.locals
103 except SystemExit:
104 raise
105 except:
106 self.showtraceback()
Guido van Rossum4ec59c72001-01-13 22:10:41 +0000107 else:
108 if softspace(sys.stdout, 0):
109 print
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000110
111 def showsyntaxerror(self, filename=None):
112 """Display the syntax error that just occurred.
113
114 This doesn't display a stack trace because there isn't one.
115
116 If a filename is given, it is stuffed in the exception instead
117 of what was there before (because Python's parser always uses
118 "<string>" when reading from a string).
119
120 The output is written by self.write(), below.
121
122 """
123 type, value, sys.last_traceback = sys.exc_info()
124 sys.last_type = type
125 sys.last_value = value
126 if filename and type is SyntaxError:
127 # Work hard to stuff the correct filename in the exception
128 try:
129 msg, (dummy_filename, lineno, offset, line) = value
130 except:
131 # Not the format we expect; leave it alone
132 pass
133 else:
134 # Stuff in the right filename
135 try:
136 # Assume SyntaxError is a class exception
137 value = SyntaxError(msg, (filename, lineno, offset, line))
138 except:
139 # If that failed, assume SyntaxError is a string
140 value = msg, (filename, lineno, offset, line)
Fred Drakec7745d42001-05-03 04:58:49 +0000141 sys.last_value = value
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000142 list = traceback.format_exception_only(type, value)
143 map(self.write, list)
144
145 def showtraceback(self):
146 """Display the exception that just occurred.
147
148 We remove the first stack item because it is our own code.
149
150 The output is written by self.write(), below.
151
152 """
153 try:
154 type, value, tb = sys.exc_info()
155 sys.last_type = type
156 sys.last_value = value
157 sys.last_traceback = tb
158 tblist = traceback.extract_tb(tb)
159 del tblist[:1]
160 list = traceback.format_list(tblist)
161 if list:
Guido van Rossum7dd06962000-12-27 19:12:58 +0000162 list.insert(0, "Traceback (most recent call last):\n")
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000163 list[len(list):] = traceback.format_exception_only(type, value)
164 finally:
165 tblist = tb = None
166 map(self.write, list)
167
168 def write(self, data):
169 """Write a string.
170
171 The base implementation writes to sys.stderr; a subclass may
172 replace this with a different implementation.
173
174 """
175 sys.stderr.write(data)
176
177
178class InteractiveConsole(InteractiveInterpreter):
179 """Closely emulate the behavior of the interactive Python interpreter.
180
181 This class builds on InteractiveInterpreter and adds prompting
182 using the familiar sys.ps1 and sys.ps2, and input buffering.
183
184 """
185
186 def __init__(self, locals=None, filename="<console>"):
187 """Constructor.
188
189 The optional locals argument will be passed to the
190 InteractiveInterpreter base class.
191
192 The optional filename argument should specify the (file)name
193 of the input stream; it will show up in tracebacks.
194
195 """
196 InteractiveInterpreter.__init__(self, locals)
197 self.filename = filename
Guido van Rossuma93b8481998-06-23 19:31:19 +0000198 self.resetbuffer()
199
200 def resetbuffer(self):
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000201 """Reset the input buffer."""
Guido van Rossuma93b8481998-06-23 19:31:19 +0000202 self.buffer = []
203
204 def interact(self, banner=None):
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000205 """Closely emulate the interactive Python console.
206
207 The optional banner argument specify the banner to print
208 before the first interaction; by default it prints a banner
209 similar to the one printed by the real Python interpreter,
210 followed by the current class name in parentheses (so as not
211 to confuse this with the real interpreter -- since it's so
212 close!).
213
214 """
Guido van Rossuma93b8481998-06-23 19:31:19 +0000215 try:
216 sys.ps1
217 except AttributeError:
218 sys.ps1 = ">>> "
219 try:
220 sys.ps2
221 except AttributeError:
222 sys.ps2 = "... "
Guido van Rossumc5f15b02001-01-14 23:04:22 +0000223 cprt = 'Type "copyright", "credits" or "license" for more information.'
Guido van Rossuma93b8481998-06-23 19:31:19 +0000224 if banner is None:
225 self.write("Python %s on %s\n%s\n(%s)\n" %
Guido van Rossumc5f15b02001-01-14 23:04:22 +0000226 (sys.version, sys.platform, cprt,
Guido van Rossuma93b8481998-06-23 19:31:19 +0000227 self.__class__.__name__))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000228 else:
Guido van Rossuma93b8481998-06-23 19:31:19 +0000229 self.write("%s\n" % str(banner))
230 more = 0
231 while 1:
232 try:
233 if more:
234 prompt = sys.ps2
235 else:
236 prompt = sys.ps1
237 try:
238 line = self.raw_input(prompt)
239 except EOFError:
240 self.write("\n")
241 break
242 else:
243 more = self.push(line)
244 except KeyboardInterrupt:
245 self.write("\nKeyboardInterrupt\n")
246 self.resetbuffer()
247 more = 0
248
249 def push(self, line):
250 """Push a line to the interpreter.
251
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000252 The line should not have a trailing newline; it may have
253 internal newlines. The line is appended to a buffer and the
254 interpreter's runsource() method is called with the
255 concatenated contents of the buffer as source. If this
256 indicates that the command was executed or invalid, the buffer
257 is reset; otherwise, the command is incomplete, and the buffer
258 is left as it was after the line was appended. The return
259 value is 1 if more input is required, 0 if the line was dealt
260 with in some way (this is the same as runsource()).
Guido van Rossuma93b8481998-06-23 19:31:19 +0000261
262 """
263 self.buffer.append(line)
Eric S. Raymond6b71e742001-02-09 08:56:30 +0000264 source = "\n".join(self.buffer)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000265 more = self.runsource(source, self.filename)
266 if not more:
Guido van Rossuma93b8481998-06-23 19:31:19 +0000267 self.resetbuffer()
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000268 return more
Guido van Rossuma93b8481998-06-23 19:31:19 +0000269
270 def raw_input(self, prompt=""):
271 """Write a prompt and read a line.
272
273 The returned line does not include the trailing newline.
274 When the user enters the EOF key sequence, EOFError is raised.
275
276 The base implementation uses the built-in function
277 raw_input(); a subclass may replace this with a different
278 implementation.
279
280 """
281 return raw_input(prompt)
282
283
Guido van Rossumd90ae191998-10-19 18:42:53 +0000284def interact(banner=None, readfunc=None, local=None):
Guido van Rossuma93b8481998-06-23 19:31:19 +0000285 """Closely emulate the interactive Python interpreter.
286
287 This is a backwards compatible interface to the InteractiveConsole
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000288 class. When readfunc is not specified, it attempts to import the
289 readline module to enable GNU readline if it is available.
Guido van Rossuma93b8481998-06-23 19:31:19 +0000290
291 Arguments (all optional, all default to None):
292
293 banner -- passed to InteractiveConsole.interact()
294 readfunc -- if not None, replaces InteractiveConsole.raw_input()
Guido van Rossumd90ae191998-10-19 18:42:53 +0000295 local -- passed to InteractiveInterpreter.__init__()
Guido van Rossuma93b8481998-06-23 19:31:19 +0000296
297 """
Guido van Rossumd90ae191998-10-19 18:42:53 +0000298 console = InteractiveConsole(local)
Guido van Rossuma93b8481998-06-23 19:31:19 +0000299 if readfunc is not None:
300 console.raw_input = readfunc
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000301 else:
302 try:
303 import readline
304 except:
305 pass
Guido van Rossuma93b8481998-06-23 19:31:19 +0000306 console.interact(banner)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000307
308
Guido van Rossum90981e01997-10-07 14:47:24 +0000309if __name__ == '__main__':
310 interact()