1 | n/a | """Utilities needed to emulate Python's interactive interpreter. |
---|
2 | n/a | |
---|
3 | n/a | """ |
---|
4 | n/a | |
---|
5 | n/a | # Inspired by similar code by Jeff Epler and Fredrik Lundh. |
---|
6 | n/a | |
---|
7 | n/a | |
---|
8 | n/a | import sys |
---|
9 | n/a | import traceback |
---|
10 | n/a | import argparse |
---|
11 | n/a | from codeop import CommandCompiler, compile_command |
---|
12 | n/a | |
---|
13 | n/a | __all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", |
---|
14 | n/a | "compile_command"] |
---|
15 | n/a | |
---|
16 | n/a | class InteractiveInterpreter: |
---|
17 | n/a | """Base class for InteractiveConsole. |
---|
18 | n/a | |
---|
19 | n/a | This class deals with parsing and interpreter state (the user's |
---|
20 | n/a | namespace); it doesn't deal with input buffering or prompting or |
---|
21 | n/a | input file naming (the filename is always passed in explicitly). |
---|
22 | n/a | |
---|
23 | n/a | """ |
---|
24 | n/a | |
---|
25 | n/a | def __init__(self, locals=None): |
---|
26 | n/a | """Constructor. |
---|
27 | n/a | |
---|
28 | n/a | The optional 'locals' argument specifies the dictionary in |
---|
29 | n/a | which code will be executed; it defaults to a newly created |
---|
30 | n/a | dictionary with key "__name__" set to "__console__" and key |
---|
31 | n/a | "__doc__" set to None. |
---|
32 | n/a | |
---|
33 | n/a | """ |
---|
34 | n/a | if locals is None: |
---|
35 | n/a | locals = {"__name__": "__console__", "__doc__": None} |
---|
36 | n/a | self.locals = locals |
---|
37 | n/a | self.compile = CommandCompiler() |
---|
38 | n/a | |
---|
39 | n/a | def runsource(self, source, filename="<input>", symbol="single"): |
---|
40 | n/a | """Compile and run some source in the interpreter. |
---|
41 | n/a | |
---|
42 | n/a | Arguments are as for compile_command(). |
---|
43 | n/a | |
---|
44 | n/a | One several things can happen: |
---|
45 | n/a | |
---|
46 | n/a | 1) The input is incorrect; compile_command() raised an |
---|
47 | n/a | exception (SyntaxError or OverflowError). A syntax traceback |
---|
48 | n/a | will be printed by calling the showsyntaxerror() method. |
---|
49 | n/a | |
---|
50 | n/a | 2) The input is incomplete, and more input is required; |
---|
51 | n/a | compile_command() returned None. Nothing happens. |
---|
52 | n/a | |
---|
53 | n/a | 3) The input is complete; compile_command() returned a code |
---|
54 | n/a | object. The code is executed by calling self.runcode() (which |
---|
55 | n/a | also handles run-time exceptions, except for SystemExit). |
---|
56 | n/a | |
---|
57 | n/a | The return value is True in case 2, False in the other cases (unless |
---|
58 | n/a | an exception is raised). The return value can be used to |
---|
59 | n/a | decide whether to use sys.ps1 or sys.ps2 to prompt the next |
---|
60 | n/a | line. |
---|
61 | n/a | |
---|
62 | n/a | """ |
---|
63 | n/a | try: |
---|
64 | n/a | code = self.compile(source, filename, symbol) |
---|
65 | n/a | except (OverflowError, SyntaxError, ValueError): |
---|
66 | n/a | # Case 1 |
---|
67 | n/a | self.showsyntaxerror(filename) |
---|
68 | n/a | return False |
---|
69 | n/a | |
---|
70 | n/a | if code is None: |
---|
71 | n/a | # Case 2 |
---|
72 | n/a | return True |
---|
73 | n/a | |
---|
74 | n/a | # Case 3 |
---|
75 | n/a | self.runcode(code) |
---|
76 | n/a | return False |
---|
77 | n/a | |
---|
78 | n/a | def runcode(self, code): |
---|
79 | n/a | """Execute a code object. |
---|
80 | n/a | |
---|
81 | n/a | When an exception occurs, self.showtraceback() is called to |
---|
82 | n/a | display a traceback. All exceptions are caught except |
---|
83 | n/a | SystemExit, which is reraised. |
---|
84 | n/a | |
---|
85 | n/a | A note about KeyboardInterrupt: this exception may occur |
---|
86 | n/a | elsewhere in this code, and may not always be caught. The |
---|
87 | n/a | caller should be prepared to deal with it. |
---|
88 | n/a | |
---|
89 | n/a | """ |
---|
90 | n/a | try: |
---|
91 | n/a | exec(code, self.locals) |
---|
92 | n/a | except SystemExit: |
---|
93 | n/a | raise |
---|
94 | n/a | except: |
---|
95 | n/a | self.showtraceback() |
---|
96 | n/a | |
---|
97 | n/a | def showsyntaxerror(self, filename=None): |
---|
98 | n/a | """Display the syntax error that just occurred. |
---|
99 | n/a | |
---|
100 | n/a | This doesn't display a stack trace because there isn't one. |
---|
101 | n/a | |
---|
102 | n/a | If a filename is given, it is stuffed in the exception instead |
---|
103 | n/a | of what was there before (because Python's parser always uses |
---|
104 | n/a | "<string>" when reading from a string). |
---|
105 | n/a | |
---|
106 | n/a | The output is written by self.write(), below. |
---|
107 | n/a | |
---|
108 | n/a | """ |
---|
109 | n/a | type, value, tb = sys.exc_info() |
---|
110 | n/a | sys.last_type = type |
---|
111 | n/a | sys.last_value = value |
---|
112 | n/a | sys.last_traceback = tb |
---|
113 | n/a | if filename and type is SyntaxError: |
---|
114 | n/a | # Work hard to stuff the correct filename in the exception |
---|
115 | n/a | try: |
---|
116 | n/a | msg, (dummy_filename, lineno, offset, line) = value.args |
---|
117 | n/a | except ValueError: |
---|
118 | n/a | # Not the format we expect; leave it alone |
---|
119 | n/a | pass |
---|
120 | n/a | else: |
---|
121 | n/a | # Stuff in the right filename |
---|
122 | n/a | value = SyntaxError(msg, (filename, lineno, offset, line)) |
---|
123 | n/a | sys.last_value = value |
---|
124 | n/a | if sys.excepthook is sys.__excepthook__: |
---|
125 | n/a | lines = traceback.format_exception_only(type, value) |
---|
126 | n/a | self.write(''.join(lines)) |
---|
127 | n/a | else: |
---|
128 | n/a | # If someone has set sys.excepthook, we let that take precedence |
---|
129 | n/a | # over self.write |
---|
130 | n/a | sys.excepthook(type, value, tb) |
---|
131 | n/a | |
---|
132 | n/a | def showtraceback(self): |
---|
133 | n/a | """Display the exception that just occurred. |
---|
134 | n/a | |
---|
135 | n/a | We remove the first stack item because it is our own code. |
---|
136 | n/a | |
---|
137 | n/a | The output is written by self.write(), below. |
---|
138 | n/a | |
---|
139 | n/a | """ |
---|
140 | n/a | sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() |
---|
141 | n/a | sys.last_traceback = last_tb |
---|
142 | n/a | try: |
---|
143 | n/a | lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) |
---|
144 | n/a | if sys.excepthook is sys.__excepthook__: |
---|
145 | n/a | self.write(''.join(lines)) |
---|
146 | n/a | else: |
---|
147 | n/a | # If someone has set sys.excepthook, we let that take precedence |
---|
148 | n/a | # over self.write |
---|
149 | n/a | sys.excepthook(ei[0], ei[1], last_tb) |
---|
150 | n/a | finally: |
---|
151 | n/a | last_tb = ei = None |
---|
152 | n/a | |
---|
153 | n/a | def write(self, data): |
---|
154 | n/a | """Write a string. |
---|
155 | n/a | |
---|
156 | n/a | The base implementation writes to sys.stderr; a subclass may |
---|
157 | n/a | replace this with a different implementation. |
---|
158 | n/a | |
---|
159 | n/a | """ |
---|
160 | n/a | sys.stderr.write(data) |
---|
161 | n/a | |
---|
162 | n/a | |
---|
163 | n/a | class InteractiveConsole(InteractiveInterpreter): |
---|
164 | n/a | """Closely emulate the behavior of the interactive Python interpreter. |
---|
165 | n/a | |
---|
166 | n/a | This class builds on InteractiveInterpreter and adds prompting |
---|
167 | n/a | using the familiar sys.ps1 and sys.ps2, and input buffering. |
---|
168 | n/a | |
---|
169 | n/a | """ |
---|
170 | n/a | |
---|
171 | n/a | def __init__(self, locals=None, filename="<console>"): |
---|
172 | n/a | """Constructor. |
---|
173 | n/a | |
---|
174 | n/a | The optional locals argument will be passed to the |
---|
175 | n/a | InteractiveInterpreter base class. |
---|
176 | n/a | |
---|
177 | n/a | The optional filename argument should specify the (file)name |
---|
178 | n/a | of the input stream; it will show up in tracebacks. |
---|
179 | n/a | |
---|
180 | n/a | """ |
---|
181 | n/a | InteractiveInterpreter.__init__(self, locals) |
---|
182 | n/a | self.filename = filename |
---|
183 | n/a | self.resetbuffer() |
---|
184 | n/a | |
---|
185 | n/a | def resetbuffer(self): |
---|
186 | n/a | """Reset the input buffer.""" |
---|
187 | n/a | self.buffer = [] |
---|
188 | n/a | |
---|
189 | n/a | def interact(self, banner=None, exitmsg=None): |
---|
190 | n/a | """Closely emulate the interactive Python console. |
---|
191 | n/a | |
---|
192 | n/a | The optional banner argument specifies the banner to print |
---|
193 | n/a | before the first interaction; by default it prints a banner |
---|
194 | n/a | similar to the one printed by the real Python interpreter, |
---|
195 | n/a | followed by the current class name in parentheses (so as not |
---|
196 | n/a | to confuse this with the real interpreter -- since it's so |
---|
197 | n/a | close!). |
---|
198 | n/a | |
---|
199 | n/a | The optional exitmsg argument specifies the exit message |
---|
200 | n/a | printed when exiting. Pass the empty string to suppress |
---|
201 | n/a | printing an exit message. If exitmsg is not given or None, |
---|
202 | n/a | a default message is printed. |
---|
203 | n/a | |
---|
204 | n/a | """ |
---|
205 | n/a | try: |
---|
206 | n/a | sys.ps1 |
---|
207 | n/a | except AttributeError: |
---|
208 | n/a | sys.ps1 = ">>> " |
---|
209 | n/a | try: |
---|
210 | n/a | sys.ps2 |
---|
211 | n/a | except AttributeError: |
---|
212 | n/a | sys.ps2 = "... " |
---|
213 | n/a | cprt = 'Type "help", "copyright", "credits" or "license" for more information.' |
---|
214 | n/a | if banner is None: |
---|
215 | n/a | self.write("Python %s on %s\n%s\n(%s)\n" % |
---|
216 | n/a | (sys.version, sys.platform, cprt, |
---|
217 | n/a | self.__class__.__name__)) |
---|
218 | n/a | elif banner: |
---|
219 | n/a | self.write("%s\n" % str(banner)) |
---|
220 | n/a | more = 0 |
---|
221 | n/a | while 1: |
---|
222 | n/a | try: |
---|
223 | n/a | if more: |
---|
224 | n/a | prompt = sys.ps2 |
---|
225 | n/a | else: |
---|
226 | n/a | prompt = sys.ps1 |
---|
227 | n/a | try: |
---|
228 | n/a | line = self.raw_input(prompt) |
---|
229 | n/a | except EOFError: |
---|
230 | n/a | self.write("\n") |
---|
231 | n/a | break |
---|
232 | n/a | else: |
---|
233 | n/a | more = self.push(line) |
---|
234 | n/a | except KeyboardInterrupt: |
---|
235 | n/a | self.write("\nKeyboardInterrupt\n") |
---|
236 | n/a | self.resetbuffer() |
---|
237 | n/a | more = 0 |
---|
238 | n/a | if exitmsg is None: |
---|
239 | n/a | self.write('now exiting %s...\n' % self.__class__.__name__) |
---|
240 | n/a | elif exitmsg != '': |
---|
241 | n/a | self.write('%s\n' % exitmsg) |
---|
242 | n/a | |
---|
243 | n/a | def push(self, line): |
---|
244 | n/a | """Push a line to the interpreter. |
---|
245 | n/a | |
---|
246 | n/a | The line should not have a trailing newline; it may have |
---|
247 | n/a | internal newlines. The line is appended to a buffer and the |
---|
248 | n/a | interpreter's runsource() method is called with the |
---|
249 | n/a | concatenated contents of the buffer as source. If this |
---|
250 | n/a | indicates that the command was executed or invalid, the buffer |
---|
251 | n/a | is reset; otherwise, the command is incomplete, and the buffer |
---|
252 | n/a | is left as it was after the line was appended. The return |
---|
253 | n/a | value is 1 if more input is required, 0 if the line was dealt |
---|
254 | n/a | with in some way (this is the same as runsource()). |
---|
255 | n/a | |
---|
256 | n/a | """ |
---|
257 | n/a | self.buffer.append(line) |
---|
258 | n/a | source = "\n".join(self.buffer) |
---|
259 | n/a | more = self.runsource(source, self.filename) |
---|
260 | n/a | if not more: |
---|
261 | n/a | self.resetbuffer() |
---|
262 | n/a | return more |
---|
263 | n/a | |
---|
264 | n/a | def raw_input(self, prompt=""): |
---|
265 | n/a | """Write a prompt and read a line. |
---|
266 | n/a | |
---|
267 | n/a | The returned line does not include the trailing newline. |
---|
268 | n/a | When the user enters the EOF key sequence, EOFError is raised. |
---|
269 | n/a | |
---|
270 | n/a | The base implementation uses the built-in function |
---|
271 | n/a | input(); a subclass may replace this with a different |
---|
272 | n/a | implementation. |
---|
273 | n/a | |
---|
274 | n/a | """ |
---|
275 | n/a | return input(prompt) |
---|
276 | n/a | |
---|
277 | n/a | |
---|
278 | n/a | |
---|
279 | n/a | def interact(banner=None, readfunc=None, local=None, exitmsg=None): |
---|
280 | n/a | """Closely emulate the interactive Python interpreter. |
---|
281 | n/a | |
---|
282 | n/a | This is a backwards compatible interface to the InteractiveConsole |
---|
283 | n/a | class. When readfunc is not specified, it attempts to import the |
---|
284 | n/a | readline module to enable GNU readline if it is available. |
---|
285 | n/a | |
---|
286 | n/a | Arguments (all optional, all default to None): |
---|
287 | n/a | |
---|
288 | n/a | banner -- passed to InteractiveConsole.interact() |
---|
289 | n/a | readfunc -- if not None, replaces InteractiveConsole.raw_input() |
---|
290 | n/a | local -- passed to InteractiveInterpreter.__init__() |
---|
291 | n/a | exitmsg -- passed to InteractiveConsole.interact() |
---|
292 | n/a | |
---|
293 | n/a | """ |
---|
294 | n/a | console = InteractiveConsole(local) |
---|
295 | n/a | if readfunc is not None: |
---|
296 | n/a | console.raw_input = readfunc |
---|
297 | n/a | else: |
---|
298 | n/a | try: |
---|
299 | n/a | import readline |
---|
300 | n/a | except ImportError: |
---|
301 | n/a | pass |
---|
302 | n/a | console.interact(banner, exitmsg) |
---|
303 | n/a | |
---|
304 | n/a | |
---|
305 | n/a | if __name__ == "__main__": |
---|
306 | n/a | parser = argparse.ArgumentParser() |
---|
307 | n/a | parser.add_argument('-q', action='store_true', |
---|
308 | n/a | help="don't print version and copyright messages") |
---|
309 | n/a | args = parser.parse_args() |
---|
310 | n/a | if args.q or sys.flags.quiet: |
---|
311 | n/a | banner = '' |
---|
312 | n/a | else: |
---|
313 | n/a | banner = None |
---|
314 | n/a | interact(banner) |
---|