blob: 86e1f03260784d31e83195e2cf791b6edbc8c0a9 [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
Alexander Belopolsky007a9032014-07-12 16:36:33 -040010import argparse
Tim Peters6cd6a822001-08-17 22:11:27 +000011from codeop import CommandCompiler, compile_command
Guido van Rossum90981e01997-10-07 14:47:24 +000012
Tim Peters6cd6a822001-08-17 22:11:27 +000013__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact",
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000014 "compile_command"]
15
Guido van Rossum5227f0f1998-09-22 20:38:53 +000016class InteractiveInterpreter:
17 """Base class for InteractiveConsole.
Guido van Rossuma93b8481998-06-23 19:31:19 +000018
Guido van Rossum5227f0f1998-09-22 20:38:53 +000019 This class deals with parsing and interpreter state (the user's
20 namespace); it doesn't deal with input buffering or prompting or
21 input file naming (the filename is always passed in explicitly).
22
Guido van Rossuma93b8481998-06-23 19:31:19 +000023 """
24
Guido van Rossum5227f0f1998-09-22 20:38:53 +000025 def __init__(self, locals=None):
Guido van Rossuma93b8481998-06-23 19:31:19 +000026 """Constructor.
27
Guido van Rossum5227f0f1998-09-22 20:38:53 +000028 The optional 'locals' argument specifies the dictionary in
29 which code will be executed; it defaults to a newly created
30 dictionary with key "__name__" set to "__console__" and key
31 "__doc__" set to None.
Guido van Rossuma93b8481998-06-23 19:31:19 +000032
33 """
Guido van Rossuma93b8481998-06-23 19:31:19 +000034 if locals is None:
Guido van Rossum5227f0f1998-09-22 20:38:53 +000035 locals = {"__name__": "__console__", "__doc__": None}
Guido van Rossuma93b8481998-06-23 19:31:19 +000036 self.locals = locals
Tim Peters6cd6a822001-08-17 22:11:27 +000037 self.compile = CommandCompiler()
Guido van Rossum5227f0f1998-09-22 20:38:53 +000038
39 def runsource(self, source, filename="<input>", symbol="single"):
40 """Compile and run some source in the interpreter.
41
42 Arguments are as for compile_command().
43
44 One several things can happen:
45
46 1) The input is incorrect; compile_command() raised an
47 exception (SyntaxError or OverflowError). A syntax traceback
48 will be printed by calling the showsyntaxerror() method.
49
50 2) The input is incomplete, and more input is required;
51 compile_command() returned None. Nothing happens.
52
53 3) The input is complete; compile_command() returned a code
54 object. The code is executed by calling self.runcode() (which
55 also handles run-time exceptions, except for SystemExit).
56
Tim Petersbc0e9102002-04-04 22:55:58 +000057 The return value is True in case 2, False in the other cases (unless
Guido van Rossum5227f0f1998-09-22 20:38:53 +000058 an exception is raised). The return value can be used to
59 decide whether to use sys.ps1 or sys.ps2 to prompt the next
60 line.
61
62 """
63 try:
Tim Peters6cd6a822001-08-17 22:11:27 +000064 code = self.compile(source, filename, symbol)
Guido van Rossum48450cf2001-01-15 18:13:35 +000065 except (OverflowError, SyntaxError, ValueError):
Guido van Rossum5227f0f1998-09-22 20:38:53 +000066 # Case 1
67 self.showsyntaxerror(filename)
Tim Petersbc0e9102002-04-04 22:55:58 +000068 return False
Guido van Rossum5227f0f1998-09-22 20:38:53 +000069
70 if code is None:
71 # Case 2
Tim Petersbc0e9102002-04-04 22:55:58 +000072 return True
Guido van Rossum5227f0f1998-09-22 20:38:53 +000073
74 # Case 3
75 self.runcode(code)
Tim Petersbc0e9102002-04-04 22:55:58 +000076 return False
Guido van Rossum5227f0f1998-09-22 20:38:53 +000077
78 def runcode(self, code):
79 """Execute a code object.
80
81 When an exception occurs, self.showtraceback() is called to
82 display a traceback. All exceptions are caught except
83 SystemExit, which is reraised.
84
85 A note about KeyboardInterrupt: this exception may occur
86 elsewhere in this code, and may not always be caught. The
87 caller should be prepared to deal with it.
88
89 """
90 try:
Georg Brandl7cae87c2006-09-06 06:51:57 +000091 exec(code, self.locals)
Guido van Rossum5227f0f1998-09-22 20:38:53 +000092 except SystemExit:
93 raise
94 except:
95 self.showtraceback()
96
97 def showsyntaxerror(self, filename=None):
98 """Display the syntax error that just occurred.
99
100 This doesn't display a stack trace because there isn't one.
101
102 If a filename is given, it is stuffed in the exception instead
103 of what was there before (because Python's parser always uses
104 "<string>" when reading from a string).
105
106 The output is written by self.write(), below.
107
108 """
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000109 type, value, tb = sys.exc_info()
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000110 sys.last_type = type
111 sys.last_value = value
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000112 sys.last_traceback = tb
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000113 if filename and type is SyntaxError:
114 # Work hard to stuff the correct filename in the exception
115 try:
Guido van Rossum33d26892007-08-05 15:29:28 +0000116 msg, (dummy_filename, lineno, offset, line) = value.args
117 except ValueError:
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000118 # Not the format we expect; leave it alone
119 pass
120 else:
121 # Stuff in the right filename
Skip Montanaro0679a732002-03-25 21:44:07 +0000122 value = SyntaxError(msg, (filename, lineno, offset, line))
Fred Drakec7745d42001-05-03 04:58:49 +0000123 sys.last_value = value
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000124 if sys.excepthook is sys.__excepthook__:
125 lines = traceback.format_exception_only(type, value)
126 self.write(''.join(lines))
127 else:
128 # If someone has set sys.excepthook, we let that take precedence
129 # over self.write
130 sys.excepthook(type, value, tb)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000131
132 def showtraceback(self):
133 """Display the exception that just occurred.
134
135 We remove the first stack item because it is our own code.
136
137 The output is written by self.write(), below.
138
139 """
R David Murrayc31e6222014-09-29 11:25:00 -0400140 sys.last_type, sys.last_value, last_tb = ei = sys.exc_info()
141 sys.last_traceback = last_tb
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000142 try:
R David Murrayc31e6222014-09-29 11:25:00 -0400143 lines = []
144 for value, tb in traceback._iter_chain(*ei[1:]):
145 if isinstance(value, str):
146 lines.append(value)
147 lines.append('\n')
148 continue
149 if tb:
150 tblist = traceback.extract_tb(tb)
151 if tb is last_tb:
152 # The last traceback includes the frame we
153 # exec'd in
154 del tblist[:1]
155 tblines = traceback.format_list(tblist)
156 if tblines:
157 lines.append("Traceback (most recent call last):\n")
158 lines.extend(tblines)
159 lines.extend(traceback.format_exception_only(type(value),
160 value))
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000161 finally:
R David Murrayc31e6222014-09-29 11:25:00 -0400162 tblist = last_tb = ei = None
Nick Coghlan8bd24fe2012-08-20 23:02:28 +1000163 if sys.excepthook is sys.__excepthook__:
164 self.write(''.join(lines))
165 else:
166 # If someone has set sys.excepthook, we let that take precedence
167 # over self.write
R David Murrayc31e6222014-09-29 11:25:00 -0400168 sys.excepthook(type, value, last_tb)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000169
170 def write(self, data):
171 """Write a string.
172
173 The base implementation writes to sys.stderr; a subclass may
174 replace this with a different implementation.
175
176 """
177 sys.stderr.write(data)
178
179
180class InteractiveConsole(InteractiveInterpreter):
181 """Closely emulate the behavior of the interactive Python interpreter.
182
183 This class builds on InteractiveInterpreter and adds prompting
184 using the familiar sys.ps1 and sys.ps2, and input buffering.
185
186 """
187
188 def __init__(self, locals=None, filename="<console>"):
189 """Constructor.
190
191 The optional locals argument will be passed to the
192 InteractiveInterpreter base class.
193
194 The optional filename argument should specify the (file)name
195 of the input stream; it will show up in tracebacks.
196
197 """
198 InteractiveInterpreter.__init__(self, locals)
199 self.filename = filename
Guido van Rossuma93b8481998-06-23 19:31:19 +0000200 self.resetbuffer()
201
202 def resetbuffer(self):
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000203 """Reset the input buffer."""
Guido van Rossuma93b8481998-06-23 19:31:19 +0000204 self.buffer = []
205
206 def interact(self, banner=None):
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000207 """Closely emulate the interactive Python console.
208
Guido van Rossum33d26892007-08-05 15:29:28 +0000209 The optional banner argument specifies the banner to print
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000210 before the first interaction; by default it prints a banner
211 similar to the one printed by the real Python interpreter,
212 followed by the current class name in parentheses (so as not
213 to confuse this with the real interpreter -- since it's so
214 close!).
215
216 """
Guido van Rossuma93b8481998-06-23 19:31:19 +0000217 try:
218 sys.ps1
219 except AttributeError:
220 sys.ps1 = ">>> "
221 try:
222 sys.ps2
223 except AttributeError:
224 sys.ps2 = "... "
Skip Montanaroacb29ae2002-03-25 22:04:23 +0000225 cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
Guido van Rossuma93b8481998-06-23 19:31:19 +0000226 if banner is None:
227 self.write("Python %s on %s\n%s\n(%s)\n" %
Guido van Rossumc5f15b02001-01-14 23:04:22 +0000228 (sys.version, sys.platform, cprt,
Guido van Rossuma93b8481998-06-23 19:31:19 +0000229 self.__class__.__name__))
Georg Brandlfbc3c3c2013-10-13 21:49:06 +0200230 elif banner:
Guido van Rossuma93b8481998-06-23 19:31:19 +0000231 self.write("%s\n" % str(banner))
232 more = 0
233 while 1:
234 try:
235 if more:
236 prompt = sys.ps2
237 else:
238 prompt = sys.ps1
239 try:
240 line = self.raw_input(prompt)
241 except EOFError:
242 self.write("\n")
243 break
244 else:
245 more = self.push(line)
246 except KeyboardInterrupt:
247 self.write("\nKeyboardInterrupt\n")
248 self.resetbuffer()
249 more = 0
250
251 def push(self, line):
252 """Push a line to the interpreter.
253
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000254 The line should not have a trailing newline; it may have
255 internal newlines. The line is appended to a buffer and the
256 interpreter's runsource() method is called with the
257 concatenated contents of the buffer as source. If this
258 indicates that the command was executed or invalid, the buffer
259 is reset; otherwise, the command is incomplete, and the buffer
260 is left as it was after the line was appended. The return
261 value is 1 if more input is required, 0 if the line was dealt
262 with in some way (this is the same as runsource()).
Guido van Rossuma93b8481998-06-23 19:31:19 +0000263
264 """
265 self.buffer.append(line)
Eric S. Raymond6b71e742001-02-09 08:56:30 +0000266 source = "\n".join(self.buffer)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000267 more = self.runsource(source, self.filename)
268 if not more:
Guido van Rossuma93b8481998-06-23 19:31:19 +0000269 self.resetbuffer()
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000270 return more
Guido van Rossuma93b8481998-06-23 19:31:19 +0000271
272 def raw_input(self, prompt=""):
273 """Write a prompt and read a line.
274
275 The returned line does not include the trailing newline.
276 When the user enters the EOF key sequence, EOFError is raised.
277
Guido van Rossum83210b92008-01-02 02:55:27 +0000278 The base implementation uses the built-in function
279 input(); a subclass may replace this with a different
280 implementation.
Guido van Rossuma93b8481998-06-23 19:31:19 +0000281
282 """
Guido van Rossum83210b92008-01-02 02:55:27 +0000283 return input(prompt)
Neal Norwitzce96f692006-03-17 06:49:51 +0000284
Guido van Rossuma93b8481998-06-23 19:31:19 +0000285
286
Guido van Rossumd90ae191998-10-19 18:42:53 +0000287def interact(banner=None, readfunc=None, local=None):
Guido van Rossuma93b8481998-06-23 19:31:19 +0000288 """Closely emulate the interactive Python interpreter.
289
290 This is a backwards compatible interface to the InteractiveConsole
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000291 class. When readfunc is not specified, it attempts to import the
292 readline module to enable GNU readline if it is available.
Guido van Rossuma93b8481998-06-23 19:31:19 +0000293
294 Arguments (all optional, all default to None):
295
296 banner -- passed to InteractiveConsole.interact()
297 readfunc -- if not None, replaces InteractiveConsole.raw_input()
Guido van Rossumd90ae191998-10-19 18:42:53 +0000298 local -- passed to InteractiveInterpreter.__init__()
Guido van Rossuma93b8481998-06-23 19:31:19 +0000299
300 """
Guido van Rossumd90ae191998-10-19 18:42:53 +0000301 console = InteractiveConsole(local)
Guido van Rossuma93b8481998-06-23 19:31:19 +0000302 if readfunc is not None:
303 console.raw_input = readfunc
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000304 else:
305 try:
306 import readline
Brett Cannoncd171c82013-07-04 17:43:24 -0400307 except ImportError:
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000308 pass
Guido van Rossuma93b8481998-06-23 19:31:19 +0000309 console.interact(banner)
Guido van Rossum5227f0f1998-09-22 20:38:53 +0000310
311
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000312if __name__ == "__main__":
Alexander Belopolsky007a9032014-07-12 16:36:33 -0400313 parser = argparse.ArgumentParser()
314 parser.add_argument('-q', action='store_true',
315 help="don't print version and copyright messages")
316 args = parser.parse_args()
317 if args.q or sys.flags.quiet:
318 banner = ''
319 else:
320 banner = None
321 interact(banner)