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