Show More
@@ -1,585 +1,589 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Pdb debugger class. |
|
4 | 4 | |
|
5 | 5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
6 | 6 | the command line completion of other programs which include this isn't |
|
7 | 7 | damaged. |
|
8 | 8 | |
|
9 | 9 | In the future, this class will be expanded with improvements over the standard |
|
10 | 10 | pdb. |
|
11 | 11 | |
|
12 | 12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
13 | 13 | changes. Licensing should therefore be under the standard Python terms. For |
|
14 | 14 | details on the PSF (Python Software Foundation) standard license, see: |
|
15 | 15 | |
|
16 | 16 | http://www.python.org/2.2.3/license.html""" |
|
17 | 17 | |
|
18 | 18 | #***************************************************************************** |
|
19 | 19 | # |
|
20 | 20 | # This file is licensed under the PSF license. |
|
21 | 21 | # |
|
22 | 22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
23 | 23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
24 | 24 | # |
|
25 | 25 | # |
|
26 | 26 | #***************************************************************************** |
|
27 | 27 | from __future__ import print_function |
|
28 | 28 | |
|
29 | 29 | import bdb |
|
30 | 30 | import functools |
|
31 | 31 | import inspect |
|
32 | 32 | import sys |
|
33 | 33 | |
|
34 | 34 | from IPython import get_ipython |
|
35 | 35 | from IPython.utils import PyColorize, ulinecache |
|
36 | 36 | from IPython.utils import coloransi, py3compat |
|
37 | 37 | from IPython.core.excolors import exception_colors |
|
38 | 38 | from IPython.testing.skipdoctest import skip_doctest |
|
39 | 39 | |
|
40 | 40 | |
|
41 | 41 | prompt = 'ipdb> ' |
|
42 | 42 | |
|
43 | 43 | #We have to check this directly from sys.argv, config struct not yet available |
|
44 | 44 | from pdb import Pdb as OldPdb |
|
45 | 45 | |
|
46 | 46 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
47 | 47 | # it does so with some limitations. The rest of this support is implemented in |
|
48 | 48 | # the Tracer constructor. |
|
49 | 49 | |
|
50 | 50 | def make_arrow(pad): |
|
51 | 51 | """generate the leading arrow in front of traceback or debugger""" |
|
52 | 52 | if pad >= 2: |
|
53 | 53 | return '-'*(pad-2) + '> ' |
|
54 | 54 | elif pad == 1: |
|
55 | 55 | return '>' |
|
56 | 56 | return '' |
|
57 | 57 | |
|
58 | 58 | |
|
59 | 59 | def BdbQuit_excepthook(et, ev, tb, excepthook=None): |
|
60 | 60 | """Exception hook which handles `BdbQuit` exceptions. |
|
61 | 61 | |
|
62 | 62 | All other exceptions are processed using the `excepthook` |
|
63 | 63 | parameter. |
|
64 | 64 | """ |
|
65 | 65 | if et==bdb.BdbQuit: |
|
66 | 66 | print('Exiting Debugger.') |
|
67 | 67 | elif excepthook is not None: |
|
68 | 68 | excepthook(et, ev, tb) |
|
69 | 69 | else: |
|
70 | 70 | # Backwards compatibility. Raise deprecation warning? |
|
71 | 71 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
72 | 72 | |
|
73 | 73 | def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): |
|
74 | 74 | print('Exiting Debugger.') |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | class Tracer(object): |
|
78 | 78 | """Class for local debugging, similar to pdb.set_trace. |
|
79 | 79 | |
|
80 | 80 | Instances of this class, when called, behave like pdb.set_trace, but |
|
81 | 81 | providing IPython's enhanced capabilities. |
|
82 | 82 | |
|
83 | 83 | This is implemented as a class which must be initialized in your own code |
|
84 | 84 | and not as a standalone function because we need to detect at runtime |
|
85 | 85 | whether IPython is already active or not. That detection is done in the |
|
86 | 86 | constructor, ensuring that this code plays nicely with a running IPython, |
|
87 | 87 | while functioning acceptably (though with limitations) if outside of it. |
|
88 | 88 | """ |
|
89 | 89 | |
|
90 | 90 | @skip_doctest |
|
91 | 91 | def __init__(self, colors=None): |
|
92 | 92 | """Create a local debugger instance. |
|
93 | 93 | |
|
94 | 94 | Parameters |
|
95 | 95 | ---------- |
|
96 | 96 | |
|
97 | 97 | colors : str, optional |
|
98 | 98 | The name of the color scheme to use, it must be one of IPython's |
|
99 | 99 | valid color schemes. If not given, the function will default to |
|
100 | 100 | the current IPython scheme when running inside IPython, and to |
|
101 | 101 | 'NoColor' otherwise. |
|
102 | 102 | |
|
103 | 103 | Examples |
|
104 | 104 | -------- |
|
105 | 105 | :: |
|
106 | 106 | |
|
107 | 107 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
108 | 108 | |
|
109 | 109 | Later in your code:: |
|
110 | 110 | |
|
111 | 111 | debug_here() # -> will open up the debugger at that point. |
|
112 | 112 | |
|
113 | 113 | Once the debugger activates, you can use all of its regular commands to |
|
114 | 114 | step through code, set breakpoints, etc. See the pdb documentation |
|
115 | 115 | from the Python standard library for usage details. |
|
116 | 116 | """ |
|
117 | 117 | |
|
118 | 118 | ip = get_ipython() |
|
119 | 119 | if ip is None: |
|
120 | 120 | # Outside of ipython, we set our own exception hook manually |
|
121 | 121 | sys.excepthook = functools.partial(BdbQuit_excepthook, |
|
122 | 122 | excepthook=sys.excepthook) |
|
123 | 123 | def_colors = 'NoColor' |
|
124 | 124 | else: |
|
125 | 125 | # In ipython, we use its custom exception handler mechanism |
|
126 | 126 | def_colors = ip.colors |
|
127 | 127 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) |
|
128 | 128 | |
|
129 | 129 | if colors is None: |
|
130 | 130 | colors = def_colors |
|
131 | 131 | |
|
132 | 132 | # The stdlib debugger internally uses a modified repr from the `repr` |
|
133 | 133 | # module, that limits the length of printed strings to a hardcoded |
|
134 | 134 | # limit of 30 characters. That much trimming is too aggressive, let's |
|
135 | 135 | # at least raise that limit to 80 chars, which should be enough for |
|
136 | 136 | # most interactive uses. |
|
137 | 137 | try: |
|
138 | 138 | try: |
|
139 | 139 | from reprlib import aRepr # Py 3 |
|
140 | 140 | except ImportError: |
|
141 | 141 | from repr import aRepr # Py 2 |
|
142 | 142 | aRepr.maxstring = 80 |
|
143 | 143 | except: |
|
144 | 144 | # This is only a user-facing convenience, so any error we encounter |
|
145 | 145 | # here can be warned about but can be otherwise ignored. These |
|
146 | 146 | # printouts will tell us about problems if this API changes |
|
147 | 147 | import traceback |
|
148 | 148 | traceback.print_exc() |
|
149 | 149 | |
|
150 | 150 | self.debugger = Pdb(colors) |
|
151 | 151 | |
|
152 | 152 | def __call__(self): |
|
153 | 153 | """Starts an interactive debugger at the point where called. |
|
154 | 154 | |
|
155 | 155 | This is similar to the pdb.set_trace() function from the std lib, but |
|
156 | 156 | using IPython's enhanced debugger.""" |
|
157 | 157 | |
|
158 | 158 | self.debugger.set_trace(sys._getframe().f_back) |
|
159 | 159 | |
|
160 | 160 | |
|
161 | 161 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
162 | 162 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
163 | 163 | for the ``do_...`` commands that hook into the help system. |
|
164 | 164 | Adapted from from a comp.lang.python posting |
|
165 | 165 | by Duncan Booth.""" |
|
166 | 166 | def wrapper(*args, **kw): |
|
167 | 167 | return new_fn(*args, **kw) |
|
168 | 168 | if old_fn.__doc__: |
|
169 | 169 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
170 | 170 | return wrapper |
|
171 | 171 | |
|
172 | 172 | |
|
173 | 173 | def _file_lines(fname): |
|
174 | 174 | """Return the contents of a named file as a list of lines. |
|
175 | 175 | |
|
176 | 176 | This function never raises an IOError exception: if the file can't be |
|
177 | 177 | read, it simply returns an empty list.""" |
|
178 | 178 | |
|
179 | 179 | try: |
|
180 | 180 | outfile = open(fname) |
|
181 | 181 | except IOError: |
|
182 | 182 | return [] |
|
183 | 183 | else: |
|
184 | 184 | out = outfile.readlines() |
|
185 | 185 | outfile.close() |
|
186 | 186 | return out |
|
187 | 187 | |
|
188 | 188 | |
|
189 | 189 | class Pdb(OldPdb, object): |
|
190 | 190 | """Modified Pdb class, does not load readline.""" |
|
191 | 191 | |
|
192 | 192 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
193 | 193 | stdin=None, stdout=None, context=5): |
|
194 | 194 | |
|
195 | 195 | # Parent constructor: |
|
196 | 196 | try: |
|
197 | 197 | self.context=int(context) |
|
198 | 198 | if self.context <= 0: |
|
199 | 199 | raise ValueError("Context must be a positive integer") |
|
200 | 200 | except (TypeError, ValueError): |
|
201 | 201 | raise ValueError("Context must be a positive integer") |
|
202 | 202 | |
|
203 | 203 | OldPdb.__init__(self, completekey, stdin, stdout) |
|
204 | 204 | |
|
205 | 205 | # IPython changes... |
|
206 | 206 | self.shell = get_ipython() |
|
207 | 207 | |
|
208 | 208 | if self.shell is None: |
|
209 | 209 | # No IPython instance running, we must create one |
|
210 | 210 | from IPython.terminal.interactiveshell import \ |
|
211 | 211 | TerminalInteractiveShell |
|
212 | 212 | self.shell = TerminalInteractiveShell.instance() |
|
213 | 213 | |
|
214 | 214 | self.aliases = {} |
|
215 | 215 | |
|
216 | 216 | # Create color table: we copy the default one from the traceback |
|
217 | 217 | # module and add a few attributes needed for debugging |
|
218 | 218 | self.color_scheme_table = exception_colors() |
|
219 | 219 | |
|
220 | 220 | # shorthands |
|
221 | 221 | C = coloransi.TermColors |
|
222 | 222 | cst = self.color_scheme_table |
|
223 | 223 | |
|
224 | 224 | cst['NoColor'].colors.prompt = C.NoColor |
|
225 | 225 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
226 | 226 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
227 | 227 | |
|
228 | 228 | cst['Linux'].colors.prompt = C.Green |
|
229 | 229 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
230 | 230 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
231 | 231 | |
|
232 | 232 | cst['LightBG'].colors.prompt = C.Blue |
|
233 | 233 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
234 | 234 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
235 | 235 | |
|
236 | cst['Neutral'].colors.prompt = C.Blue | |
|
237 | cst['Neutral'].colors.breakpoint_enabled = C.LightRed | |
|
238 | cst['Neutral'].colors.breakpoint_disabled = C.Red | |
|
239 | ||
|
236 | 240 | self.set_colors(color_scheme) |
|
237 | 241 | |
|
238 | 242 | # Add a python parser so we can syntax highlight source while |
|
239 | 243 | # debugging. |
|
240 | 244 | self.parser = PyColorize.Parser() |
|
241 | 245 | |
|
242 | 246 | # Set the prompt - the default prompt is '(Pdb)' |
|
243 | 247 | self.prompt = prompt |
|
244 | 248 | |
|
245 | 249 | def set_colors(self, scheme): |
|
246 | 250 | """Shorthand access to the color table scheme selector method.""" |
|
247 | 251 | self.color_scheme_table.set_active_scheme(scheme) |
|
248 | 252 | |
|
249 | 253 | def interaction(self, frame, traceback): |
|
250 | 254 | try: |
|
251 | 255 | OldPdb.interaction(self, frame, traceback) |
|
252 | 256 | except KeyboardInterrupt: |
|
253 | 257 | sys.stdout.write('\n' + self.shell.get_exception_only()) |
|
254 | 258 | |
|
255 | 259 | def parseline(self, line): |
|
256 | 260 | if line.startswith("!!"): |
|
257 | 261 | # Force standard behavior. |
|
258 | 262 | return super(Pdb, self).parseline(line[2:]) |
|
259 | 263 | # "Smart command mode" from pdb++: don't execute commands if a variable |
|
260 | 264 | # with the same name exists. |
|
261 | 265 | cmd, arg, newline = super(Pdb, self).parseline(line) |
|
262 | 266 | # Fix for #9611: Do not trigger smart command if the command is `exit` |
|
263 | 267 | # or `quit` and it would resolve to their *global* value (the |
|
264 | 268 | # `ExitAutocall` object). Just checking that it is not present in the |
|
265 | 269 | # locals dict is not enough as locals and globals match at the |
|
266 | 270 | # toplevel. |
|
267 | 271 | if ((cmd in self.curframe.f_locals or cmd in self.curframe.f_globals) |
|
268 | 272 | and not (cmd in ["exit", "quit"] |
|
269 | 273 | and (self.curframe.f_locals is self.curframe.f_globals |
|
270 | 274 | or cmd not in self.curframe.f_locals))): |
|
271 | 275 | return super(Pdb, self).parseline("!" + line) |
|
272 | 276 | return super(Pdb, self).parseline(line) |
|
273 | 277 | |
|
274 | 278 | def new_do_up(self, arg): |
|
275 | 279 | OldPdb.do_up(self, arg) |
|
276 | 280 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
277 | 281 | |
|
278 | 282 | def new_do_down(self, arg): |
|
279 | 283 | OldPdb.do_down(self, arg) |
|
280 | 284 | |
|
281 | 285 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
282 | 286 | |
|
283 | 287 | def new_do_frame(self, arg): |
|
284 | 288 | OldPdb.do_frame(self, arg) |
|
285 | 289 | |
|
286 | 290 | def new_do_quit(self, arg): |
|
287 | 291 | |
|
288 | 292 | if hasattr(self, 'old_all_completions'): |
|
289 | 293 | self.shell.Completer.all_completions=self.old_all_completions |
|
290 | 294 | |
|
291 | 295 | return OldPdb.do_quit(self, arg) |
|
292 | 296 | |
|
293 | 297 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
294 | 298 | |
|
295 | 299 | def new_do_restart(self, arg): |
|
296 | 300 | """Restart command. In the context of ipython this is exactly the same |
|
297 | 301 | thing as 'quit'.""" |
|
298 | 302 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
299 | 303 | return self.do_quit(arg) |
|
300 | 304 | |
|
301 | 305 | def print_stack_trace(self, context=None): |
|
302 | 306 | if context is None: |
|
303 | 307 | context = self.context |
|
304 | 308 | try: |
|
305 | 309 | context=int(context) |
|
306 | 310 | if context <= 0: |
|
307 | 311 | raise ValueError("Context must be a positive integer") |
|
308 | 312 | except (TypeError, ValueError): |
|
309 | 313 | raise ValueError("Context must be a positive integer") |
|
310 | 314 | try: |
|
311 | 315 | for frame_lineno in self.stack: |
|
312 | 316 | self.print_stack_entry(frame_lineno, context=context) |
|
313 | 317 | except KeyboardInterrupt: |
|
314 | 318 | pass |
|
315 | 319 | |
|
316 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', | |
|
320 | def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ', | |
|
317 | 321 | context=None): |
|
318 | 322 | if context is None: |
|
319 | 323 | context = self.context |
|
320 | 324 | try: |
|
321 | 325 | context=int(context) |
|
322 | 326 | if context <= 0: |
|
323 | 327 | raise ValueError("Context must be a positive integer") |
|
324 | 328 | except (TypeError, ValueError): |
|
325 | 329 | raise ValueError("Context must be a positive integer") |
|
326 | 330 | print(self.format_stack_entry(frame_lineno, '', context)) |
|
327 | 331 | |
|
328 | 332 | # vds: >> |
|
329 | 333 | frame, lineno = frame_lineno |
|
330 | 334 | filename = frame.f_code.co_filename |
|
331 | 335 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
332 | 336 | # vds: << |
|
333 | 337 | |
|
334 | 338 | def format_stack_entry(self, frame_lineno, lprefix=': ', context=None): |
|
335 | 339 | if context is None: |
|
336 | 340 | context = self.context |
|
337 | 341 | try: |
|
338 | 342 | context=int(context) |
|
339 | 343 | if context <= 0: |
|
340 | 344 | print("Context must be a positive integer") |
|
341 | 345 | except (TypeError, ValueError): |
|
342 | 346 | print("Context must be a positive integer") |
|
343 | 347 | try: |
|
344 | 348 | import reprlib # Py 3 |
|
345 | 349 | except ImportError: |
|
346 | 350 | import repr as reprlib # Py 2 |
|
347 | 351 | |
|
348 | 352 | ret = [] |
|
349 | 353 | |
|
350 | 354 | Colors = self.color_scheme_table.active_colors |
|
351 | 355 | ColorsNormal = Colors.Normal |
|
352 | 356 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
353 | 357 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
354 | 358 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
355 | 359 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
356 | 360 | ColorsNormal) |
|
357 | 361 | |
|
358 | 362 | frame, lineno = frame_lineno |
|
359 | 363 | |
|
360 | 364 | return_value = '' |
|
361 | 365 | if '__return__' in frame.f_locals: |
|
362 | 366 | rv = frame.f_locals['__return__'] |
|
363 | 367 | #return_value += '->' |
|
364 | 368 | return_value += reprlib.repr(rv) + '\n' |
|
365 | 369 | ret.append(return_value) |
|
366 | 370 | |
|
367 | 371 | #s = filename + '(' + `lineno` + ')' |
|
368 | 372 | filename = self.canonic(frame.f_code.co_filename) |
|
369 | 373 | link = tpl_link % py3compat.cast_unicode(filename) |
|
370 | 374 | |
|
371 | 375 | if frame.f_code.co_name: |
|
372 | 376 | func = frame.f_code.co_name |
|
373 | 377 | else: |
|
374 | 378 | func = "<lambda>" |
|
375 | 379 | |
|
376 | 380 | call = '' |
|
377 | 381 | if func != '?': |
|
378 | 382 | if '__args__' in frame.f_locals: |
|
379 | 383 | args = reprlib.repr(frame.f_locals['__args__']) |
|
380 | 384 | else: |
|
381 | 385 | args = '()' |
|
382 | 386 | call = tpl_call % (func, args) |
|
383 | 387 | |
|
384 | 388 | # The level info should be generated in the same format pdb uses, to |
|
385 | 389 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
386 | 390 | if frame is self.curframe: |
|
387 | 391 | ret.append('> ') |
|
388 | 392 | else: |
|
389 | 393 | ret.append(' ') |
|
390 | 394 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) |
|
391 | 395 | |
|
392 | 396 | start = lineno - 1 - context//2 |
|
393 | 397 | lines = ulinecache.getlines(filename) |
|
394 | 398 | start = min(start, len(lines) - context) |
|
395 | 399 | start = max(start, 0) |
|
396 | 400 | lines = lines[start : start + context] |
|
397 | 401 | |
|
398 | 402 | for i,line in enumerate(lines): |
|
399 | 403 | show_arrow = (start + 1 + i == lineno) |
|
400 | 404 | linetpl = (frame is self.curframe or show_arrow) \ |
|
401 | 405 | and tpl_line_em \ |
|
402 | 406 | or tpl_line |
|
403 | 407 | ret.append(self.__format_line(linetpl, filename, |
|
404 | 408 | start + 1 + i, line, |
|
405 | 409 | arrow = show_arrow) ) |
|
406 | 410 | return ''.join(ret) |
|
407 | 411 | |
|
408 | 412 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
409 | 413 | bp_mark = "" |
|
410 | 414 | bp_mark_color = "" |
|
411 | 415 | |
|
412 | 416 | scheme = self.color_scheme_table.active_scheme_name |
|
413 | 417 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
414 | 418 | if not err: line = new_line |
|
415 | 419 | |
|
416 | 420 | bp = None |
|
417 | 421 | if lineno in self.get_file_breaks(filename): |
|
418 | 422 | bps = self.get_breaks(filename, lineno) |
|
419 | 423 | bp = bps[-1] |
|
420 | 424 | |
|
421 | 425 | if bp: |
|
422 | 426 | Colors = self.color_scheme_table.active_colors |
|
423 | 427 | bp_mark = str(bp.number) |
|
424 | 428 | bp_mark_color = Colors.breakpoint_enabled |
|
425 | 429 | if not bp.enabled: |
|
426 | 430 | bp_mark_color = Colors.breakpoint_disabled |
|
427 | 431 | |
|
428 | 432 | numbers_width = 7 |
|
429 | 433 | if arrow: |
|
430 | 434 | # This is the line with the error |
|
431 | 435 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
432 | 436 | num = '%s%s' % (make_arrow(pad), str(lineno)) |
|
433 | 437 | else: |
|
434 | 438 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
435 | 439 | |
|
436 | 440 | return tpl_line % (bp_mark_color + bp_mark, num, line) |
|
437 | 441 | |
|
438 | 442 | |
|
439 | 443 | def print_list_lines(self, filename, first, last): |
|
440 | 444 | """The printing (as opposed to the parsing part of a 'list' |
|
441 | 445 | command.""" |
|
442 | 446 | try: |
|
443 | 447 | Colors = self.color_scheme_table.active_colors |
|
444 | 448 | ColorsNormal = Colors.Normal |
|
445 | 449 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
446 | 450 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
447 | 451 | src = [] |
|
448 | 452 | if filename == "<string>" and hasattr(self, "_exec_filename"): |
|
449 | 453 | filename = self._exec_filename |
|
450 | 454 | |
|
451 | 455 | for lineno in range(first, last+1): |
|
452 | 456 | line = ulinecache.getline(filename, lineno) |
|
453 | 457 | if not line: |
|
454 | 458 | break |
|
455 | 459 | |
|
456 | 460 | if lineno == self.curframe.f_lineno: |
|
457 | 461 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
458 | 462 | else: |
|
459 | 463 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
460 | 464 | |
|
461 | 465 | src.append(line) |
|
462 | 466 | self.lineno = lineno |
|
463 | 467 | |
|
464 | 468 | print(''.join(src)) |
|
465 | 469 | |
|
466 | 470 | except KeyboardInterrupt: |
|
467 | 471 | pass |
|
468 | 472 | |
|
469 | 473 | def do_list(self, arg): |
|
470 | 474 | self.lastcmd = 'list' |
|
471 | 475 | last = None |
|
472 | 476 | if arg: |
|
473 | 477 | try: |
|
474 | 478 | x = eval(arg, {}, {}) |
|
475 | 479 | if type(x) == type(()): |
|
476 | 480 | first, last = x |
|
477 | 481 | first = int(first) |
|
478 | 482 | last = int(last) |
|
479 | 483 | if last < first: |
|
480 | 484 | # Assume it's a count |
|
481 | 485 | last = first + last |
|
482 | 486 | else: |
|
483 | 487 | first = max(1, int(x) - 5) |
|
484 | 488 | except: |
|
485 | 489 | print('*** Error in argument:', repr(arg)) |
|
486 | 490 | return |
|
487 | 491 | elif self.lineno is None: |
|
488 | 492 | first = max(1, self.curframe.f_lineno - 5) |
|
489 | 493 | else: |
|
490 | 494 | first = self.lineno + 1 |
|
491 | 495 | if last is None: |
|
492 | 496 | last = first + 10 |
|
493 | 497 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
494 | 498 | |
|
495 | 499 | # vds: >> |
|
496 | 500 | lineno = first |
|
497 | 501 | filename = self.curframe.f_code.co_filename |
|
498 | 502 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
499 | 503 | # vds: << |
|
500 | 504 | |
|
501 | 505 | do_l = do_list |
|
502 | 506 | |
|
503 | 507 | def getsourcelines(self, obj): |
|
504 | 508 | lines, lineno = inspect.findsource(obj) |
|
505 | 509 | if inspect.isframe(obj) and obj.f_globals is obj.f_locals: |
|
506 | 510 | # must be a module frame: do not try to cut a block out of it |
|
507 | 511 | return lines, 1 |
|
508 | 512 | elif inspect.ismodule(obj): |
|
509 | 513 | return lines, 1 |
|
510 | 514 | return inspect.getblock(lines[lineno:]), lineno+1 |
|
511 | 515 | |
|
512 | 516 | def do_longlist(self, arg): |
|
513 | 517 | self.lastcmd = 'longlist' |
|
514 | 518 | try: |
|
515 | 519 | lines, lineno = self.getsourcelines(self.curframe) |
|
516 | 520 | except OSError as err: |
|
517 | 521 | self.error(err) |
|
518 | 522 | return |
|
519 | 523 | last = lineno + len(lines) |
|
520 | 524 | self.print_list_lines(self.curframe.f_code.co_filename, lineno, last) |
|
521 | 525 | do_ll = do_longlist |
|
522 | 526 | |
|
523 | 527 | def do_pdef(self, arg): |
|
524 | 528 | """Print the call signature for any callable object. |
|
525 | 529 | |
|
526 | 530 | The debugger interface to %pdef""" |
|
527 | 531 | namespaces = [('Locals', self.curframe.f_locals), |
|
528 | 532 | ('Globals', self.curframe.f_globals)] |
|
529 | 533 | self.shell.find_line_magic('pdef')(arg, namespaces=namespaces) |
|
530 | 534 | |
|
531 | 535 | def do_pdoc(self, arg): |
|
532 | 536 | """Print the docstring for an object. |
|
533 | 537 | |
|
534 | 538 | The debugger interface to %pdoc.""" |
|
535 | 539 | namespaces = [('Locals', self.curframe.f_locals), |
|
536 | 540 | ('Globals', self.curframe.f_globals)] |
|
537 | 541 | self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces) |
|
538 | 542 | |
|
539 | 543 | def do_pfile(self, arg): |
|
540 | 544 | """Print (or run through pager) the file where an object is defined. |
|
541 | 545 | |
|
542 | 546 | The debugger interface to %pfile. |
|
543 | 547 | """ |
|
544 | 548 | namespaces = [('Locals', self.curframe.f_locals), |
|
545 | 549 | ('Globals', self.curframe.f_globals)] |
|
546 | 550 | self.shell.find_line_magic('pfile')(arg, namespaces=namespaces) |
|
547 | 551 | |
|
548 | 552 | def do_pinfo(self, arg): |
|
549 | 553 | """Provide detailed information about an object. |
|
550 | 554 | |
|
551 | 555 | The debugger interface to %pinfo, i.e., obj?.""" |
|
552 | 556 | namespaces = [('Locals', self.curframe.f_locals), |
|
553 | 557 | ('Globals', self.curframe.f_globals)] |
|
554 | 558 | self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces) |
|
555 | 559 | |
|
556 | 560 | def do_pinfo2(self, arg): |
|
557 | 561 | """Provide extra detailed information about an object. |
|
558 | 562 | |
|
559 | 563 | The debugger interface to %pinfo2, i.e., obj??.""" |
|
560 | 564 | namespaces = [('Locals', self.curframe.f_locals), |
|
561 | 565 | ('Globals', self.curframe.f_globals)] |
|
562 | 566 | self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces) |
|
563 | 567 | |
|
564 | 568 | def do_psource(self, arg): |
|
565 | 569 | """Print (or run through pager) the source code for an object.""" |
|
566 | 570 | namespaces = [('Locals', self.curframe.f_locals), |
|
567 | 571 | ('Globals', self.curframe.f_globals)] |
|
568 | 572 | self.shell.find_line_magic('psource')(arg, namespaces=namespaces) |
|
569 | 573 | |
|
570 | 574 | if sys.version_info > (3, ): |
|
571 | 575 | def do_where(self, arg): |
|
572 | 576 | """w(here) |
|
573 | 577 | Print a stack trace, with the most recent frame at the bottom. |
|
574 | 578 | An arrow indicates the "current frame", which determines the |
|
575 | 579 | context of most commands. 'bt' is an alias for this command. |
|
576 | 580 | |
|
577 | 581 | Take a number as argument as an (optional) number of context line to |
|
578 | 582 | print""" |
|
579 | 583 | if arg: |
|
580 | 584 | context = int(arg) |
|
581 | 585 | self.print_stack_trace(context) |
|
582 | 586 | else: |
|
583 | 587 | self.print_stack_trace() |
|
584 | 588 | |
|
585 | 589 | do_w = do_where |
@@ -1,147 +1,176 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Color schemes for exception handling code in IPython. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | import warnings |
|
7 | 7 | |
|
8 | 8 | #***************************************************************************** |
|
9 | 9 | # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu> |
|
10 | 10 | # |
|
11 | 11 | # Distributed under the terms of the BSD License. The full license is in |
|
12 | 12 | # the file COPYING, distributed as part of this software. |
|
13 | 13 | #***************************************************************************** |
|
14 | 14 | |
|
15 | 15 | from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme |
|
16 | 16 | |
|
17 | 17 | def exception_colors(): |
|
18 | 18 | """Return a color table with fields for exception reporting. |
|
19 | 19 | |
|
20 | 20 | The table is an instance of ColorSchemeTable with schemes added for |
|
21 | 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled | |
|
21 | 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled | |
|
22 | 22 | in. |
|
23 | 23 | |
|
24 | 24 | Examples: |
|
25 | 25 | |
|
26 | 26 | >>> ec = exception_colors() |
|
27 | 27 | >>> ec.active_scheme_name |
|
28 | 28 | '' |
|
29 | 29 | >>> print(ec.active_colors) |
|
30 | 30 | None |
|
31 | 31 | |
|
32 | 32 | Now we activate a color scheme: |
|
33 | 33 | >>> ec.set_active_scheme('NoColor') |
|
34 | 34 | >>> ec.active_scheme_name |
|
35 | 35 | 'NoColor' |
|
36 | 36 | >>> sorted(ec.active_colors.keys()) |
|
37 | 37 | ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line', |
|
38 | 38 | 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName', |
|
39 | 39 | 'val', 'valEm'] |
|
40 | 40 | """ |
|
41 | 41 | |
|
42 | 42 | ex_colors = ColorSchemeTable() |
|
43 | 43 | |
|
44 | 44 | # Populate it with color schemes |
|
45 | 45 | C = TermColors # shorthand and local lookup |
|
46 | 46 | ex_colors.add_scheme(ColorScheme( |
|
47 | 47 | 'NoColor', |
|
48 | 48 | # The color to be used for the top line |
|
49 | 49 | topline = C.NoColor, |
|
50 | 50 | |
|
51 | 51 | # The colors to be used in the traceback |
|
52 | 52 | filename = C.NoColor, |
|
53 | 53 | lineno = C.NoColor, |
|
54 | 54 | name = C.NoColor, |
|
55 | 55 | vName = C.NoColor, |
|
56 | 56 | val = C.NoColor, |
|
57 | 57 | em = C.NoColor, |
|
58 | 58 | |
|
59 | 59 | # Emphasized colors for the last frame of the traceback |
|
60 | 60 | normalEm = C.NoColor, |
|
61 | 61 | filenameEm = C.NoColor, |
|
62 | 62 | linenoEm = C.NoColor, |
|
63 | 63 | nameEm = C.NoColor, |
|
64 | 64 | valEm = C.NoColor, |
|
65 | 65 | |
|
66 | 66 | # Colors for printing the exception |
|
67 | 67 | excName = C.NoColor, |
|
68 | 68 | line = C.NoColor, |
|
69 | 69 | caret = C.NoColor, |
|
70 | 70 | Normal = C.NoColor |
|
71 | 71 | )) |
|
72 | 72 | |
|
73 | 73 | # make some schemes as instances so we can copy them for modification easily |
|
74 | 74 | ex_colors.add_scheme(ColorScheme( |
|
75 | 75 | 'Linux', |
|
76 | 76 | # The color to be used for the top line |
|
77 | 77 | topline = C.LightRed, |
|
78 | 78 | |
|
79 | 79 | # The colors to be used in the traceback |
|
80 | 80 | filename = C.Green, |
|
81 | 81 | lineno = C.Green, |
|
82 | 82 | name = C.Purple, |
|
83 | 83 | vName = C.Cyan, |
|
84 | 84 | val = C.Green, |
|
85 | 85 | em = C.LightCyan, |
|
86 | 86 | |
|
87 | 87 | # Emphasized colors for the last frame of the traceback |
|
88 | 88 | normalEm = C.LightCyan, |
|
89 | 89 | filenameEm = C.LightGreen, |
|
90 | 90 | linenoEm = C.LightGreen, |
|
91 | 91 | nameEm = C.LightPurple, |
|
92 | 92 | valEm = C.LightBlue, |
|
93 | 93 | |
|
94 | 94 | # Colors for printing the exception |
|
95 | 95 | excName = C.LightRed, |
|
96 | 96 | line = C.Yellow, |
|
97 | 97 | caret = C.White, |
|
98 | 98 | Normal = C.Normal |
|
99 | 99 | )) |
|
100 | 100 | |
|
101 | 101 | # For light backgrounds, swap dark/light colors |
|
102 | 102 | ex_colors.add_scheme(ColorScheme( |
|
103 | 103 | 'LightBG', |
|
104 | 104 | # The color to be used for the top line |
|
105 | 105 | topline = C.Red, |
|
106 | 106 | |
|
107 | 107 | # The colors to be used in the traceback |
|
108 | 108 | filename = C.LightGreen, |
|
109 | 109 | lineno = C.LightGreen, |
|
110 | 110 | name = C.LightPurple, |
|
111 | 111 | vName = C.Cyan, |
|
112 | 112 | val = C.LightGreen, |
|
113 | 113 | em = C.Cyan, |
|
114 | 114 | |
|
115 | 115 | # Emphasized colors for the last frame of the traceback |
|
116 | 116 | normalEm = C.Cyan, |
|
117 | 117 | filenameEm = C.Green, |
|
118 | 118 | linenoEm = C.Green, |
|
119 | 119 | nameEm = C.Purple, |
|
120 | 120 | valEm = C.Blue, |
|
121 | 121 | |
|
122 | 122 | # Colors for printing the exception |
|
123 | 123 | excName = C.Red, |
|
124 | 124 | #line = C.Brown, # brown often is displayed as yellow |
|
125 | 125 | line = C.Red, |
|
126 | 126 | caret = C.Normal, |
|
127 | 127 | Normal = C.Normal, |
|
128 | 128 | )) |
|
129 | 129 | |
|
130 | ex_colors.add_scheme(ColorScheme( | |
|
131 | 'Neutral', | |
|
132 | # The color to be used for the top line | |
|
133 | topline = C.Red, | |
|
134 | ||
|
135 | # The colors to be used in the traceback | |
|
136 | filename = C.LightGreen, | |
|
137 | lineno = C.LightGreen, | |
|
138 | name = C.LightPurple, | |
|
139 | vName = C.Cyan, | |
|
140 | val = C.LightGreen, | |
|
141 | em = C.Cyan, | |
|
142 | ||
|
143 | # Emphasized colors for the last frame of the traceback | |
|
144 | normalEm = C.Cyan, | |
|
145 | filenameEm = C.Green, | |
|
146 | linenoEm = C.Green, | |
|
147 | nameEm = C.Purple, | |
|
148 | valEm = C.Blue, | |
|
149 | ||
|
150 | # Colors for printing the exception | |
|
151 | excName = C.Red, | |
|
152 | #line = C.Brown, # brown often is displayed as yellow | |
|
153 | line = C.Red, | |
|
154 | caret = C.Normal, | |
|
155 | Normal = C.Normal, | |
|
156 | )) | |
|
157 | ||
|
158 | ||
|
130 | 159 | return ex_colors |
|
131 | 160 | |
|
132 | 161 | class Deprec(object): |
|
133 | 162 | |
|
134 | 163 | def __init__(self, wrapped_obj): |
|
135 | 164 | self.wrapped=wrapped_obj |
|
136 | 165 | |
|
137 | 166 | def __getattr__(self, name): |
|
138 | 167 | val = getattr(self.wrapped, name) |
|
139 | 168 | warnings.warn("Using ExceptionColors global is deprecated and will be removed in IPython 6.0", DeprecationWarning) |
|
140 | 169 | # using getattr after warnings break ipydoctest in weird way for 3.5 |
|
141 | 170 | return val |
|
142 | 171 | |
|
143 | 172 | # For backwards compatibility, keep around a single global object. Note that |
|
144 | 173 | # this should NOT be used, the factory function should be used instead, since |
|
145 | 174 | # these objects are stateful and it's very easy to get strange bugs if any code |
|
146 | 175 | # modifies the module-level object's state. |
|
147 | 176 | ExceptionColors = Deprec(exception_colors()) |
@@ -1,3293 +1,3291 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Main IPython class.""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
6 | 6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
7 | 7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
8 | 8 | # |
|
9 | 9 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | 10 | # the file COPYING, distributed as part of this software. |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | |
|
13 | 13 | from __future__ import absolute_import, print_function |
|
14 | 14 | |
|
15 | 15 | import __future__ |
|
16 | 16 | import abc |
|
17 | 17 | import ast |
|
18 | 18 | import atexit |
|
19 | 19 | import functools |
|
20 | 20 | import os |
|
21 | 21 | import re |
|
22 | 22 | import runpy |
|
23 | 23 | import sys |
|
24 | 24 | import tempfile |
|
25 | 25 | import traceback |
|
26 | 26 | import types |
|
27 | 27 | import subprocess |
|
28 | 28 | import warnings |
|
29 | 29 | from io import open as io_open |
|
30 | 30 | |
|
31 | 31 | from pickleshare import PickleShareDB |
|
32 | 32 | |
|
33 | 33 | from traitlets.config.configurable import SingletonConfigurable |
|
34 | 34 | from IPython.core import oinspect |
|
35 | 35 | from IPython.core import magic |
|
36 | 36 | from IPython.core import page |
|
37 | 37 | from IPython.core import prefilter |
|
38 | 38 | from IPython.core import shadowns |
|
39 | 39 | from IPython.core import ultratb |
|
40 | 40 | from IPython.core.alias import Alias, AliasManager |
|
41 | 41 | from IPython.core.autocall import ExitAutocall |
|
42 | 42 | from IPython.core.builtin_trap import BuiltinTrap |
|
43 | 43 | from IPython.core.events import EventManager, available_events |
|
44 | 44 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
45 | 45 | from IPython.core.debugger import Pdb |
|
46 | 46 | from IPython.core.display_trap import DisplayTrap |
|
47 | 47 | from IPython.core.displayhook import DisplayHook |
|
48 | 48 | from IPython.core.displaypub import DisplayPublisher |
|
49 | 49 | from IPython.core.error import InputRejected, UsageError |
|
50 | 50 | from IPython.core.extensions import ExtensionManager |
|
51 | 51 | from IPython.core.formatters import DisplayFormatter |
|
52 | 52 | from IPython.core.history import HistoryManager |
|
53 | 53 | from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2 |
|
54 | 54 | from IPython.core.logger import Logger |
|
55 | 55 | from IPython.core.macro import Macro |
|
56 | 56 | from IPython.core.payload import PayloadManager |
|
57 | 57 | from IPython.core.prefilter import PrefilterManager |
|
58 | 58 | from IPython.core.profiledir import ProfileDir |
|
59 | 59 | from IPython.core.usage import default_banner |
|
60 | 60 | from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest |
|
61 | 61 | from IPython.utils import PyColorize |
|
62 | 62 | from IPython.utils import io |
|
63 | 63 | from IPython.utils import py3compat |
|
64 | 64 | from IPython.utils import openpy |
|
65 | 65 | from IPython.utils.contexts import NoOpContext |
|
66 | 66 | from IPython.utils.decorators import undoc |
|
67 | 67 | from IPython.utils.io import ask_yes_no |
|
68 | 68 | from IPython.utils.ipstruct import Struct |
|
69 | 69 | from IPython.paths import get_ipython_dir |
|
70 | 70 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists |
|
71 | 71 | from IPython.utils.process import system, getoutput |
|
72 | 72 | from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types, |
|
73 | 73 | with_metaclass, iteritems) |
|
74 | 74 | from IPython.utils.strdispatch import StrDispatch |
|
75 | 75 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
76 | 76 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter |
|
77 | 77 | from IPython.utils.tempdir import TemporaryDirectory |
|
78 | 78 | from traitlets import ( |
|
79 | 79 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
80 | 80 | observe, default, |
|
81 | 81 | ) |
|
82 | 82 | from warnings import warn |
|
83 | 83 | from logging import error |
|
84 | 84 | import IPython.core.hooks |
|
85 | 85 | |
|
86 | 86 | try: |
|
87 | 87 | import docrepr.sphinxify as sphx |
|
88 | 88 | |
|
89 | 89 | def sphinxify(doc): |
|
90 | 90 | with TemporaryDirectory() as dirname: |
|
91 | 91 | return { |
|
92 | 92 | 'text/html': sphx.sphinxify(doc, dirname), |
|
93 | 93 | 'text/plain': doc |
|
94 | 94 | } |
|
95 | 95 | except ImportError: |
|
96 | 96 | sphinxify = None |
|
97 | 97 | |
|
98 | 98 | |
|
99 | 99 | class ProvisionalWarning(DeprecationWarning): |
|
100 | 100 | """ |
|
101 | 101 | Warning class for unstable features |
|
102 | 102 | """ |
|
103 | 103 | pass |
|
104 | 104 | |
|
105 | 105 | #----------------------------------------------------------------------------- |
|
106 | 106 | # Globals |
|
107 | 107 | #----------------------------------------------------------------------------- |
|
108 | 108 | |
|
109 | 109 | # compiled regexps for autoindent management |
|
110 | 110 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
111 | 111 | |
|
112 | 112 | #----------------------------------------------------------------------------- |
|
113 | 113 | # Utilities |
|
114 | 114 | #----------------------------------------------------------------------------- |
|
115 | 115 | |
|
116 | 116 | @undoc |
|
117 | 117 | def softspace(file, newvalue): |
|
118 | 118 | """Copied from code.py, to remove the dependency""" |
|
119 | 119 | |
|
120 | 120 | oldvalue = 0 |
|
121 | 121 | try: |
|
122 | 122 | oldvalue = file.softspace |
|
123 | 123 | except AttributeError: |
|
124 | 124 | pass |
|
125 | 125 | try: |
|
126 | 126 | file.softspace = newvalue |
|
127 | 127 | except (AttributeError, TypeError): |
|
128 | 128 | # "attribute-less object" or "read-only attributes" |
|
129 | 129 | pass |
|
130 | 130 | return oldvalue |
|
131 | 131 | |
|
132 | 132 | @undoc |
|
133 | 133 | def no_op(*a, **kw): pass |
|
134 | 134 | |
|
135 | 135 | |
|
136 | 136 | class SpaceInInput(Exception): pass |
|
137 | 137 | |
|
138 | 138 | |
|
139 | 139 | def get_default_colors(): |
|
140 | if sys.platform=='darwin': | |
|
141 | return "LightBG" | |
|
142 | elif os.name=='nt': | |
|
143 |
|
|
|
144 | else: | |
|
145 | return 'Linux' | |
|
140 | "DEPRECATED" | |
|
141 | warn('get_default_color is Deprecated, and is `Neutral` on all platforms.', | |
|
142 | DeprecationWarning, stacklevel=2) | |
|
143 | return 'Neutral' | |
|
146 | 144 | |
|
147 | 145 | |
|
148 | 146 | class SeparateUnicode(Unicode): |
|
149 | 147 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
150 | 148 | |
|
151 | 149 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
152 | 150 | """ |
|
153 | 151 | |
|
154 | 152 | def validate(self, obj, value): |
|
155 | 153 | if value == '0': value = '' |
|
156 | 154 | value = value.replace('\\n','\n') |
|
157 | 155 | return super(SeparateUnicode, self).validate(obj, value) |
|
158 | 156 | |
|
159 | 157 | |
|
160 | 158 | @undoc |
|
161 | 159 | class DummyMod(object): |
|
162 | 160 | """A dummy module used for IPython's interactive module when |
|
163 | 161 | a namespace must be assigned to the module's __dict__.""" |
|
164 | 162 | pass |
|
165 | 163 | |
|
166 | 164 | |
|
167 | 165 | class ExecutionResult(object): |
|
168 | 166 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
169 | 167 | |
|
170 | 168 | Stores information about what took place. |
|
171 | 169 | """ |
|
172 | 170 | execution_count = None |
|
173 | 171 | error_before_exec = None |
|
174 | 172 | error_in_exec = None |
|
175 | 173 | result = None |
|
176 | 174 | |
|
177 | 175 | @property |
|
178 | 176 | def success(self): |
|
179 | 177 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
180 | 178 | |
|
181 | 179 | def raise_error(self): |
|
182 | 180 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
183 | 181 | if self.error_before_exec is not None: |
|
184 | 182 | raise self.error_before_exec |
|
185 | 183 | if self.error_in_exec is not None: |
|
186 | 184 | raise self.error_in_exec |
|
187 | 185 | |
|
188 | 186 | def __repr__(self): |
|
189 | 187 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\ |
|
190 | 188 | (self.__class__.__qualname__, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result)) |
|
191 | 189 | |
|
192 | 190 | |
|
193 | 191 | class InteractiveShell(SingletonConfigurable): |
|
194 | 192 | """An enhanced, interactive shell for Python.""" |
|
195 | 193 | |
|
196 | 194 | _instance = None |
|
197 | 195 | |
|
198 | 196 | ast_transformers = List([], help= |
|
199 | 197 | """ |
|
200 | 198 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
201 | 199 | to user input before code is run. |
|
202 | 200 | """ |
|
203 | 201 | ).tag(config=True) |
|
204 | 202 | |
|
205 | 203 | autocall = Enum((0,1,2), default_value=0, help= |
|
206 | 204 | """ |
|
207 | 205 | Make IPython automatically call any callable object even if you didn't |
|
208 | 206 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
209 | 207 | automatically. The value can be '0' to disable the feature, '1' for |
|
210 | 208 | 'smart' autocall, where it is not applied if there are no more |
|
211 | 209 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
212 | 210 | objects are automatically called (even if no arguments are present). |
|
213 | 211 | """ |
|
214 | 212 | ).tag(config=True) |
|
215 | 213 | # TODO: remove all autoindent logic and put into frontends. |
|
216 | 214 | # We can't do this yet because even runlines uses the autoindent. |
|
217 | 215 | autoindent = Bool(True, help= |
|
218 | 216 | """ |
|
219 | 217 | Autoindent IPython code entered interactively. |
|
220 | 218 | """ |
|
221 | 219 | ).tag(config=True) |
|
222 | 220 | |
|
223 | 221 | automagic = Bool(True, help= |
|
224 | 222 | """ |
|
225 | 223 | Enable magic commands to be called without the leading %. |
|
226 | 224 | """ |
|
227 | 225 | ).tag(config=True) |
|
228 | 226 | |
|
229 | 227 | banner1 = Unicode(default_banner, |
|
230 | 228 | help="""The part of the banner to be printed before the profile""" |
|
231 | 229 | ).tag(config=True) |
|
232 | 230 | banner2 = Unicode('', |
|
233 | 231 | help="""The part of the banner to be printed after the profile""" |
|
234 | 232 | ).tag(config=True) |
|
235 | 233 | |
|
236 | 234 | cache_size = Integer(1000, help= |
|
237 | 235 | """ |
|
238 | 236 | Set the size of the output cache. The default is 1000, you can |
|
239 | 237 | change it permanently in your config file. Setting it to 0 completely |
|
240 | 238 | disables the caching system, and the minimum value accepted is 20 (if |
|
241 | 239 | you provide a value less than 20, it is reset to 0 and a warning is |
|
242 | 240 | issued). This limit is defined because otherwise you'll spend more |
|
243 | 241 | time re-flushing a too small cache than working |
|
244 | 242 | """ |
|
245 | 243 | ).tag(config=True) |
|
246 | 244 | color_info = Bool(True, help= |
|
247 | 245 | """ |
|
248 | 246 | Use colors for displaying information about objects. Because this |
|
249 | 247 | information is passed through a pager (like 'less'), and some pagers |
|
250 | 248 | get confused with color codes, this capability can be turned off. |
|
251 | 249 | """ |
|
252 | 250 | ).tag(config=True) |
|
253 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
|
254 |
default_value= |
|
|
251 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), | |
|
252 | default_value='Neutral', | |
|
255 | 253 | help="Set the color scheme (NoColor, Linux, or LightBG)." |
|
256 | 254 | ).tag(config=True) |
|
257 | 255 | colors_force = Bool(False, help= |
|
258 | 256 | """ |
|
259 | 257 | Force use of ANSI color codes, regardless of OS and readline |
|
260 | 258 | availability. |
|
261 | 259 | """ |
|
262 | 260 | # FIXME: This is essentially a hack to allow ZMQShell to show colors |
|
263 | 261 | # without readline on Win32. When the ZMQ formatting system is |
|
264 | 262 | # refactored, this should be removed. |
|
265 | 263 | ) |
|
266 | 264 | debug = Bool(False).tag(config=True) |
|
267 | 265 | deep_reload = Bool(False, help= |
|
268 | 266 | """ |
|
269 | 267 | **Deprecated** |
|
270 | 268 | |
|
271 | 269 | Will be removed in IPython 6.0 |
|
272 | 270 | |
|
273 | 271 | Enable deep (recursive) reloading by default. IPython can use the |
|
274 | 272 | deep_reload module which reloads changes in modules recursively (it |
|
275 | 273 | replaces the reload() function, so you don't need to change anything to |
|
276 | 274 | use it). `deep_reload` forces a full reload of modules whose code may |
|
277 | 275 | have changed, which the default reload() function does not. When |
|
278 | 276 | deep_reload is off, IPython will use the normal reload(), but |
|
279 | 277 | deep_reload will still be available as dreload(). |
|
280 | 278 | """ |
|
281 | 279 | ).tag(config=True) |
|
282 | 280 | disable_failing_post_execute = Bool(False, |
|
283 | 281 | help="Don't call post-execute functions that have failed in the past." |
|
284 | 282 | ).tag(config=True) |
|
285 | 283 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
286 | 284 | displayhook_class = Type(DisplayHook) |
|
287 | 285 | display_pub_class = Type(DisplayPublisher) |
|
288 | 286 | |
|
289 | 287 | sphinxify_docstring = Bool(False, help= |
|
290 | 288 | """ |
|
291 | 289 | Enables rich html representation of docstrings. (This requires the |
|
292 | 290 | docrepr module). |
|
293 | 291 | """).tag(config=True) |
|
294 | 292 | |
|
295 | 293 | @observe("sphinxify_docstring") |
|
296 | 294 | def _sphinxify_docstring_changed(self, change): |
|
297 | 295 | if change['new']: |
|
298 | 296 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) |
|
299 | 297 | |
|
300 | 298 | enable_html_pager = Bool(False, help= |
|
301 | 299 | """ |
|
302 | 300 | (Provisional API) enables html representation in mime bundles sent |
|
303 | 301 | to pagers. |
|
304 | 302 | """).tag(config=True) |
|
305 | 303 | |
|
306 | 304 | @observe("enable_html_pager") |
|
307 | 305 | def _enable_html_pager_changed(self, change): |
|
308 | 306 | if change['new']: |
|
309 | 307 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) |
|
310 | 308 | |
|
311 | 309 | data_pub_class = None |
|
312 | 310 | |
|
313 | 311 | exit_now = Bool(False) |
|
314 | 312 | exiter = Instance(ExitAutocall) |
|
315 | 313 | @default('exiter') |
|
316 | 314 | def _exiter_default(self): |
|
317 | 315 | return ExitAutocall(self) |
|
318 | 316 | # Monotonically increasing execution counter |
|
319 | 317 | execution_count = Integer(1) |
|
320 | 318 | filename = Unicode("<ipython console>") |
|
321 | 319 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
322 | 320 | |
|
323 | 321 | # Input splitter, to transform input line by line and detect when a block |
|
324 | 322 | # is ready to be executed. |
|
325 | 323 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
326 | 324 | (), {'line_input_checker': True}) |
|
327 | 325 | |
|
328 | 326 | # This InputSplitter instance is used to transform completed cells before |
|
329 | 327 | # running them. It allows cell magics to contain blank lines. |
|
330 | 328 | input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
331 | 329 | (), {'line_input_checker': False}) |
|
332 | 330 | |
|
333 | 331 | logstart = Bool(False, help= |
|
334 | 332 | """ |
|
335 | 333 | Start logging to the default log file in overwrite mode. |
|
336 | 334 | Use `logappend` to specify a log file to **append** logs to. |
|
337 | 335 | """ |
|
338 | 336 | ).tag(config=True) |
|
339 | 337 | logfile = Unicode('', help= |
|
340 | 338 | """ |
|
341 | 339 | The name of the logfile to use. |
|
342 | 340 | """ |
|
343 | 341 | ).tag(config=True) |
|
344 | 342 | logappend = Unicode('', help= |
|
345 | 343 | """ |
|
346 | 344 | Start logging to the given file in append mode. |
|
347 | 345 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
348 | 346 | """ |
|
349 | 347 | ).tag(config=True) |
|
350 | 348 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
351 | 349 | ).tag(config=True) |
|
352 | 350 | pdb = Bool(False, help= |
|
353 | 351 | """ |
|
354 | 352 | Automatically call the pdb debugger after every exception. |
|
355 | 353 | """ |
|
356 | 354 | ).tag(config=True) |
|
357 | 355 | multiline_history = Bool(sys.platform != 'win32', |
|
358 | 356 | help="Save multi-line entries as one entry in readline history" |
|
359 | 357 | ).tag(config=True) |
|
360 | 358 | display_page = Bool(False, |
|
361 | 359 | help="""If True, anything that would be passed to the pager |
|
362 | 360 | will be displayed as regular output instead.""" |
|
363 | 361 | ).tag(config=True) |
|
364 | 362 | |
|
365 | 363 | # deprecated prompt traits: |
|
366 | 364 | |
|
367 | 365 | prompt_in1 = Unicode('In [\\#]: ', |
|
368 | 366 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
369 | 367 | ).tag(config=True) |
|
370 | 368 | prompt_in2 = Unicode(' .\\D.: ', |
|
371 | 369 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
372 | 370 | ).tag(config=True) |
|
373 | 371 | prompt_out = Unicode('Out[\\#]: ', |
|
374 | 372 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
375 | 373 | ).tag(config=True) |
|
376 | 374 | prompts_pad_left = Bool(True, |
|
377 | 375 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
378 | 376 | ).tag(config=True) |
|
379 | 377 | |
|
380 | 378 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
381 | 379 | def _prompt_trait_changed(self, change): |
|
382 | 380 | name = change['name'] |
|
383 | 381 | warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format( |
|
384 | 382 | name=name) |
|
385 | 383 | ) |
|
386 | 384 | # protect against weird cases where self.config may not exist: |
|
387 | 385 | |
|
388 | 386 | show_rewritten_input = Bool(True, |
|
389 | 387 | help="Show rewritten input, e.g. for autocall." |
|
390 | 388 | ).tag(config=True) |
|
391 | 389 | |
|
392 | 390 | quiet = Bool(False).tag(config=True) |
|
393 | 391 | |
|
394 | 392 | history_length = Integer(10000, |
|
395 | 393 | help='Total length of command history' |
|
396 | 394 | ).tag(config=True) |
|
397 | 395 | |
|
398 | 396 | history_load_length = Integer(1000, help= |
|
399 | 397 | """ |
|
400 | 398 | The number of saved history entries to be loaded |
|
401 | 399 | into the readline buffer at startup. |
|
402 | 400 | """ |
|
403 | 401 | ).tag(config=True) |
|
404 | 402 | |
|
405 | 403 | # The readline stuff will eventually be moved to the terminal subclass |
|
406 | 404 | # but for now, we can't do that as readline is welded in everywhere. |
|
407 | 405 | readline_use = Bool(True).tag(config=True) |
|
408 | 406 | readline_remove_delims = Unicode('-/~').tag(config=True) |
|
409 | 407 | readline_delims = Unicode() # set by init_readline() |
|
410 | 408 | # don't use \M- bindings by default, because they |
|
411 | 409 | # conflict with 8-bit encodings. See gh-58,gh-88 |
|
412 | 410 | readline_parse_and_bind = List([ |
|
413 | 411 | 'tab: complete', |
|
414 | 412 | '"\C-l": clear-screen', |
|
415 | 413 | 'set show-all-if-ambiguous on', |
|
416 | 414 | '"\C-o": tab-insert', |
|
417 | 415 | '"\C-r": reverse-search-history', |
|
418 | 416 | '"\C-s": forward-search-history', |
|
419 | 417 | '"\C-p": history-search-backward', |
|
420 | 418 | '"\C-n": history-search-forward', |
|
421 | 419 | '"\e[A": history-search-backward', |
|
422 | 420 | '"\e[B": history-search-forward', |
|
423 | 421 | '"\C-k": kill-line', |
|
424 | 422 | '"\C-u": unix-line-discard', |
|
425 | 423 | ]).tag(config=True) |
|
426 | 424 | |
|
427 | 425 | _custom_readline_config = False |
|
428 | 426 | |
|
429 | 427 | @observe('readline_parse_and_bind') |
|
430 | 428 | def _readline_parse_and_bind_changed(self, change): |
|
431 | 429 | # notice that readline config is customized |
|
432 | 430 | # indicates that it should have higher priority than inputrc |
|
433 | 431 | self._custom_readline_config = True |
|
434 | 432 | |
|
435 | 433 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'], |
|
436 | 434 | default_value='last_expr', |
|
437 | 435 | help=""" |
|
438 | 436 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
439 | 437 | run interactively (displaying output from expressions).""" |
|
440 | 438 | ).tag(config=True) |
|
441 | 439 | |
|
442 | 440 | # TODO: this part of prompt management should be moved to the frontends. |
|
443 | 441 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
444 | 442 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
445 | 443 | separate_out = SeparateUnicode('').tag(config=True) |
|
446 | 444 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
447 | 445 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
448 | 446 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
449 | 447 | default_value='Context').tag(config=True) |
|
450 | 448 | |
|
451 | 449 | # Subcomponents of InteractiveShell |
|
452 | 450 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
453 | 451 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
454 | 452 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
455 | 453 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
456 | 454 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
457 | 455 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
458 | 456 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
459 | 457 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
460 | 458 | |
|
461 | 459 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
462 | 460 | @property |
|
463 | 461 | def profile(self): |
|
464 | 462 | if self.profile_dir is not None: |
|
465 | 463 | name = os.path.basename(self.profile_dir.location) |
|
466 | 464 | return name.replace('profile_','') |
|
467 | 465 | |
|
468 | 466 | |
|
469 | 467 | # Private interface |
|
470 | 468 | _post_execute = Dict() |
|
471 | 469 | |
|
472 | 470 | # Tracks any GUI loop loaded for pylab |
|
473 | 471 | pylab_gui_select = None |
|
474 | 472 | |
|
475 | 473 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') |
|
476 | 474 | |
|
477 | 475 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
478 | 476 | user_module=None, user_ns=None, |
|
479 | 477 | custom_exceptions=((), None), **kwargs): |
|
480 | 478 | |
|
481 | 479 | # This is where traits with a config_key argument are updated |
|
482 | 480 | # from the values on config. |
|
483 | 481 | super(InteractiveShell, self).__init__(**kwargs) |
|
484 | 482 | if 'PromptManager' in self.config: |
|
485 | 483 | warn('As of IPython 5.0 `PromptManager` config will have no effect' |
|
486 | 484 | ' and has been replaced by TerminalInteractiveShell.prompts_class') |
|
487 | 485 | self.configurables = [self] |
|
488 | 486 | |
|
489 | 487 | # These are relatively independent and stateless |
|
490 | 488 | self.init_ipython_dir(ipython_dir) |
|
491 | 489 | self.init_profile_dir(profile_dir) |
|
492 | 490 | self.init_instance_attrs() |
|
493 | 491 | self.init_environment() |
|
494 | 492 | |
|
495 | 493 | # Check if we're in a virtualenv, and set up sys.path. |
|
496 | 494 | self.init_virtualenv() |
|
497 | 495 | |
|
498 | 496 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
499 | 497 | self.init_create_namespaces(user_module, user_ns) |
|
500 | 498 | # This has to be done after init_create_namespaces because it uses |
|
501 | 499 | # something in self.user_ns, but before init_sys_modules, which |
|
502 | 500 | # is the first thing to modify sys. |
|
503 | 501 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
504 | 502 | # is created, we are saving the overridden ones here. Not sure if this |
|
505 | 503 | # is what we want to do. |
|
506 | 504 | self.save_sys_module_state() |
|
507 | 505 | self.init_sys_modules() |
|
508 | 506 | |
|
509 | 507 | # While we're trying to have each part of the code directly access what |
|
510 | 508 | # it needs without keeping redundant references to objects, we have too |
|
511 | 509 | # much legacy code that expects ip.db to exist. |
|
512 | 510 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
513 | 511 | |
|
514 | 512 | self.init_history() |
|
515 | 513 | self.init_encoding() |
|
516 | 514 | self.init_prefilter() |
|
517 | 515 | |
|
518 | 516 | self.init_syntax_highlighting() |
|
519 | 517 | self.init_hooks() |
|
520 | 518 | self.init_events() |
|
521 | 519 | self.init_pushd_popd_magic() |
|
522 | 520 | # self.init_traceback_handlers use to be here, but we moved it below |
|
523 | 521 | # because it and init_io have to come after init_readline. |
|
524 | 522 | self.init_user_ns() |
|
525 | 523 | self.init_logger() |
|
526 | 524 | self.init_builtins() |
|
527 | 525 | |
|
528 | 526 | # The following was in post_config_initialization |
|
529 | 527 | self.init_inspector() |
|
530 | 528 | # init_readline() must come before init_io(), because init_io uses |
|
531 | 529 | # readline related things. |
|
532 | 530 | self.init_readline() |
|
533 | 531 | # We save this here in case user code replaces raw_input, but it needs |
|
534 | 532 | # to be after init_readline(), because PyPy's readline works by replacing |
|
535 | 533 | # raw_input. |
|
536 | 534 | if py3compat.PY3: |
|
537 | 535 | self.raw_input_original = input |
|
538 | 536 | else: |
|
539 | 537 | self.raw_input_original = raw_input |
|
540 | 538 | # init_completer must come after init_readline, because it needs to |
|
541 | 539 | # know whether readline is present or not system-wide to configure the |
|
542 | 540 | # completers, since the completion machinery can now operate |
|
543 | 541 | # independently of readline (e.g. over the network) |
|
544 | 542 | self.init_completer() |
|
545 | 543 | # TODO: init_io() needs to happen before init_traceback handlers |
|
546 | 544 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
547 | 545 | # This logic in in debugger.Pdb and should eventually be changed. |
|
548 | 546 | self.init_io() |
|
549 | 547 | self.init_traceback_handlers(custom_exceptions) |
|
550 | 548 | self.init_prompts() |
|
551 | 549 | self.init_display_formatter() |
|
552 | 550 | self.init_display_pub() |
|
553 | 551 | self.init_data_pub() |
|
554 | 552 | self.init_displayhook() |
|
555 | 553 | self.init_magics() |
|
556 | 554 | self.init_alias() |
|
557 | 555 | self.init_logstart() |
|
558 | 556 | self.init_pdb() |
|
559 | 557 | self.init_extension_manager() |
|
560 | 558 | self.init_payload() |
|
561 | 559 | self.init_deprecation_warnings() |
|
562 | 560 | self.hooks.late_startup_hook() |
|
563 | 561 | self.events.trigger('shell_initialized', self) |
|
564 | 562 | atexit.register(self.atexit_operations) |
|
565 | 563 | |
|
566 | 564 | def get_ipython(self): |
|
567 | 565 | """Return the currently running IPython instance.""" |
|
568 | 566 | return self |
|
569 | 567 | |
|
570 | 568 | #------------------------------------------------------------------------- |
|
571 | 569 | # Trait changed handlers |
|
572 | 570 | #------------------------------------------------------------------------- |
|
573 | 571 | @observe('ipython_dir') |
|
574 | 572 | def _ipython_dir_changed(self, change): |
|
575 | 573 | ensure_dir_exists(change['new']) |
|
576 | 574 | |
|
577 | 575 | def set_autoindent(self,value=None): |
|
578 | 576 | """Set the autoindent flag. |
|
579 | 577 | |
|
580 | 578 | If called with no arguments, it acts as a toggle.""" |
|
581 | 579 | if value is None: |
|
582 | 580 | self.autoindent = not self.autoindent |
|
583 | 581 | else: |
|
584 | 582 | self.autoindent = value |
|
585 | 583 | |
|
586 | 584 | #------------------------------------------------------------------------- |
|
587 | 585 | # init_* methods called by __init__ |
|
588 | 586 | #------------------------------------------------------------------------- |
|
589 | 587 | |
|
590 | 588 | def init_ipython_dir(self, ipython_dir): |
|
591 | 589 | if ipython_dir is not None: |
|
592 | 590 | self.ipython_dir = ipython_dir |
|
593 | 591 | return |
|
594 | 592 | |
|
595 | 593 | self.ipython_dir = get_ipython_dir() |
|
596 | 594 | |
|
597 | 595 | def init_profile_dir(self, profile_dir): |
|
598 | 596 | if profile_dir is not None: |
|
599 | 597 | self.profile_dir = profile_dir |
|
600 | 598 | return |
|
601 | 599 | self.profile_dir =\ |
|
602 | 600 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
603 | 601 | |
|
604 | 602 | def init_instance_attrs(self): |
|
605 | 603 | self.more = False |
|
606 | 604 | |
|
607 | 605 | # command compiler |
|
608 | 606 | self.compile = CachingCompiler() |
|
609 | 607 | |
|
610 | 608 | # Make an empty namespace, which extension writers can rely on both |
|
611 | 609 | # existing and NEVER being used by ipython itself. This gives them a |
|
612 | 610 | # convenient location for storing additional information and state |
|
613 | 611 | # their extensions may require, without fear of collisions with other |
|
614 | 612 | # ipython names that may develop later. |
|
615 | 613 | self.meta = Struct() |
|
616 | 614 | |
|
617 | 615 | # Temporary files used for various purposes. Deleted at exit. |
|
618 | 616 | self.tempfiles = [] |
|
619 | 617 | self.tempdirs = [] |
|
620 | 618 | |
|
621 | 619 | # Keep track of readline usage (later set by init_readline) |
|
622 | 620 | self.has_readline = False |
|
623 | 621 | |
|
624 | 622 | # keep track of where we started running (mainly for crash post-mortem) |
|
625 | 623 | # This is not being used anywhere currently. |
|
626 | 624 | self.starting_dir = py3compat.getcwd() |
|
627 | 625 | |
|
628 | 626 | # Indentation management |
|
629 | 627 | self.indent_current_nsp = 0 |
|
630 | 628 | |
|
631 | 629 | # Dict to track post-execution functions that have been registered |
|
632 | 630 | self._post_execute = {} |
|
633 | 631 | |
|
634 | 632 | def init_environment(self): |
|
635 | 633 | """Any changes we need to make to the user's environment.""" |
|
636 | 634 | pass |
|
637 | 635 | |
|
638 | 636 | def init_encoding(self): |
|
639 | 637 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
640 | 638 | # under Win32 have it set to None, and we need to have a known valid |
|
641 | 639 | # encoding to use in the raw_input() method |
|
642 | 640 | try: |
|
643 | 641 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
644 | 642 | except AttributeError: |
|
645 | 643 | self.stdin_encoding = 'ascii' |
|
646 | 644 | |
|
647 | 645 | def init_syntax_highlighting(self): |
|
648 | 646 | # Python source parser/formatter for syntax highlighting |
|
649 | 647 | pyformat = PyColorize.Parser().format |
|
650 | 648 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
651 | 649 | |
|
652 | 650 | def init_pushd_popd_magic(self): |
|
653 | 651 | # for pushd/popd management |
|
654 | 652 | self.home_dir = get_home_dir() |
|
655 | 653 | |
|
656 | 654 | self.dir_stack = [] |
|
657 | 655 | |
|
658 | 656 | def init_logger(self): |
|
659 | 657 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
660 | 658 | logmode='rotate') |
|
661 | 659 | |
|
662 | 660 | def init_logstart(self): |
|
663 | 661 | """Initialize logging in case it was requested at the command line. |
|
664 | 662 | """ |
|
665 | 663 | if self.logappend: |
|
666 | 664 | self.magic('logstart %s append' % self.logappend) |
|
667 | 665 | elif self.logfile: |
|
668 | 666 | self.magic('logstart %s' % self.logfile) |
|
669 | 667 | elif self.logstart: |
|
670 | 668 | self.magic('logstart') |
|
671 | 669 | |
|
672 | 670 | def init_deprecation_warnings(self): |
|
673 | 671 | """ |
|
674 | 672 | register default filter for deprecation warning. |
|
675 | 673 | |
|
676 | 674 | This will allow deprecation warning of function used interactively to show |
|
677 | 675 | warning to users, and still hide deprecation warning from libraries import. |
|
678 | 676 | """ |
|
679 | 677 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
680 | 678 | |
|
681 | 679 | def init_builtins(self): |
|
682 | 680 | # A single, static flag that we set to True. Its presence indicates |
|
683 | 681 | # that an IPython shell has been created, and we make no attempts at |
|
684 | 682 | # removing on exit or representing the existence of more than one |
|
685 | 683 | # IPython at a time. |
|
686 | 684 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
687 | 685 | |
|
688 | 686 | self.builtin_trap = BuiltinTrap(shell=self) |
|
689 | 687 | |
|
690 | 688 | def init_inspector(self): |
|
691 | 689 | # Object inspector |
|
692 | 690 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
693 | 691 | PyColorize.ANSICodeColors, |
|
694 | 692 | 'NoColor', |
|
695 | 693 | self.object_info_string_level) |
|
696 | 694 | |
|
697 | 695 | def init_io(self): |
|
698 | 696 | # This will just use sys.stdout and sys.stderr. If you want to |
|
699 | 697 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
700 | 698 | # *before* instantiating this class, because io holds onto |
|
701 | 699 | # references to the underlying streams. |
|
702 | 700 | if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline: |
|
703 | 701 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) |
|
704 | 702 | else: |
|
705 | 703 | io.stdout = io.IOStream(sys.stdout) |
|
706 | 704 | io.stderr = io.IOStream(sys.stderr) |
|
707 | 705 | |
|
708 | 706 | def init_prompts(self): |
|
709 | 707 | # Set system prompts, so that scripts can decide if they are running |
|
710 | 708 | # interactively. |
|
711 | 709 | sys.ps1 = 'In : ' |
|
712 | 710 | sys.ps2 = '...: ' |
|
713 | 711 | sys.ps3 = 'Out: ' |
|
714 | 712 | |
|
715 | 713 | def init_display_formatter(self): |
|
716 | 714 | self.display_formatter = DisplayFormatter(parent=self) |
|
717 | 715 | self.configurables.append(self.display_formatter) |
|
718 | 716 | |
|
719 | 717 | def init_display_pub(self): |
|
720 | 718 | self.display_pub = self.display_pub_class(parent=self) |
|
721 | 719 | self.configurables.append(self.display_pub) |
|
722 | 720 | |
|
723 | 721 | def init_data_pub(self): |
|
724 | 722 | if not self.data_pub_class: |
|
725 | 723 | self.data_pub = None |
|
726 | 724 | return |
|
727 | 725 | self.data_pub = self.data_pub_class(parent=self) |
|
728 | 726 | self.configurables.append(self.data_pub) |
|
729 | 727 | |
|
730 | 728 | def init_displayhook(self): |
|
731 | 729 | # Initialize displayhook, set in/out prompts and printing system |
|
732 | 730 | self.displayhook = self.displayhook_class( |
|
733 | 731 | parent=self, |
|
734 | 732 | shell=self, |
|
735 | 733 | cache_size=self.cache_size, |
|
736 | 734 | ) |
|
737 | 735 | self.configurables.append(self.displayhook) |
|
738 | 736 | # This is a context manager that installs/revmoes the displayhook at |
|
739 | 737 | # the appropriate time. |
|
740 | 738 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
741 | 739 | |
|
742 | 740 | def init_virtualenv(self): |
|
743 | 741 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
744 | 742 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
745 | 743 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
746 | 744 | warning will appear suggesting the user installs IPython in the |
|
747 | 745 | virtualenv, but for many cases, it probably works well enough. |
|
748 | 746 | |
|
749 | 747 | Adapted from code snippets online. |
|
750 | 748 | |
|
751 | 749 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
752 | 750 | """ |
|
753 | 751 | if 'VIRTUAL_ENV' not in os.environ: |
|
754 | 752 | # Not in a virtualenv |
|
755 | 753 | return |
|
756 | 754 | |
|
757 | 755 | # venv detection: |
|
758 | 756 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
759 | 757 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
760 | 758 | # So we just check every item in the symlink tree (generally <= 3) |
|
761 | 759 | p = os.path.normcase(sys.executable) |
|
762 | 760 | paths = [p] |
|
763 | 761 | while os.path.islink(p): |
|
764 | 762 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
765 | 763 | paths.append(p) |
|
766 | 764 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
767 | 765 | if any(p.startswith(p_venv) for p in paths): |
|
768 | 766 | # Running properly in the virtualenv, don't need to do anything |
|
769 | 767 | return |
|
770 | 768 | |
|
771 | 769 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
772 | 770 | "install IPython inside the virtualenv.") |
|
773 | 771 | if sys.platform == "win32": |
|
774 | 772 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
775 | 773 | else: |
|
776 | 774 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
777 | 775 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
778 | 776 | |
|
779 | 777 | import site |
|
780 | 778 | sys.path.insert(0, virtual_env) |
|
781 | 779 | site.addsitedir(virtual_env) |
|
782 | 780 | |
|
783 | 781 | #------------------------------------------------------------------------- |
|
784 | 782 | # Things related to injections into the sys module |
|
785 | 783 | #------------------------------------------------------------------------- |
|
786 | 784 | |
|
787 | 785 | def save_sys_module_state(self): |
|
788 | 786 | """Save the state of hooks in the sys module. |
|
789 | 787 | |
|
790 | 788 | This has to be called after self.user_module is created. |
|
791 | 789 | """ |
|
792 | 790 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
793 | 791 | 'stdout': sys.stdout, |
|
794 | 792 | 'stderr': sys.stderr, |
|
795 | 793 | 'excepthook': sys.excepthook} |
|
796 | 794 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
797 | 795 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
798 | 796 | |
|
799 | 797 | def restore_sys_module_state(self): |
|
800 | 798 | """Restore the state of the sys module.""" |
|
801 | 799 | try: |
|
802 | 800 | for k, v in iteritems(self._orig_sys_module_state): |
|
803 | 801 | setattr(sys, k, v) |
|
804 | 802 | except AttributeError: |
|
805 | 803 | pass |
|
806 | 804 | # Reset what what done in self.init_sys_modules |
|
807 | 805 | if self._orig_sys_modules_main_mod is not None: |
|
808 | 806 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
809 | 807 | |
|
810 | 808 | #------------------------------------------------------------------------- |
|
811 | 809 | # Things related to the banner |
|
812 | 810 | #------------------------------------------------------------------------- |
|
813 | 811 | |
|
814 | 812 | @property |
|
815 | 813 | def banner(self): |
|
816 | 814 | banner = self.banner1 |
|
817 | 815 | if self.profile and self.profile != 'default': |
|
818 | 816 | banner += '\nIPython profile: %s\n' % self.profile |
|
819 | 817 | if self.banner2: |
|
820 | 818 | banner += '\n' + self.banner2 |
|
821 | 819 | return banner |
|
822 | 820 | |
|
823 | 821 | def show_banner(self, banner=None): |
|
824 | 822 | if banner is None: |
|
825 | 823 | banner = self.banner |
|
826 | 824 | sys.stdout.write(banner) |
|
827 | 825 | |
|
828 | 826 | #------------------------------------------------------------------------- |
|
829 | 827 | # Things related to hooks |
|
830 | 828 | #------------------------------------------------------------------------- |
|
831 | 829 | |
|
832 | 830 | def init_hooks(self): |
|
833 | 831 | # hooks holds pointers used for user-side customizations |
|
834 | 832 | self.hooks = Struct() |
|
835 | 833 | |
|
836 | 834 | self.strdispatchers = {} |
|
837 | 835 | |
|
838 | 836 | # Set all default hooks, defined in the IPython.hooks module. |
|
839 | 837 | hooks = IPython.core.hooks |
|
840 | 838 | for hook_name in hooks.__all__: |
|
841 | 839 | # default hooks have priority 100, i.e. low; user hooks should have |
|
842 | 840 | # 0-100 priority |
|
843 | 841 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
844 | 842 | |
|
845 | 843 | if self.display_page: |
|
846 | 844 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
847 | 845 | |
|
848 | 846 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
849 | 847 | _warn_deprecated=True): |
|
850 | 848 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
851 | 849 | |
|
852 | 850 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
853 | 851 | adding your function to one of these hooks, you can modify IPython's |
|
854 | 852 | behavior to call at runtime your own routines.""" |
|
855 | 853 | |
|
856 | 854 | # At some point in the future, this should validate the hook before it |
|
857 | 855 | # accepts it. Probably at least check that the hook takes the number |
|
858 | 856 | # of args it's supposed to. |
|
859 | 857 | |
|
860 | 858 | f = types.MethodType(hook,self) |
|
861 | 859 | |
|
862 | 860 | # check if the hook is for strdispatcher first |
|
863 | 861 | if str_key is not None: |
|
864 | 862 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
865 | 863 | sdp.add_s(str_key, f, priority ) |
|
866 | 864 | self.strdispatchers[name] = sdp |
|
867 | 865 | return |
|
868 | 866 | if re_key is not None: |
|
869 | 867 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
870 | 868 | sdp.add_re(re.compile(re_key), f, priority ) |
|
871 | 869 | self.strdispatchers[name] = sdp |
|
872 | 870 | return |
|
873 | 871 | |
|
874 | 872 | dp = getattr(self.hooks, name, None) |
|
875 | 873 | if name not in IPython.core.hooks.__all__: |
|
876 | 874 | print("Warning! Hook '%s' is not one of %s" % \ |
|
877 | 875 | (name, IPython.core.hooks.__all__ )) |
|
878 | 876 | |
|
879 | 877 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
880 | 878 | alternative = IPython.core.hooks.deprecated[name] |
|
881 | 879 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative)) |
|
882 | 880 | |
|
883 | 881 | if not dp: |
|
884 | 882 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
885 | 883 | |
|
886 | 884 | try: |
|
887 | 885 | dp.add(f,priority) |
|
888 | 886 | except AttributeError: |
|
889 | 887 | # it was not commandchain, plain old func - replace |
|
890 | 888 | dp = f |
|
891 | 889 | |
|
892 | 890 | setattr(self.hooks,name, dp) |
|
893 | 891 | |
|
894 | 892 | #------------------------------------------------------------------------- |
|
895 | 893 | # Things related to events |
|
896 | 894 | #------------------------------------------------------------------------- |
|
897 | 895 | |
|
898 | 896 | def init_events(self): |
|
899 | 897 | self.events = EventManager(self, available_events) |
|
900 | 898 | |
|
901 | 899 | self.events.register("pre_execute", self._clear_warning_registry) |
|
902 | 900 | |
|
903 | 901 | def register_post_execute(self, func): |
|
904 | 902 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
905 | 903 | |
|
906 | 904 | Register a function for calling after code execution. |
|
907 | 905 | """ |
|
908 | 906 | warn("ip.register_post_execute is deprecated, use " |
|
909 | 907 | "ip.events.register('post_run_cell', func) instead.") |
|
910 | 908 | self.events.register('post_run_cell', func) |
|
911 | 909 | |
|
912 | 910 | def _clear_warning_registry(self): |
|
913 | 911 | # clear the warning registry, so that different code blocks with |
|
914 | 912 | # overlapping line number ranges don't cause spurious suppression of |
|
915 | 913 | # warnings (see gh-6611 for details) |
|
916 | 914 | if "__warningregistry__" in self.user_global_ns: |
|
917 | 915 | del self.user_global_ns["__warningregistry__"] |
|
918 | 916 | |
|
919 | 917 | #------------------------------------------------------------------------- |
|
920 | 918 | # Things related to the "main" module |
|
921 | 919 | #------------------------------------------------------------------------- |
|
922 | 920 | |
|
923 | 921 | def new_main_mod(self, filename, modname): |
|
924 | 922 | """Return a new 'main' module object for user code execution. |
|
925 | 923 | |
|
926 | 924 | ``filename`` should be the path of the script which will be run in the |
|
927 | 925 | module. Requests with the same filename will get the same module, with |
|
928 | 926 | its namespace cleared. |
|
929 | 927 | |
|
930 | 928 | ``modname`` should be the module name - normally either '__main__' or |
|
931 | 929 | the basename of the file without the extension. |
|
932 | 930 | |
|
933 | 931 | When scripts are executed via %run, we must keep a reference to their |
|
934 | 932 | __main__ module around so that Python doesn't |
|
935 | 933 | clear it, rendering references to module globals useless. |
|
936 | 934 | |
|
937 | 935 | This method keeps said reference in a private dict, keyed by the |
|
938 | 936 | absolute path of the script. This way, for multiple executions of the |
|
939 | 937 | same script we only keep one copy of the namespace (the last one), |
|
940 | 938 | thus preventing memory leaks from old references while allowing the |
|
941 | 939 | objects from the last execution to be accessible. |
|
942 | 940 | """ |
|
943 | 941 | filename = os.path.abspath(filename) |
|
944 | 942 | try: |
|
945 | 943 | main_mod = self._main_mod_cache[filename] |
|
946 | 944 | except KeyError: |
|
947 | 945 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
948 | 946 | py3compat.cast_bytes_py2(modname), |
|
949 | 947 | doc="Module created for script run in IPython") |
|
950 | 948 | else: |
|
951 | 949 | main_mod.__dict__.clear() |
|
952 | 950 | main_mod.__name__ = modname |
|
953 | 951 | |
|
954 | 952 | main_mod.__file__ = filename |
|
955 | 953 | # It seems pydoc (and perhaps others) needs any module instance to |
|
956 | 954 | # implement a __nonzero__ method |
|
957 | 955 | main_mod.__nonzero__ = lambda : True |
|
958 | 956 | |
|
959 | 957 | return main_mod |
|
960 | 958 | |
|
961 | 959 | def clear_main_mod_cache(self): |
|
962 | 960 | """Clear the cache of main modules. |
|
963 | 961 | |
|
964 | 962 | Mainly for use by utilities like %reset. |
|
965 | 963 | |
|
966 | 964 | Examples |
|
967 | 965 | -------- |
|
968 | 966 | |
|
969 | 967 | In [15]: import IPython |
|
970 | 968 | |
|
971 | 969 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
972 | 970 | |
|
973 | 971 | In [17]: len(_ip._main_mod_cache) > 0 |
|
974 | 972 | Out[17]: True |
|
975 | 973 | |
|
976 | 974 | In [18]: _ip.clear_main_mod_cache() |
|
977 | 975 | |
|
978 | 976 | In [19]: len(_ip._main_mod_cache) == 0 |
|
979 | 977 | Out[19]: True |
|
980 | 978 | """ |
|
981 | 979 | self._main_mod_cache.clear() |
|
982 | 980 | |
|
983 | 981 | #------------------------------------------------------------------------- |
|
984 | 982 | # Things related to debugging |
|
985 | 983 | #------------------------------------------------------------------------- |
|
986 | 984 | |
|
987 | 985 | def init_pdb(self): |
|
988 | 986 | # Set calling of pdb on exceptions |
|
989 | 987 | # self.call_pdb is a property |
|
990 | 988 | self.call_pdb = self.pdb |
|
991 | 989 | |
|
992 | 990 | def _get_call_pdb(self): |
|
993 | 991 | return self._call_pdb |
|
994 | 992 | |
|
995 | 993 | def _set_call_pdb(self,val): |
|
996 | 994 | |
|
997 | 995 | if val not in (0,1,False,True): |
|
998 | 996 | raise ValueError('new call_pdb value must be boolean') |
|
999 | 997 | |
|
1000 | 998 | # store value in instance |
|
1001 | 999 | self._call_pdb = val |
|
1002 | 1000 | |
|
1003 | 1001 | # notify the actual exception handlers |
|
1004 | 1002 | self.InteractiveTB.call_pdb = val |
|
1005 | 1003 | |
|
1006 | 1004 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1007 | 1005 | 'Control auto-activation of pdb at exceptions') |
|
1008 | 1006 | |
|
1009 | 1007 | def debugger(self,force=False): |
|
1010 | 1008 | """Call the pdb debugger. |
|
1011 | 1009 | |
|
1012 | 1010 | Keywords: |
|
1013 | 1011 | |
|
1014 | 1012 | - force(False): by default, this routine checks the instance call_pdb |
|
1015 | 1013 | flag and does not actually invoke the debugger if the flag is false. |
|
1016 | 1014 | The 'force' option forces the debugger to activate even if the flag |
|
1017 | 1015 | is false. |
|
1018 | 1016 | """ |
|
1019 | 1017 | |
|
1020 | 1018 | if not (force or self.call_pdb): |
|
1021 | 1019 | return |
|
1022 | 1020 | |
|
1023 | 1021 | if not hasattr(sys,'last_traceback'): |
|
1024 | 1022 | error('No traceback has been produced, nothing to debug.') |
|
1025 | 1023 | return |
|
1026 | 1024 | |
|
1027 | 1025 | |
|
1028 | 1026 | with self.readline_no_record: |
|
1029 | 1027 | self.InteractiveTB.debugger(force=True) |
|
1030 | 1028 | |
|
1031 | 1029 | #------------------------------------------------------------------------- |
|
1032 | 1030 | # Things related to IPython's various namespaces |
|
1033 | 1031 | #------------------------------------------------------------------------- |
|
1034 | 1032 | default_user_namespaces = True |
|
1035 | 1033 | |
|
1036 | 1034 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
1037 | 1035 | # Create the namespace where the user will operate. user_ns is |
|
1038 | 1036 | # normally the only one used, and it is passed to the exec calls as |
|
1039 | 1037 | # the locals argument. But we do carry a user_global_ns namespace |
|
1040 | 1038 | # given as the exec 'globals' argument, This is useful in embedding |
|
1041 | 1039 | # situations where the ipython shell opens in a context where the |
|
1042 | 1040 | # distinction between locals and globals is meaningful. For |
|
1043 | 1041 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
1044 | 1042 | |
|
1045 | 1043 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
1046 | 1044 | # level as a dict instead of a module. This is a manual fix, but I |
|
1047 | 1045 | # should really track down where the problem is coming from. Alex |
|
1048 | 1046 | # Schmolck reported this problem first. |
|
1049 | 1047 | |
|
1050 | 1048 | # A useful post by Alex Martelli on this topic: |
|
1051 | 1049 | # Re: inconsistent value from __builtins__ |
|
1052 | 1050 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
1053 | 1051 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
1054 | 1052 | # Gruppen: comp.lang.python |
|
1055 | 1053 | |
|
1056 | 1054 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
1057 | 1055 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
1058 | 1056 | # > <type 'dict'> |
|
1059 | 1057 | # > >>> print type(__builtins__) |
|
1060 | 1058 | # > <type 'module'> |
|
1061 | 1059 | # > Is this difference in return value intentional? |
|
1062 | 1060 | |
|
1063 | 1061 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
1064 | 1062 | # or a module, and it's been that way for a long time. Whether it's |
|
1065 | 1063 | # intentional (or sensible), I don't know. In any case, the idea is |
|
1066 | 1064 | # that if you need to access the built-in namespace directly, you |
|
1067 | 1065 | # should start with "import __builtin__" (note, no 's') which will |
|
1068 | 1066 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1069 | 1067 | |
|
1070 | 1068 | # These routines return a properly built module and dict as needed by |
|
1071 | 1069 | # the rest of the code, and can also be used by extension writers to |
|
1072 | 1070 | # generate properly initialized namespaces. |
|
1073 | 1071 | if (user_ns is not None) or (user_module is not None): |
|
1074 | 1072 | self.default_user_namespaces = False |
|
1075 | 1073 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1076 | 1074 | |
|
1077 | 1075 | # A record of hidden variables we have added to the user namespace, so |
|
1078 | 1076 | # we can list later only variables defined in actual interactive use. |
|
1079 | 1077 | self.user_ns_hidden = {} |
|
1080 | 1078 | |
|
1081 | 1079 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1082 | 1080 | # problem: after script execution (via %run), the module where the user |
|
1083 | 1081 | # code ran is deleted. Now that this object is a true module (needed |
|
1084 | 1082 | # so doctest and other tools work correctly), the Python module |
|
1085 | 1083 | # teardown mechanism runs over it, and sets to None every variable |
|
1086 | 1084 | # present in that module. Top-level references to objects from the |
|
1087 | 1085 | # script survive, because the user_ns is updated with them. However, |
|
1088 | 1086 | # calling functions defined in the script that use other things from |
|
1089 | 1087 | # the script will fail, because the function's closure had references |
|
1090 | 1088 | # to the original objects, which are now all None. So we must protect |
|
1091 | 1089 | # these modules from deletion by keeping a cache. |
|
1092 | 1090 | # |
|
1093 | 1091 | # To avoid keeping stale modules around (we only need the one from the |
|
1094 | 1092 | # last run), we use a dict keyed with the full path to the script, so |
|
1095 | 1093 | # only the last version of the module is held in the cache. Note, |
|
1096 | 1094 | # however, that we must cache the module *namespace contents* (their |
|
1097 | 1095 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1098 | 1096 | # (uncached) could be destroyed while still holding references (such as |
|
1099 | 1097 | # those held by GUI objects that tend to be long-lived)> |
|
1100 | 1098 | # |
|
1101 | 1099 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1102 | 1100 | # and clear_main_mod_cache() methods for details on use. |
|
1103 | 1101 | |
|
1104 | 1102 | # This is the cache used for 'main' namespaces |
|
1105 | 1103 | self._main_mod_cache = {} |
|
1106 | 1104 | |
|
1107 | 1105 | # A table holding all the namespaces IPython deals with, so that |
|
1108 | 1106 | # introspection facilities can search easily. |
|
1109 | 1107 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1110 | 1108 | 'user_local':self.user_ns, |
|
1111 | 1109 | 'builtin':builtin_mod.__dict__ |
|
1112 | 1110 | } |
|
1113 | 1111 | |
|
1114 | 1112 | @property |
|
1115 | 1113 | def user_global_ns(self): |
|
1116 | 1114 | return self.user_module.__dict__ |
|
1117 | 1115 | |
|
1118 | 1116 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1119 | 1117 | """Prepare the module and namespace in which user code will be run. |
|
1120 | 1118 | |
|
1121 | 1119 | When IPython is started normally, both parameters are None: a new module |
|
1122 | 1120 | is created automatically, and its __dict__ used as the namespace. |
|
1123 | 1121 | |
|
1124 | 1122 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1125 | 1123 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1126 | 1124 | becomes the global namespace. If both are provided (as they may be |
|
1127 | 1125 | when embedding), user_ns is the local namespace, and user_module |
|
1128 | 1126 | provides the global namespace. |
|
1129 | 1127 | |
|
1130 | 1128 | Parameters |
|
1131 | 1129 | ---------- |
|
1132 | 1130 | user_module : module, optional |
|
1133 | 1131 | The current user module in which IPython is being run. If None, |
|
1134 | 1132 | a clean module will be created. |
|
1135 | 1133 | user_ns : dict, optional |
|
1136 | 1134 | A namespace in which to run interactive commands. |
|
1137 | 1135 | |
|
1138 | 1136 | Returns |
|
1139 | 1137 | ------- |
|
1140 | 1138 | A tuple of user_module and user_ns, each properly initialised. |
|
1141 | 1139 | """ |
|
1142 | 1140 | if user_module is None and user_ns is not None: |
|
1143 | 1141 | user_ns.setdefault("__name__", "__main__") |
|
1144 | 1142 | user_module = DummyMod() |
|
1145 | 1143 | user_module.__dict__ = user_ns |
|
1146 | 1144 | |
|
1147 | 1145 | if user_module is None: |
|
1148 | 1146 | user_module = types.ModuleType("__main__", |
|
1149 | 1147 | doc="Automatically created module for IPython interactive environment") |
|
1150 | 1148 | |
|
1151 | 1149 | # We must ensure that __builtin__ (without the final 's') is always |
|
1152 | 1150 | # available and pointing to the __builtin__ *module*. For more details: |
|
1153 | 1151 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1154 | 1152 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1155 | 1153 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1156 | 1154 | |
|
1157 | 1155 | if user_ns is None: |
|
1158 | 1156 | user_ns = user_module.__dict__ |
|
1159 | 1157 | |
|
1160 | 1158 | return user_module, user_ns |
|
1161 | 1159 | |
|
1162 | 1160 | def init_sys_modules(self): |
|
1163 | 1161 | # We need to insert into sys.modules something that looks like a |
|
1164 | 1162 | # module but which accesses the IPython namespace, for shelve and |
|
1165 | 1163 | # pickle to work interactively. Normally they rely on getting |
|
1166 | 1164 | # everything out of __main__, but for embedding purposes each IPython |
|
1167 | 1165 | # instance has its own private namespace, so we can't go shoving |
|
1168 | 1166 | # everything into __main__. |
|
1169 | 1167 | |
|
1170 | 1168 | # note, however, that we should only do this for non-embedded |
|
1171 | 1169 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1172 | 1170 | # namespace. Embedded instances, on the other hand, should not do |
|
1173 | 1171 | # this because they need to manage the user local/global namespaces |
|
1174 | 1172 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1175 | 1173 | # shouldn't overtake the execution environment of the script they're |
|
1176 | 1174 | # embedded in). |
|
1177 | 1175 | |
|
1178 | 1176 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1179 | 1177 | main_name = self.user_module.__name__ |
|
1180 | 1178 | sys.modules[main_name] = self.user_module |
|
1181 | 1179 | |
|
1182 | 1180 | def init_user_ns(self): |
|
1183 | 1181 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1184 | 1182 | |
|
1185 | 1183 | Certain history lists are also initialized here, as they effectively |
|
1186 | 1184 | act as user namespaces. |
|
1187 | 1185 | |
|
1188 | 1186 | Notes |
|
1189 | 1187 | ----- |
|
1190 | 1188 | All data structures here are only filled in, they are NOT reset by this |
|
1191 | 1189 | method. If they were not empty before, data will simply be added to |
|
1192 | 1190 | therm. |
|
1193 | 1191 | """ |
|
1194 | 1192 | # This function works in two parts: first we put a few things in |
|
1195 | 1193 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1196 | 1194 | # initial variables aren't shown by %who. After the sync, we add the |
|
1197 | 1195 | # rest of what we *do* want the user to see with %who even on a new |
|
1198 | 1196 | # session (probably nothing, so they really only see their own stuff) |
|
1199 | 1197 | |
|
1200 | 1198 | # The user dict must *always* have a __builtin__ reference to the |
|
1201 | 1199 | # Python standard __builtin__ namespace, which must be imported. |
|
1202 | 1200 | # This is so that certain operations in prompt evaluation can be |
|
1203 | 1201 | # reliably executed with builtins. Note that we can NOT use |
|
1204 | 1202 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1205 | 1203 | # module, and can even mutate at runtime, depending on the context |
|
1206 | 1204 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1207 | 1205 | # always a module object, though it must be explicitly imported. |
|
1208 | 1206 | |
|
1209 | 1207 | # For more details: |
|
1210 | 1208 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1211 | 1209 | ns = dict() |
|
1212 | 1210 | |
|
1213 | 1211 | # make global variables for user access to the histories |
|
1214 | 1212 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1215 | 1213 | ns['_oh'] = self.history_manager.output_hist |
|
1216 | 1214 | ns['_dh'] = self.history_manager.dir_hist |
|
1217 | 1215 | |
|
1218 | 1216 | ns['_sh'] = shadowns |
|
1219 | 1217 | |
|
1220 | 1218 | # user aliases to input and output histories. These shouldn't show up |
|
1221 | 1219 | # in %who, as they can have very large reprs. |
|
1222 | 1220 | ns['In'] = self.history_manager.input_hist_parsed |
|
1223 | 1221 | ns['Out'] = self.history_manager.output_hist |
|
1224 | 1222 | |
|
1225 | 1223 | # Store myself as the public api!!! |
|
1226 | 1224 | ns['get_ipython'] = self.get_ipython |
|
1227 | 1225 | |
|
1228 | 1226 | ns['exit'] = self.exiter |
|
1229 | 1227 | ns['quit'] = self.exiter |
|
1230 | 1228 | |
|
1231 | 1229 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1232 | 1230 | # by %who |
|
1233 | 1231 | self.user_ns_hidden.update(ns) |
|
1234 | 1232 | |
|
1235 | 1233 | # Anything put into ns now would show up in %who. Think twice before |
|
1236 | 1234 | # putting anything here, as we really want %who to show the user their |
|
1237 | 1235 | # stuff, not our variables. |
|
1238 | 1236 | |
|
1239 | 1237 | # Finally, update the real user's namespace |
|
1240 | 1238 | self.user_ns.update(ns) |
|
1241 | 1239 | |
|
1242 | 1240 | @property |
|
1243 | 1241 | def all_ns_refs(self): |
|
1244 | 1242 | """Get a list of references to all the namespace dictionaries in which |
|
1245 | 1243 | IPython might store a user-created object. |
|
1246 | 1244 | |
|
1247 | 1245 | Note that this does not include the displayhook, which also caches |
|
1248 | 1246 | objects from the output.""" |
|
1249 | 1247 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1250 | 1248 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1251 | 1249 | |
|
1252 | 1250 | def reset(self, new_session=True): |
|
1253 | 1251 | """Clear all internal namespaces, and attempt to release references to |
|
1254 | 1252 | user objects. |
|
1255 | 1253 | |
|
1256 | 1254 | If new_session is True, a new history session will be opened. |
|
1257 | 1255 | """ |
|
1258 | 1256 | # Clear histories |
|
1259 | 1257 | self.history_manager.reset(new_session) |
|
1260 | 1258 | # Reset counter used to index all histories |
|
1261 | 1259 | if new_session: |
|
1262 | 1260 | self.execution_count = 1 |
|
1263 | 1261 | |
|
1264 | 1262 | # Flush cached output items |
|
1265 | 1263 | if self.displayhook.do_full_cache: |
|
1266 | 1264 | self.displayhook.flush() |
|
1267 | 1265 | |
|
1268 | 1266 | # The main execution namespaces must be cleared very carefully, |
|
1269 | 1267 | # skipping the deletion of the builtin-related keys, because doing so |
|
1270 | 1268 | # would cause errors in many object's __del__ methods. |
|
1271 | 1269 | if self.user_ns is not self.user_global_ns: |
|
1272 | 1270 | self.user_ns.clear() |
|
1273 | 1271 | ns = self.user_global_ns |
|
1274 | 1272 | drop_keys = set(ns.keys()) |
|
1275 | 1273 | drop_keys.discard('__builtin__') |
|
1276 | 1274 | drop_keys.discard('__builtins__') |
|
1277 | 1275 | drop_keys.discard('__name__') |
|
1278 | 1276 | for k in drop_keys: |
|
1279 | 1277 | del ns[k] |
|
1280 | 1278 | |
|
1281 | 1279 | self.user_ns_hidden.clear() |
|
1282 | 1280 | |
|
1283 | 1281 | # Restore the user namespaces to minimal usability |
|
1284 | 1282 | self.init_user_ns() |
|
1285 | 1283 | |
|
1286 | 1284 | # Restore the default and user aliases |
|
1287 | 1285 | self.alias_manager.clear_aliases() |
|
1288 | 1286 | self.alias_manager.init_aliases() |
|
1289 | 1287 | |
|
1290 | 1288 | # Flush the private list of module references kept for script |
|
1291 | 1289 | # execution protection |
|
1292 | 1290 | self.clear_main_mod_cache() |
|
1293 | 1291 | |
|
1294 | 1292 | def del_var(self, varname, by_name=False): |
|
1295 | 1293 | """Delete a variable from the various namespaces, so that, as |
|
1296 | 1294 | far as possible, we're not keeping any hidden references to it. |
|
1297 | 1295 | |
|
1298 | 1296 | Parameters |
|
1299 | 1297 | ---------- |
|
1300 | 1298 | varname : str |
|
1301 | 1299 | The name of the variable to delete. |
|
1302 | 1300 | by_name : bool |
|
1303 | 1301 | If True, delete variables with the given name in each |
|
1304 | 1302 | namespace. If False (default), find the variable in the user |
|
1305 | 1303 | namespace, and delete references to it. |
|
1306 | 1304 | """ |
|
1307 | 1305 | if varname in ('__builtin__', '__builtins__'): |
|
1308 | 1306 | raise ValueError("Refusing to delete %s" % varname) |
|
1309 | 1307 | |
|
1310 | 1308 | ns_refs = self.all_ns_refs |
|
1311 | 1309 | |
|
1312 | 1310 | if by_name: # Delete by name |
|
1313 | 1311 | for ns in ns_refs: |
|
1314 | 1312 | try: |
|
1315 | 1313 | del ns[varname] |
|
1316 | 1314 | except KeyError: |
|
1317 | 1315 | pass |
|
1318 | 1316 | else: # Delete by object |
|
1319 | 1317 | try: |
|
1320 | 1318 | obj = self.user_ns[varname] |
|
1321 | 1319 | except KeyError: |
|
1322 | 1320 | raise NameError("name '%s' is not defined" % varname) |
|
1323 | 1321 | # Also check in output history |
|
1324 | 1322 | ns_refs.append(self.history_manager.output_hist) |
|
1325 | 1323 | for ns in ns_refs: |
|
1326 | 1324 | to_delete = [n for n, o in iteritems(ns) if o is obj] |
|
1327 | 1325 | for name in to_delete: |
|
1328 | 1326 | del ns[name] |
|
1329 | 1327 | |
|
1330 | 1328 | # displayhook keeps extra references, but not in a dictionary |
|
1331 | 1329 | for name in ('_', '__', '___'): |
|
1332 | 1330 | if getattr(self.displayhook, name) is obj: |
|
1333 | 1331 | setattr(self.displayhook, name, None) |
|
1334 | 1332 | |
|
1335 | 1333 | def reset_selective(self, regex=None): |
|
1336 | 1334 | """Clear selective variables from internal namespaces based on a |
|
1337 | 1335 | specified regular expression. |
|
1338 | 1336 | |
|
1339 | 1337 | Parameters |
|
1340 | 1338 | ---------- |
|
1341 | 1339 | regex : string or compiled pattern, optional |
|
1342 | 1340 | A regular expression pattern that will be used in searching |
|
1343 | 1341 | variable names in the users namespaces. |
|
1344 | 1342 | """ |
|
1345 | 1343 | if regex is not None: |
|
1346 | 1344 | try: |
|
1347 | 1345 | m = re.compile(regex) |
|
1348 | 1346 | except TypeError: |
|
1349 | 1347 | raise TypeError('regex must be a string or compiled pattern') |
|
1350 | 1348 | # Search for keys in each namespace that match the given regex |
|
1351 | 1349 | # If a match is found, delete the key/value pair. |
|
1352 | 1350 | for ns in self.all_ns_refs: |
|
1353 | 1351 | for var in ns: |
|
1354 | 1352 | if m.search(var): |
|
1355 | 1353 | del ns[var] |
|
1356 | 1354 | |
|
1357 | 1355 | def push(self, variables, interactive=True): |
|
1358 | 1356 | """Inject a group of variables into the IPython user namespace. |
|
1359 | 1357 | |
|
1360 | 1358 | Parameters |
|
1361 | 1359 | ---------- |
|
1362 | 1360 | variables : dict, str or list/tuple of str |
|
1363 | 1361 | The variables to inject into the user's namespace. If a dict, a |
|
1364 | 1362 | simple update is done. If a str, the string is assumed to have |
|
1365 | 1363 | variable names separated by spaces. A list/tuple of str can also |
|
1366 | 1364 | be used to give the variable names. If just the variable names are |
|
1367 | 1365 | give (list/tuple/str) then the variable values looked up in the |
|
1368 | 1366 | callers frame. |
|
1369 | 1367 | interactive : bool |
|
1370 | 1368 | If True (default), the variables will be listed with the ``who`` |
|
1371 | 1369 | magic. |
|
1372 | 1370 | """ |
|
1373 | 1371 | vdict = None |
|
1374 | 1372 | |
|
1375 | 1373 | # We need a dict of name/value pairs to do namespace updates. |
|
1376 | 1374 | if isinstance(variables, dict): |
|
1377 | 1375 | vdict = variables |
|
1378 | 1376 | elif isinstance(variables, string_types+(list, tuple)): |
|
1379 | 1377 | if isinstance(variables, string_types): |
|
1380 | 1378 | vlist = variables.split() |
|
1381 | 1379 | else: |
|
1382 | 1380 | vlist = variables |
|
1383 | 1381 | vdict = {} |
|
1384 | 1382 | cf = sys._getframe(1) |
|
1385 | 1383 | for name in vlist: |
|
1386 | 1384 | try: |
|
1387 | 1385 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1388 | 1386 | except: |
|
1389 | 1387 | print('Could not get variable %s from %s' % |
|
1390 | 1388 | (name,cf.f_code.co_name)) |
|
1391 | 1389 | else: |
|
1392 | 1390 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1393 | 1391 | |
|
1394 | 1392 | # Propagate variables to user namespace |
|
1395 | 1393 | self.user_ns.update(vdict) |
|
1396 | 1394 | |
|
1397 | 1395 | # And configure interactive visibility |
|
1398 | 1396 | user_ns_hidden = self.user_ns_hidden |
|
1399 | 1397 | if interactive: |
|
1400 | 1398 | for name in vdict: |
|
1401 | 1399 | user_ns_hidden.pop(name, None) |
|
1402 | 1400 | else: |
|
1403 | 1401 | user_ns_hidden.update(vdict) |
|
1404 | 1402 | |
|
1405 | 1403 | def drop_by_id(self, variables): |
|
1406 | 1404 | """Remove a dict of variables from the user namespace, if they are the |
|
1407 | 1405 | same as the values in the dictionary. |
|
1408 | 1406 | |
|
1409 | 1407 | This is intended for use by extensions: variables that they've added can |
|
1410 | 1408 | be taken back out if they are unloaded, without removing any that the |
|
1411 | 1409 | user has overwritten. |
|
1412 | 1410 | |
|
1413 | 1411 | Parameters |
|
1414 | 1412 | ---------- |
|
1415 | 1413 | variables : dict |
|
1416 | 1414 | A dictionary mapping object names (as strings) to the objects. |
|
1417 | 1415 | """ |
|
1418 | 1416 | for name, obj in iteritems(variables): |
|
1419 | 1417 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1420 | 1418 | del self.user_ns[name] |
|
1421 | 1419 | self.user_ns_hidden.pop(name, None) |
|
1422 | 1420 | |
|
1423 | 1421 | #------------------------------------------------------------------------- |
|
1424 | 1422 | # Things related to object introspection |
|
1425 | 1423 | #------------------------------------------------------------------------- |
|
1426 | 1424 | |
|
1427 | 1425 | def _ofind(self, oname, namespaces=None): |
|
1428 | 1426 | """Find an object in the available namespaces. |
|
1429 | 1427 | |
|
1430 | 1428 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1431 | 1429 | |
|
1432 | 1430 | Has special code to detect magic functions. |
|
1433 | 1431 | """ |
|
1434 | 1432 | oname = oname.strip() |
|
1435 | 1433 | #print '1- oname: <%r>' % oname # dbg |
|
1436 | 1434 | if not oname.startswith(ESC_MAGIC) and \ |
|
1437 | 1435 | not oname.startswith(ESC_MAGIC2) and \ |
|
1438 | 1436 | not py3compat.isidentifier(oname, dotted=True): |
|
1439 | 1437 | return dict(found=False) |
|
1440 | 1438 | |
|
1441 | 1439 | if namespaces is None: |
|
1442 | 1440 | # Namespaces to search in: |
|
1443 | 1441 | # Put them in a list. The order is important so that we |
|
1444 | 1442 | # find things in the same order that Python finds them. |
|
1445 | 1443 | namespaces = [ ('Interactive', self.user_ns), |
|
1446 | 1444 | ('Interactive (global)', self.user_global_ns), |
|
1447 | 1445 | ('Python builtin', builtin_mod.__dict__), |
|
1448 | 1446 | ] |
|
1449 | 1447 | |
|
1450 | 1448 | # initialize results to 'null' |
|
1451 | 1449 | found = False; obj = None; ospace = None; |
|
1452 | 1450 | ismagic = False; isalias = False; parent = None |
|
1453 | 1451 | |
|
1454 | 1452 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1455 | 1453 | # function but should only be treated as one if print_function was |
|
1456 | 1454 | # loaded with a future import. In this case, just bail. |
|
1457 | 1455 | if (oname == 'print' and not py3compat.PY3 and not \ |
|
1458 | 1456 | (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1459 | 1457 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1460 | 1458 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1461 | 1459 | |
|
1462 | 1460 | # Look for the given name by splitting it in parts. If the head is |
|
1463 | 1461 | # found, then we look for all the remaining parts as members, and only |
|
1464 | 1462 | # declare success if we can find them all. |
|
1465 | 1463 | oname_parts = oname.split('.') |
|
1466 | 1464 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1467 | 1465 | for nsname,ns in namespaces: |
|
1468 | 1466 | try: |
|
1469 | 1467 | obj = ns[oname_head] |
|
1470 | 1468 | except KeyError: |
|
1471 | 1469 | continue |
|
1472 | 1470 | else: |
|
1473 | 1471 | #print 'oname_rest:', oname_rest # dbg |
|
1474 | 1472 | for idx, part in enumerate(oname_rest): |
|
1475 | 1473 | try: |
|
1476 | 1474 | parent = obj |
|
1477 | 1475 | # The last part is looked up in a special way to avoid |
|
1478 | 1476 | # descriptor invocation as it may raise or have side |
|
1479 | 1477 | # effects. |
|
1480 | 1478 | if idx == len(oname_rest) - 1: |
|
1481 | 1479 | obj = self._getattr_property(obj, part) |
|
1482 | 1480 | else: |
|
1483 | 1481 | obj = getattr(obj, part) |
|
1484 | 1482 | except: |
|
1485 | 1483 | # Blanket except b/c some badly implemented objects |
|
1486 | 1484 | # allow __getattr__ to raise exceptions other than |
|
1487 | 1485 | # AttributeError, which then crashes IPython. |
|
1488 | 1486 | break |
|
1489 | 1487 | else: |
|
1490 | 1488 | # If we finish the for loop (no break), we got all members |
|
1491 | 1489 | found = True |
|
1492 | 1490 | ospace = nsname |
|
1493 | 1491 | break # namespace loop |
|
1494 | 1492 | |
|
1495 | 1493 | # Try to see if it's magic |
|
1496 | 1494 | if not found: |
|
1497 | 1495 | obj = None |
|
1498 | 1496 | if oname.startswith(ESC_MAGIC2): |
|
1499 | 1497 | oname = oname.lstrip(ESC_MAGIC2) |
|
1500 | 1498 | obj = self.find_cell_magic(oname) |
|
1501 | 1499 | elif oname.startswith(ESC_MAGIC): |
|
1502 | 1500 | oname = oname.lstrip(ESC_MAGIC) |
|
1503 | 1501 | obj = self.find_line_magic(oname) |
|
1504 | 1502 | else: |
|
1505 | 1503 | # search without prefix, so run? will find %run? |
|
1506 | 1504 | obj = self.find_line_magic(oname) |
|
1507 | 1505 | if obj is None: |
|
1508 | 1506 | obj = self.find_cell_magic(oname) |
|
1509 | 1507 | if obj is not None: |
|
1510 | 1508 | found = True |
|
1511 | 1509 | ospace = 'IPython internal' |
|
1512 | 1510 | ismagic = True |
|
1513 | 1511 | isalias = isinstance(obj, Alias) |
|
1514 | 1512 | |
|
1515 | 1513 | # Last try: special-case some literals like '', [], {}, etc: |
|
1516 | 1514 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1517 | 1515 | obj = eval(oname_head) |
|
1518 | 1516 | found = True |
|
1519 | 1517 | ospace = 'Interactive' |
|
1520 | 1518 | |
|
1521 | 1519 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1522 | 1520 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1523 | 1521 | |
|
1524 | 1522 | @staticmethod |
|
1525 | 1523 | def _getattr_property(obj, attrname): |
|
1526 | 1524 | """Property-aware getattr to use in object finding. |
|
1527 | 1525 | |
|
1528 | 1526 | If attrname represents a property, return it unevaluated (in case it has |
|
1529 | 1527 | side effects or raises an error. |
|
1530 | 1528 | |
|
1531 | 1529 | """ |
|
1532 | 1530 | if not isinstance(obj, type): |
|
1533 | 1531 | try: |
|
1534 | 1532 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1535 | 1533 | # `obj`, but does so for property: |
|
1536 | 1534 | # |
|
1537 | 1535 | # property.__get__(self, None, cls) -> self |
|
1538 | 1536 | # |
|
1539 | 1537 | # The universal alternative is to traverse the mro manually |
|
1540 | 1538 | # searching for attrname in class dicts. |
|
1541 | 1539 | attr = getattr(type(obj), attrname) |
|
1542 | 1540 | except AttributeError: |
|
1543 | 1541 | pass |
|
1544 | 1542 | else: |
|
1545 | 1543 | # This relies on the fact that data descriptors (with both |
|
1546 | 1544 | # __get__ & __set__ magic methods) take precedence over |
|
1547 | 1545 | # instance-level attributes: |
|
1548 | 1546 | # |
|
1549 | 1547 | # class A(object): |
|
1550 | 1548 | # @property |
|
1551 | 1549 | # def foobar(self): return 123 |
|
1552 | 1550 | # a = A() |
|
1553 | 1551 | # a.__dict__['foobar'] = 345 |
|
1554 | 1552 | # a.foobar # == 123 |
|
1555 | 1553 | # |
|
1556 | 1554 | # So, a property may be returned right away. |
|
1557 | 1555 | if isinstance(attr, property): |
|
1558 | 1556 | return attr |
|
1559 | 1557 | |
|
1560 | 1558 | # Nothing helped, fall back. |
|
1561 | 1559 | return getattr(obj, attrname) |
|
1562 | 1560 | |
|
1563 | 1561 | def _object_find(self, oname, namespaces=None): |
|
1564 | 1562 | """Find an object and return a struct with info about it.""" |
|
1565 | 1563 | return Struct(self._ofind(oname, namespaces)) |
|
1566 | 1564 | |
|
1567 | 1565 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1568 | 1566 | """Generic interface to the inspector system. |
|
1569 | 1567 | |
|
1570 | 1568 | This function is meant to be called by pdef, pdoc & friends. |
|
1571 | 1569 | """ |
|
1572 | 1570 | info = self._object_find(oname, namespaces) |
|
1573 | 1571 | docformat = sphinxify if self.sphinxify_docstring else None |
|
1574 | 1572 | if info.found: |
|
1575 | 1573 | pmethod = getattr(self.inspector, meth) |
|
1576 | 1574 | # TODO: only apply format_screen to the plain/text repr of the mime |
|
1577 | 1575 | # bundle. |
|
1578 | 1576 | formatter = format_screen if info.ismagic else docformat |
|
1579 | 1577 | if meth == 'pdoc': |
|
1580 | 1578 | pmethod(info.obj, oname, formatter) |
|
1581 | 1579 | elif meth == 'pinfo': |
|
1582 | 1580 | pmethod(info.obj, oname, formatter, info, |
|
1583 | 1581 | enable_html_pager=self.enable_html_pager, **kw) |
|
1584 | 1582 | else: |
|
1585 | 1583 | pmethod(info.obj, oname) |
|
1586 | 1584 | else: |
|
1587 | 1585 | print('Object `%s` not found.' % oname) |
|
1588 | 1586 | return 'not found' # so callers can take other action |
|
1589 | 1587 | |
|
1590 | 1588 | def object_inspect(self, oname, detail_level=0): |
|
1591 | 1589 | """Get object info about oname""" |
|
1592 | 1590 | with self.builtin_trap: |
|
1593 | 1591 | info = self._object_find(oname) |
|
1594 | 1592 | if info.found: |
|
1595 | 1593 | return self.inspector.info(info.obj, oname, info=info, |
|
1596 | 1594 | detail_level=detail_level |
|
1597 | 1595 | ) |
|
1598 | 1596 | else: |
|
1599 | 1597 | return oinspect.object_info(name=oname, found=False) |
|
1600 | 1598 | |
|
1601 | 1599 | def object_inspect_text(self, oname, detail_level=0): |
|
1602 | 1600 | """Get object info as formatted text""" |
|
1603 | 1601 | return self.object_inspect_mime(oname, detail_level)['text/plain'] |
|
1604 | 1602 | |
|
1605 | 1603 | def object_inspect_mime(self, oname, detail_level=0): |
|
1606 | 1604 | """Get object info as a mimebundle of formatted representations. |
|
1607 | 1605 | |
|
1608 | 1606 | A mimebundle is a dictionary, keyed by mime-type. |
|
1609 | 1607 | It must always have the key `'text/plain'`. |
|
1610 | 1608 | """ |
|
1611 | 1609 | with self.builtin_trap: |
|
1612 | 1610 | info = self._object_find(oname) |
|
1613 | 1611 | if info.found: |
|
1614 | 1612 | return self.inspector._get_info(info.obj, oname, info=info, |
|
1615 | 1613 | detail_level=detail_level |
|
1616 | 1614 | ) |
|
1617 | 1615 | else: |
|
1618 | 1616 | raise KeyError(oname) |
|
1619 | 1617 | |
|
1620 | 1618 | #------------------------------------------------------------------------- |
|
1621 | 1619 | # Things related to history management |
|
1622 | 1620 | #------------------------------------------------------------------------- |
|
1623 | 1621 | |
|
1624 | 1622 | def init_history(self): |
|
1625 | 1623 | """Sets up the command history, and starts regular autosaves.""" |
|
1626 | 1624 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1627 | 1625 | self.configurables.append(self.history_manager) |
|
1628 | 1626 | |
|
1629 | 1627 | #------------------------------------------------------------------------- |
|
1630 | 1628 | # Things related to exception handling and tracebacks (not debugging) |
|
1631 | 1629 | #------------------------------------------------------------------------- |
|
1632 | 1630 | |
|
1633 | 1631 | debugger_cls = Pdb |
|
1634 | 1632 | |
|
1635 | 1633 | def init_traceback_handlers(self, custom_exceptions): |
|
1636 | 1634 | # Syntax error handler. |
|
1637 | 1635 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1638 | 1636 | |
|
1639 | 1637 | # The interactive one is initialized with an offset, meaning we always |
|
1640 | 1638 | # want to remove the topmost item in the traceback, which is our own |
|
1641 | 1639 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1642 | 1640 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1643 | 1641 | color_scheme='NoColor', |
|
1644 | 1642 | tb_offset = 1, |
|
1645 | 1643 | check_cache=check_linecache_ipython, |
|
1646 | 1644 | debugger_cls=self.debugger_cls) |
|
1647 | 1645 | |
|
1648 | 1646 | # The instance will store a pointer to the system-wide exception hook, |
|
1649 | 1647 | # so that runtime code (such as magics) can access it. This is because |
|
1650 | 1648 | # during the read-eval loop, it may get temporarily overwritten. |
|
1651 | 1649 | self.sys_excepthook = sys.excepthook |
|
1652 | 1650 | |
|
1653 | 1651 | # and add any custom exception handlers the user may have specified |
|
1654 | 1652 | self.set_custom_exc(*custom_exceptions) |
|
1655 | 1653 | |
|
1656 | 1654 | # Set the exception mode |
|
1657 | 1655 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1658 | 1656 | |
|
1659 | 1657 | def set_custom_exc(self, exc_tuple, handler): |
|
1660 | 1658 | """set_custom_exc(exc_tuple, handler) |
|
1661 | 1659 | |
|
1662 | 1660 | Set a custom exception handler, which will be called if any of the |
|
1663 | 1661 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1664 | 1662 | run_code() method). |
|
1665 | 1663 | |
|
1666 | 1664 | Parameters |
|
1667 | 1665 | ---------- |
|
1668 | 1666 | |
|
1669 | 1667 | exc_tuple : tuple of exception classes |
|
1670 | 1668 | A *tuple* of exception classes, for which to call the defined |
|
1671 | 1669 | handler. It is very important that you use a tuple, and NOT A |
|
1672 | 1670 | LIST here, because of the way Python's except statement works. If |
|
1673 | 1671 | you only want to trap a single exception, use a singleton tuple:: |
|
1674 | 1672 | |
|
1675 | 1673 | exc_tuple == (MyCustomException,) |
|
1676 | 1674 | |
|
1677 | 1675 | handler : callable |
|
1678 | 1676 | handler must have the following signature:: |
|
1679 | 1677 | |
|
1680 | 1678 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1681 | 1679 | ... |
|
1682 | 1680 | return structured_traceback |
|
1683 | 1681 | |
|
1684 | 1682 | Your handler must return a structured traceback (a list of strings), |
|
1685 | 1683 | or None. |
|
1686 | 1684 | |
|
1687 | 1685 | This will be made into an instance method (via types.MethodType) |
|
1688 | 1686 | of IPython itself, and it will be called if any of the exceptions |
|
1689 | 1687 | listed in the exc_tuple are caught. If the handler is None, an |
|
1690 | 1688 | internal basic one is used, which just prints basic info. |
|
1691 | 1689 | |
|
1692 | 1690 | To protect IPython from crashes, if your handler ever raises an |
|
1693 | 1691 | exception or returns an invalid result, it will be immediately |
|
1694 | 1692 | disabled. |
|
1695 | 1693 | |
|
1696 | 1694 | WARNING: by putting in your own exception handler into IPython's main |
|
1697 | 1695 | execution loop, you run a very good chance of nasty crashes. This |
|
1698 | 1696 | facility should only be used if you really know what you are doing.""" |
|
1699 | 1697 | |
|
1700 | 1698 | assert type(exc_tuple)==type(()) , \ |
|
1701 | 1699 | "The custom exceptions must be given AS A TUPLE." |
|
1702 | 1700 | |
|
1703 | 1701 | def dummy_handler(self, etype, value, tb, tb_offset=None): |
|
1704 | 1702 | print('*** Simple custom exception handler ***') |
|
1705 | 1703 | print('Exception type :',etype) |
|
1706 | 1704 | print('Exception value:',value) |
|
1707 | 1705 | print('Traceback :',tb) |
|
1708 | 1706 | #print 'Source code :','\n'.join(self.buffer) |
|
1709 | 1707 | |
|
1710 | 1708 | def validate_stb(stb): |
|
1711 | 1709 | """validate structured traceback return type |
|
1712 | 1710 | |
|
1713 | 1711 | return type of CustomTB *should* be a list of strings, but allow |
|
1714 | 1712 | single strings or None, which are harmless. |
|
1715 | 1713 | |
|
1716 | 1714 | This function will *always* return a list of strings, |
|
1717 | 1715 | and will raise a TypeError if stb is inappropriate. |
|
1718 | 1716 | """ |
|
1719 | 1717 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1720 | 1718 | if stb is None: |
|
1721 | 1719 | return [] |
|
1722 | 1720 | elif isinstance(stb, string_types): |
|
1723 | 1721 | return [stb] |
|
1724 | 1722 | elif not isinstance(stb, list): |
|
1725 | 1723 | raise TypeError(msg) |
|
1726 | 1724 | # it's a list |
|
1727 | 1725 | for line in stb: |
|
1728 | 1726 | # check every element |
|
1729 | 1727 | if not isinstance(line, string_types): |
|
1730 | 1728 | raise TypeError(msg) |
|
1731 | 1729 | return stb |
|
1732 | 1730 | |
|
1733 | 1731 | if handler is None: |
|
1734 | 1732 | wrapped = dummy_handler |
|
1735 | 1733 | else: |
|
1736 | 1734 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1737 | 1735 | """wrap CustomTB handler, to protect IPython from user code |
|
1738 | 1736 | |
|
1739 | 1737 | This makes it harder (but not impossible) for custom exception |
|
1740 | 1738 | handlers to crash IPython. |
|
1741 | 1739 | """ |
|
1742 | 1740 | try: |
|
1743 | 1741 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1744 | 1742 | return validate_stb(stb) |
|
1745 | 1743 | except: |
|
1746 | 1744 | # clear custom handler immediately |
|
1747 | 1745 | self.set_custom_exc((), None) |
|
1748 | 1746 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1749 | 1747 | # show the exception in handler first |
|
1750 | 1748 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1751 | 1749 | print(self.InteractiveTB.stb2text(stb)) |
|
1752 | 1750 | print("The original exception:") |
|
1753 | 1751 | stb = self.InteractiveTB.structured_traceback( |
|
1754 | 1752 | (etype,value,tb), tb_offset=tb_offset |
|
1755 | 1753 | ) |
|
1756 | 1754 | return stb |
|
1757 | 1755 | |
|
1758 | 1756 | self.CustomTB = types.MethodType(wrapped,self) |
|
1759 | 1757 | self.custom_exceptions = exc_tuple |
|
1760 | 1758 | |
|
1761 | 1759 | def excepthook(self, etype, value, tb): |
|
1762 | 1760 | """One more defense for GUI apps that call sys.excepthook. |
|
1763 | 1761 | |
|
1764 | 1762 | GUI frameworks like wxPython trap exceptions and call |
|
1765 | 1763 | sys.excepthook themselves. I guess this is a feature that |
|
1766 | 1764 | enables them to keep running after exceptions that would |
|
1767 | 1765 | otherwise kill their mainloop. This is a bother for IPython |
|
1768 | 1766 | which excepts to catch all of the program exceptions with a try: |
|
1769 | 1767 | except: statement. |
|
1770 | 1768 | |
|
1771 | 1769 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1772 | 1770 | any app directly invokes sys.excepthook, it will look to the user like |
|
1773 | 1771 | IPython crashed. In order to work around this, we can disable the |
|
1774 | 1772 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1775 | 1773 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1776 | 1774 | call sys.excepthook will generate a regular-looking exception from |
|
1777 | 1775 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1778 | 1776 | crashes. |
|
1779 | 1777 | |
|
1780 | 1778 | This hook should be used sparingly, only in places which are not likely |
|
1781 | 1779 | to be true IPython errors. |
|
1782 | 1780 | """ |
|
1783 | 1781 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1784 | 1782 | |
|
1785 | 1783 | def _get_exc_info(self, exc_tuple=None): |
|
1786 | 1784 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1787 | 1785 | |
|
1788 | 1786 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1789 | 1787 | from whichever source. |
|
1790 | 1788 | |
|
1791 | 1789 | raises ValueError if none of these contain any information |
|
1792 | 1790 | """ |
|
1793 | 1791 | if exc_tuple is None: |
|
1794 | 1792 | etype, value, tb = sys.exc_info() |
|
1795 | 1793 | else: |
|
1796 | 1794 | etype, value, tb = exc_tuple |
|
1797 | 1795 | |
|
1798 | 1796 | if etype is None: |
|
1799 | 1797 | if hasattr(sys, 'last_type'): |
|
1800 | 1798 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1801 | 1799 | sys.last_traceback |
|
1802 | 1800 | |
|
1803 | 1801 | if etype is None: |
|
1804 | 1802 | raise ValueError("No exception to find") |
|
1805 | 1803 | |
|
1806 | 1804 | # Now store the exception info in sys.last_type etc. |
|
1807 | 1805 | # WARNING: these variables are somewhat deprecated and not |
|
1808 | 1806 | # necessarily safe to use in a threaded environment, but tools |
|
1809 | 1807 | # like pdb depend on their existence, so let's set them. If we |
|
1810 | 1808 | # find problems in the field, we'll need to revisit their use. |
|
1811 | 1809 | sys.last_type = etype |
|
1812 | 1810 | sys.last_value = value |
|
1813 | 1811 | sys.last_traceback = tb |
|
1814 | 1812 | |
|
1815 | 1813 | return etype, value, tb |
|
1816 | 1814 | |
|
1817 | 1815 | def show_usage_error(self, exc): |
|
1818 | 1816 | """Show a short message for UsageErrors |
|
1819 | 1817 | |
|
1820 | 1818 | These are special exceptions that shouldn't show a traceback. |
|
1821 | 1819 | """ |
|
1822 | 1820 | print("UsageError: %s" % exc, file=sys.stderr) |
|
1823 | 1821 | |
|
1824 | 1822 | def get_exception_only(self, exc_tuple=None): |
|
1825 | 1823 | """ |
|
1826 | 1824 | Return as a string (ending with a newline) the exception that |
|
1827 | 1825 | just occurred, without any traceback. |
|
1828 | 1826 | """ |
|
1829 | 1827 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1830 | 1828 | msg = traceback.format_exception_only(etype, value) |
|
1831 | 1829 | return ''.join(msg) |
|
1832 | 1830 | |
|
1833 | 1831 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1834 | 1832 | exception_only=False): |
|
1835 | 1833 | """Display the exception that just occurred. |
|
1836 | 1834 | |
|
1837 | 1835 | If nothing is known about the exception, this is the method which |
|
1838 | 1836 | should be used throughout the code for presenting user tracebacks, |
|
1839 | 1837 | rather than directly invoking the InteractiveTB object. |
|
1840 | 1838 | |
|
1841 | 1839 | A specific showsyntaxerror() also exists, but this method can take |
|
1842 | 1840 | care of calling it if needed, so unless you are explicitly catching a |
|
1843 | 1841 | SyntaxError exception, don't try to analyze the stack manually and |
|
1844 | 1842 | simply call this method.""" |
|
1845 | 1843 | |
|
1846 | 1844 | try: |
|
1847 | 1845 | try: |
|
1848 | 1846 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1849 | 1847 | except ValueError: |
|
1850 | 1848 | print('No traceback available to show.', file=sys.stderr) |
|
1851 | 1849 | return |
|
1852 | 1850 | |
|
1853 | 1851 | if issubclass(etype, SyntaxError): |
|
1854 | 1852 | # Though this won't be called by syntax errors in the input |
|
1855 | 1853 | # line, there may be SyntaxError cases with imported code. |
|
1856 | 1854 | self.showsyntaxerror(filename) |
|
1857 | 1855 | elif etype is UsageError: |
|
1858 | 1856 | self.show_usage_error(value) |
|
1859 | 1857 | else: |
|
1860 | 1858 | if exception_only: |
|
1861 | 1859 | stb = ['An exception has occurred, use %tb to see ' |
|
1862 | 1860 | 'the full traceback.\n'] |
|
1863 | 1861 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1864 | 1862 | value)) |
|
1865 | 1863 | else: |
|
1866 | 1864 | try: |
|
1867 | 1865 | # Exception classes can customise their traceback - we |
|
1868 | 1866 | # use this in IPython.parallel for exceptions occurring |
|
1869 | 1867 | # in the engines. This should return a list of strings. |
|
1870 | 1868 | stb = value._render_traceback_() |
|
1871 | 1869 | except Exception: |
|
1872 | 1870 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1873 | 1871 | value, tb, tb_offset=tb_offset) |
|
1874 | 1872 | |
|
1875 | 1873 | self._showtraceback(etype, value, stb) |
|
1876 | 1874 | if self.call_pdb: |
|
1877 | 1875 | # drop into debugger |
|
1878 | 1876 | self.debugger(force=True) |
|
1879 | 1877 | return |
|
1880 | 1878 | |
|
1881 | 1879 | # Actually show the traceback |
|
1882 | 1880 | self._showtraceback(etype, value, stb) |
|
1883 | 1881 | |
|
1884 | 1882 | except KeyboardInterrupt: |
|
1885 | 1883 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
1886 | 1884 | |
|
1887 | 1885 | def _showtraceback(self, etype, evalue, stb): |
|
1888 | 1886 | """Actually show a traceback. |
|
1889 | 1887 | |
|
1890 | 1888 | Subclasses may override this method to put the traceback on a different |
|
1891 | 1889 | place, like a side channel. |
|
1892 | 1890 | """ |
|
1893 | 1891 | print(self.InteractiveTB.stb2text(stb)) |
|
1894 | 1892 | |
|
1895 | 1893 | def showsyntaxerror(self, filename=None): |
|
1896 | 1894 | """Display the syntax error that just occurred. |
|
1897 | 1895 | |
|
1898 | 1896 | This doesn't display a stack trace because there isn't one. |
|
1899 | 1897 | |
|
1900 | 1898 | If a filename is given, it is stuffed in the exception instead |
|
1901 | 1899 | of what was there before (because Python's parser always uses |
|
1902 | 1900 | "<string>" when reading from a string). |
|
1903 | 1901 | """ |
|
1904 | 1902 | etype, value, last_traceback = self._get_exc_info() |
|
1905 | 1903 | |
|
1906 | 1904 | if filename and issubclass(etype, SyntaxError): |
|
1907 | 1905 | try: |
|
1908 | 1906 | value.filename = filename |
|
1909 | 1907 | except: |
|
1910 | 1908 | # Not the format we expect; leave it alone |
|
1911 | 1909 | pass |
|
1912 | 1910 | |
|
1913 | 1911 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1914 | 1912 | self._showtraceback(etype, value, stb) |
|
1915 | 1913 | |
|
1916 | 1914 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1917 | 1915 | # the %paste magic. |
|
1918 | 1916 | def showindentationerror(self): |
|
1919 | 1917 | """Called by run_cell when there's an IndentationError in code entered |
|
1920 | 1918 | at the prompt. |
|
1921 | 1919 | |
|
1922 | 1920 | This is overridden in TerminalInteractiveShell to show a message about |
|
1923 | 1921 | the %paste magic.""" |
|
1924 | 1922 | self.showsyntaxerror() |
|
1925 | 1923 | |
|
1926 | 1924 | #------------------------------------------------------------------------- |
|
1927 | 1925 | # Things related to readline |
|
1928 | 1926 | #------------------------------------------------------------------------- |
|
1929 | 1927 | |
|
1930 | 1928 | def init_readline(self): |
|
1931 | 1929 | """Moved to terminal subclass, here only to simplify the init logic.""" |
|
1932 | 1930 | self.readline = None |
|
1933 | 1931 | # Set a number of methods that depend on readline to be no-op |
|
1934 | 1932 | self.readline_no_record = NoOpContext() |
|
1935 | 1933 | self.set_readline_completer = no_op |
|
1936 | 1934 | self.set_custom_completer = no_op |
|
1937 | 1935 | |
|
1938 | 1936 | @skip_doctest |
|
1939 | 1937 | def set_next_input(self, s, replace=False): |
|
1940 | 1938 | """ Sets the 'default' input string for the next command line. |
|
1941 | 1939 | |
|
1942 | 1940 | Example:: |
|
1943 | 1941 | |
|
1944 | 1942 | In [1]: _ip.set_next_input("Hello Word") |
|
1945 | 1943 | In [2]: Hello Word_ # cursor is here |
|
1946 | 1944 | """ |
|
1947 | 1945 | self.rl_next_input = py3compat.cast_bytes_py2(s) |
|
1948 | 1946 | |
|
1949 | 1947 | def _indent_current_str(self): |
|
1950 | 1948 | """return the current level of indentation as a string""" |
|
1951 | 1949 | return self.input_splitter.indent_spaces * ' ' |
|
1952 | 1950 | |
|
1953 | 1951 | #------------------------------------------------------------------------- |
|
1954 | 1952 | # Things related to text completion |
|
1955 | 1953 | #------------------------------------------------------------------------- |
|
1956 | 1954 | |
|
1957 | 1955 | def init_completer(self): |
|
1958 | 1956 | """Initialize the completion machinery. |
|
1959 | 1957 | |
|
1960 | 1958 | This creates completion machinery that can be used by client code, |
|
1961 | 1959 | either interactively in-process (typically triggered by the readline |
|
1962 | 1960 | library), programmatically (such as in test suites) or out-of-process |
|
1963 | 1961 | (typically over the network by remote frontends). |
|
1964 | 1962 | """ |
|
1965 | 1963 | from IPython.core.completer import IPCompleter |
|
1966 | 1964 | from IPython.core.completerlib import (module_completer, |
|
1967 | 1965 | magic_run_completer, cd_completer, reset_completer) |
|
1968 | 1966 | |
|
1969 | 1967 | self.Completer = IPCompleter(shell=self, |
|
1970 | 1968 | namespace=self.user_ns, |
|
1971 | 1969 | global_namespace=self.user_global_ns, |
|
1972 | 1970 | use_readline=self.has_readline, |
|
1973 | 1971 | parent=self, |
|
1974 | 1972 | ) |
|
1975 | 1973 | self.configurables.append(self.Completer) |
|
1976 | 1974 | |
|
1977 | 1975 | # Add custom completers to the basic ones built into IPCompleter |
|
1978 | 1976 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1979 | 1977 | self.strdispatchers['complete_command'] = sdisp |
|
1980 | 1978 | self.Completer.custom_completers = sdisp |
|
1981 | 1979 | |
|
1982 | 1980 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1983 | 1981 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1984 | 1982 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
1985 | 1983 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1986 | 1984 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1987 | 1985 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
1988 | 1986 | |
|
1989 | 1987 | |
|
1990 | 1988 | @skip_doctest_py2 |
|
1991 | 1989 | def complete(self, text, line=None, cursor_pos=None): |
|
1992 | 1990 | """Return the completed text and a list of completions. |
|
1993 | 1991 | |
|
1994 | 1992 | Parameters |
|
1995 | 1993 | ---------- |
|
1996 | 1994 | |
|
1997 | 1995 | text : string |
|
1998 | 1996 | A string of text to be completed on. It can be given as empty and |
|
1999 | 1997 | instead a line/position pair are given. In this case, the |
|
2000 | 1998 | completer itself will split the line like readline does. |
|
2001 | 1999 | |
|
2002 | 2000 | line : string, optional |
|
2003 | 2001 | The complete line that text is part of. |
|
2004 | 2002 | |
|
2005 | 2003 | cursor_pos : int, optional |
|
2006 | 2004 | The position of the cursor on the input line. |
|
2007 | 2005 | |
|
2008 | 2006 | Returns |
|
2009 | 2007 | ------- |
|
2010 | 2008 | text : string |
|
2011 | 2009 | The actual text that was completed. |
|
2012 | 2010 | |
|
2013 | 2011 | matches : list |
|
2014 | 2012 | A sorted list with all possible completions. |
|
2015 | 2013 | |
|
2016 | 2014 | The optional arguments allow the completion to take more context into |
|
2017 | 2015 | account, and are part of the low-level completion API. |
|
2018 | 2016 | |
|
2019 | 2017 | This is a wrapper around the completion mechanism, similar to what |
|
2020 | 2018 | readline does at the command line when the TAB key is hit. By |
|
2021 | 2019 | exposing it as a method, it can be used by other non-readline |
|
2022 | 2020 | environments (such as GUIs) for text completion. |
|
2023 | 2021 | |
|
2024 | 2022 | Simple usage example: |
|
2025 | 2023 | |
|
2026 | 2024 | In [1]: x = 'hello' |
|
2027 | 2025 | |
|
2028 | 2026 | In [2]: _ip.complete('x.l') |
|
2029 | 2027 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2030 | 2028 | """ |
|
2031 | 2029 | |
|
2032 | 2030 | # Inject names into __builtin__ so we can complete on the added names. |
|
2033 | 2031 | with self.builtin_trap: |
|
2034 | 2032 | return self.Completer.complete(text, line, cursor_pos) |
|
2035 | 2033 | |
|
2036 | 2034 | def set_custom_completer(self, completer, pos=0): |
|
2037 | 2035 | """Adds a new custom completer function. |
|
2038 | 2036 | |
|
2039 | 2037 | The position argument (defaults to 0) is the index in the completers |
|
2040 | 2038 | list where you want the completer to be inserted.""" |
|
2041 | 2039 | |
|
2042 | 2040 | newcomp = types.MethodType(completer,self.Completer) |
|
2043 | 2041 | self.Completer.matchers.insert(pos,newcomp) |
|
2044 | 2042 | |
|
2045 | 2043 | def set_completer_frame(self, frame=None): |
|
2046 | 2044 | """Set the frame of the completer.""" |
|
2047 | 2045 | if frame: |
|
2048 | 2046 | self.Completer.namespace = frame.f_locals |
|
2049 | 2047 | self.Completer.global_namespace = frame.f_globals |
|
2050 | 2048 | else: |
|
2051 | 2049 | self.Completer.namespace = self.user_ns |
|
2052 | 2050 | self.Completer.global_namespace = self.user_global_ns |
|
2053 | 2051 | |
|
2054 | 2052 | #------------------------------------------------------------------------- |
|
2055 | 2053 | # Things related to magics |
|
2056 | 2054 | #------------------------------------------------------------------------- |
|
2057 | 2055 | |
|
2058 | 2056 | def init_magics(self): |
|
2059 | 2057 | from IPython.core import magics as m |
|
2060 | 2058 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2061 | 2059 | parent=self, |
|
2062 | 2060 | user_magics=m.UserMagics(self)) |
|
2063 | 2061 | self.configurables.append(self.magics_manager) |
|
2064 | 2062 | |
|
2065 | 2063 | # Expose as public API from the magics manager |
|
2066 | 2064 | self.register_magics = self.magics_manager.register |
|
2067 | 2065 | |
|
2068 | 2066 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2069 | 2067 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2070 | 2068 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2071 | 2069 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2072 | 2070 | ) |
|
2073 | 2071 | |
|
2074 | 2072 | # Register Magic Aliases |
|
2075 | 2073 | mman = self.magics_manager |
|
2076 | 2074 | # FIXME: magic aliases should be defined by the Magics classes |
|
2077 | 2075 | # or in MagicsManager, not here |
|
2078 | 2076 | mman.register_alias('ed', 'edit') |
|
2079 | 2077 | mman.register_alias('hist', 'history') |
|
2080 | 2078 | mman.register_alias('rep', 'recall') |
|
2081 | 2079 | mman.register_alias('SVG', 'svg', 'cell') |
|
2082 | 2080 | mman.register_alias('HTML', 'html', 'cell') |
|
2083 | 2081 | mman.register_alias('file', 'writefile', 'cell') |
|
2084 | 2082 | |
|
2085 | 2083 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2086 | 2084 | # should be split into a prompt manager and displayhook. We probably |
|
2087 | 2085 | # even need a centralize colors management object. |
|
2088 | 2086 | self.magic('colors %s' % self.colors) |
|
2089 | 2087 | |
|
2090 | 2088 | # Defined here so that it's included in the documentation |
|
2091 | 2089 | @functools.wraps(magic.MagicsManager.register_function) |
|
2092 | 2090 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2093 | 2091 | self.magics_manager.register_function(func, |
|
2094 | 2092 | magic_kind=magic_kind, magic_name=magic_name) |
|
2095 | 2093 | |
|
2096 | 2094 | def run_line_magic(self, magic_name, line): |
|
2097 | 2095 | """Execute the given line magic. |
|
2098 | 2096 | |
|
2099 | 2097 | Parameters |
|
2100 | 2098 | ---------- |
|
2101 | 2099 | magic_name : str |
|
2102 | 2100 | Name of the desired magic function, without '%' prefix. |
|
2103 | 2101 | |
|
2104 | 2102 | line : str |
|
2105 | 2103 | The rest of the input line as a single string. |
|
2106 | 2104 | """ |
|
2107 | 2105 | fn = self.find_line_magic(magic_name) |
|
2108 | 2106 | if fn is None: |
|
2109 | 2107 | cm = self.find_cell_magic(magic_name) |
|
2110 | 2108 | etpl = "Line magic function `%%%s` not found%s." |
|
2111 | 2109 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2112 | 2110 | 'did you mean that instead?)' % magic_name ) |
|
2113 | 2111 | error(etpl % (magic_name, extra)) |
|
2114 | 2112 | else: |
|
2115 | 2113 | # Note: this is the distance in the stack to the user's frame. |
|
2116 | 2114 | # This will need to be updated if the internal calling logic gets |
|
2117 | 2115 | # refactored, or else we'll be expanding the wrong variables. |
|
2118 | 2116 | stack_depth = 2 |
|
2119 | 2117 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2120 | 2118 | # Put magic args in a list so we can call with f(*a) syntax |
|
2121 | 2119 | args = [magic_arg_s] |
|
2122 | 2120 | kwargs = {} |
|
2123 | 2121 | # Grab local namespace if we need it: |
|
2124 | 2122 | if getattr(fn, "needs_local_scope", False): |
|
2125 | 2123 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2126 | 2124 | with self.builtin_trap: |
|
2127 | 2125 | result = fn(*args,**kwargs) |
|
2128 | 2126 | return result |
|
2129 | 2127 | |
|
2130 | 2128 | def run_cell_magic(self, magic_name, line, cell): |
|
2131 | 2129 | """Execute the given cell magic. |
|
2132 | 2130 | |
|
2133 | 2131 | Parameters |
|
2134 | 2132 | ---------- |
|
2135 | 2133 | magic_name : str |
|
2136 | 2134 | Name of the desired magic function, without '%' prefix. |
|
2137 | 2135 | |
|
2138 | 2136 | line : str |
|
2139 | 2137 | The rest of the first input line as a single string. |
|
2140 | 2138 | |
|
2141 | 2139 | cell : str |
|
2142 | 2140 | The body of the cell as a (possibly multiline) string. |
|
2143 | 2141 | """ |
|
2144 | 2142 | fn = self.find_cell_magic(magic_name) |
|
2145 | 2143 | if fn is None: |
|
2146 | 2144 | lm = self.find_line_magic(magic_name) |
|
2147 | 2145 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2148 | 2146 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2149 | 2147 | 'did you mean that instead?)'.format(magic_name)) |
|
2150 | 2148 | error(etpl.format(magic_name, extra)) |
|
2151 | 2149 | elif cell == '': |
|
2152 | 2150 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2153 | 2151 | if self.find_line_magic(magic_name) is not None: |
|
2154 | 2152 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2155 | 2153 | raise UsageError(message) |
|
2156 | 2154 | else: |
|
2157 | 2155 | # Note: this is the distance in the stack to the user's frame. |
|
2158 | 2156 | # This will need to be updated if the internal calling logic gets |
|
2159 | 2157 | # refactored, or else we'll be expanding the wrong variables. |
|
2160 | 2158 | stack_depth = 2 |
|
2161 | 2159 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2162 | 2160 | with self.builtin_trap: |
|
2163 | 2161 | result = fn(magic_arg_s, cell) |
|
2164 | 2162 | return result |
|
2165 | 2163 | |
|
2166 | 2164 | def find_line_magic(self, magic_name): |
|
2167 | 2165 | """Find and return a line magic by name. |
|
2168 | 2166 | |
|
2169 | 2167 | Returns None if the magic isn't found.""" |
|
2170 | 2168 | return self.magics_manager.magics['line'].get(magic_name) |
|
2171 | 2169 | |
|
2172 | 2170 | def find_cell_magic(self, magic_name): |
|
2173 | 2171 | """Find and return a cell magic by name. |
|
2174 | 2172 | |
|
2175 | 2173 | Returns None if the magic isn't found.""" |
|
2176 | 2174 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2177 | 2175 | |
|
2178 | 2176 | def find_magic(self, magic_name, magic_kind='line'): |
|
2179 | 2177 | """Find and return a magic of the given type by name. |
|
2180 | 2178 | |
|
2181 | 2179 | Returns None if the magic isn't found.""" |
|
2182 | 2180 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2183 | 2181 | |
|
2184 | 2182 | def magic(self, arg_s): |
|
2185 | 2183 | """DEPRECATED. Use run_line_magic() instead. |
|
2186 | 2184 | |
|
2187 | 2185 | Call a magic function by name. |
|
2188 | 2186 | |
|
2189 | 2187 | Input: a string containing the name of the magic function to call and |
|
2190 | 2188 | any additional arguments to be passed to the magic. |
|
2191 | 2189 | |
|
2192 | 2190 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2193 | 2191 | prompt: |
|
2194 | 2192 | |
|
2195 | 2193 | In[1]: %name -opt foo bar |
|
2196 | 2194 | |
|
2197 | 2195 | To call a magic without arguments, simply use magic('name'). |
|
2198 | 2196 | |
|
2199 | 2197 | This provides a proper Python function to call IPython's magics in any |
|
2200 | 2198 | valid Python code you can type at the interpreter, including loops and |
|
2201 | 2199 | compound statements. |
|
2202 | 2200 | """ |
|
2203 | 2201 | # TODO: should we issue a loud deprecation warning here? |
|
2204 | 2202 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2205 | 2203 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2206 | 2204 | return self.run_line_magic(magic_name, magic_arg_s) |
|
2207 | 2205 | |
|
2208 | 2206 | #------------------------------------------------------------------------- |
|
2209 | 2207 | # Things related to macros |
|
2210 | 2208 | #------------------------------------------------------------------------- |
|
2211 | 2209 | |
|
2212 | 2210 | def define_macro(self, name, themacro): |
|
2213 | 2211 | """Define a new macro |
|
2214 | 2212 | |
|
2215 | 2213 | Parameters |
|
2216 | 2214 | ---------- |
|
2217 | 2215 | name : str |
|
2218 | 2216 | The name of the macro. |
|
2219 | 2217 | themacro : str or Macro |
|
2220 | 2218 | The action to do upon invoking the macro. If a string, a new |
|
2221 | 2219 | Macro object is created by passing the string to it. |
|
2222 | 2220 | """ |
|
2223 | 2221 | |
|
2224 | 2222 | from IPython.core import macro |
|
2225 | 2223 | |
|
2226 | 2224 | if isinstance(themacro, string_types): |
|
2227 | 2225 | themacro = macro.Macro(themacro) |
|
2228 | 2226 | if not isinstance(themacro, macro.Macro): |
|
2229 | 2227 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2230 | 2228 | self.user_ns[name] = themacro |
|
2231 | 2229 | |
|
2232 | 2230 | #------------------------------------------------------------------------- |
|
2233 | 2231 | # Things related to the running of system commands |
|
2234 | 2232 | #------------------------------------------------------------------------- |
|
2235 | 2233 | |
|
2236 | 2234 | def system_piped(self, cmd): |
|
2237 | 2235 | """Call the given cmd in a subprocess, piping stdout/err |
|
2238 | 2236 | |
|
2239 | 2237 | Parameters |
|
2240 | 2238 | ---------- |
|
2241 | 2239 | cmd : str |
|
2242 | 2240 | Command to execute (can not end in '&', as background processes are |
|
2243 | 2241 | not supported. Should not be a command that expects input |
|
2244 | 2242 | other than simple text. |
|
2245 | 2243 | """ |
|
2246 | 2244 | if cmd.rstrip().endswith('&'): |
|
2247 | 2245 | # this is *far* from a rigorous test |
|
2248 | 2246 | # We do not support backgrounding processes because we either use |
|
2249 | 2247 | # pexpect or pipes to read from. Users can always just call |
|
2250 | 2248 | # os.system() or use ip.system=ip.system_raw |
|
2251 | 2249 | # if they really want a background process. |
|
2252 | 2250 | raise OSError("Background processes not supported.") |
|
2253 | 2251 | |
|
2254 | 2252 | # we explicitly do NOT return the subprocess status code, because |
|
2255 | 2253 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2256 | 2254 | # Instead, we store the exit_code in user_ns. |
|
2257 | 2255 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2258 | 2256 | |
|
2259 | 2257 | def system_raw(self, cmd): |
|
2260 | 2258 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2261 | 2259 | subprocess.call using the system shell on other platforms. |
|
2262 | 2260 | |
|
2263 | 2261 | Parameters |
|
2264 | 2262 | ---------- |
|
2265 | 2263 | cmd : str |
|
2266 | 2264 | Command to execute. |
|
2267 | 2265 | """ |
|
2268 | 2266 | cmd = self.var_expand(cmd, depth=1) |
|
2269 | 2267 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2270 | 2268 | if sys.platform == 'win32': |
|
2271 | 2269 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2272 | 2270 | with AvoidUNCPath() as path: |
|
2273 | 2271 | if path is not None: |
|
2274 | 2272 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2275 | 2273 | cmd = py3compat.unicode_to_str(cmd) |
|
2276 | 2274 | try: |
|
2277 | 2275 | ec = os.system(cmd) |
|
2278 | 2276 | except KeyboardInterrupt: |
|
2279 | 2277 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2280 | 2278 | ec = -2 |
|
2281 | 2279 | else: |
|
2282 | 2280 | cmd = py3compat.unicode_to_str(cmd) |
|
2283 | 2281 | # For posix the result of the subprocess.call() below is an exit |
|
2284 | 2282 | # code, which by convention is zero for success, positive for |
|
2285 | 2283 | # program failure. Exit codes above 128 are reserved for signals, |
|
2286 | 2284 | # and the formula for converting a signal to an exit code is usually |
|
2287 | 2285 | # signal_number+128. To more easily differentiate between exit |
|
2288 | 2286 | # codes and signals, ipython uses negative numbers. For instance |
|
2289 | 2287 | # since control-c is signal 2 but exit code 130, ipython's |
|
2290 | 2288 | # _exit_code variable will read -2. Note that some shells like |
|
2291 | 2289 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2292 | 2290 | executable = os.environ.get('SHELL', None) |
|
2293 | 2291 | try: |
|
2294 | 2292 | # Use env shell instead of default /bin/sh |
|
2295 | 2293 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2296 | 2294 | except KeyboardInterrupt: |
|
2297 | 2295 | # intercept control-C; a long traceback is not useful here |
|
2298 | 2296 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2299 | 2297 | ec = 130 |
|
2300 | 2298 | if ec > 128: |
|
2301 | 2299 | ec = -(ec - 128) |
|
2302 | 2300 | |
|
2303 | 2301 | # We explicitly do NOT return the subprocess status code, because |
|
2304 | 2302 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2305 | 2303 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2306 | 2304 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2307 | 2305 | # but raising SystemExit(_exit_code) will give status 254! |
|
2308 | 2306 | self.user_ns['_exit_code'] = ec |
|
2309 | 2307 | |
|
2310 | 2308 | # use piped system by default, because it is better behaved |
|
2311 | 2309 | system = system_piped |
|
2312 | 2310 | |
|
2313 | 2311 | def getoutput(self, cmd, split=True, depth=0): |
|
2314 | 2312 | """Get output (possibly including stderr) from a subprocess. |
|
2315 | 2313 | |
|
2316 | 2314 | Parameters |
|
2317 | 2315 | ---------- |
|
2318 | 2316 | cmd : str |
|
2319 | 2317 | Command to execute (can not end in '&', as background processes are |
|
2320 | 2318 | not supported. |
|
2321 | 2319 | split : bool, optional |
|
2322 | 2320 | If True, split the output into an IPython SList. Otherwise, an |
|
2323 | 2321 | IPython LSString is returned. These are objects similar to normal |
|
2324 | 2322 | lists and strings, with a few convenience attributes for easier |
|
2325 | 2323 | manipulation of line-based output. You can use '?' on them for |
|
2326 | 2324 | details. |
|
2327 | 2325 | depth : int, optional |
|
2328 | 2326 | How many frames above the caller are the local variables which should |
|
2329 | 2327 | be expanded in the command string? The default (0) assumes that the |
|
2330 | 2328 | expansion variables are in the stack frame calling this function. |
|
2331 | 2329 | """ |
|
2332 | 2330 | if cmd.rstrip().endswith('&'): |
|
2333 | 2331 | # this is *far* from a rigorous test |
|
2334 | 2332 | raise OSError("Background processes not supported.") |
|
2335 | 2333 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2336 | 2334 | if split: |
|
2337 | 2335 | out = SList(out.splitlines()) |
|
2338 | 2336 | else: |
|
2339 | 2337 | out = LSString(out) |
|
2340 | 2338 | return out |
|
2341 | 2339 | |
|
2342 | 2340 | #------------------------------------------------------------------------- |
|
2343 | 2341 | # Things related to aliases |
|
2344 | 2342 | #------------------------------------------------------------------------- |
|
2345 | 2343 | |
|
2346 | 2344 | def init_alias(self): |
|
2347 | 2345 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2348 | 2346 | self.configurables.append(self.alias_manager) |
|
2349 | 2347 | |
|
2350 | 2348 | #------------------------------------------------------------------------- |
|
2351 | 2349 | # Things related to extensions |
|
2352 | 2350 | #------------------------------------------------------------------------- |
|
2353 | 2351 | |
|
2354 | 2352 | def init_extension_manager(self): |
|
2355 | 2353 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2356 | 2354 | self.configurables.append(self.extension_manager) |
|
2357 | 2355 | |
|
2358 | 2356 | #------------------------------------------------------------------------- |
|
2359 | 2357 | # Things related to payloads |
|
2360 | 2358 | #------------------------------------------------------------------------- |
|
2361 | 2359 | |
|
2362 | 2360 | def init_payload(self): |
|
2363 | 2361 | self.payload_manager = PayloadManager(parent=self) |
|
2364 | 2362 | self.configurables.append(self.payload_manager) |
|
2365 | 2363 | |
|
2366 | 2364 | #------------------------------------------------------------------------- |
|
2367 | 2365 | # Things related to the prefilter |
|
2368 | 2366 | #------------------------------------------------------------------------- |
|
2369 | 2367 | |
|
2370 | 2368 | def init_prefilter(self): |
|
2371 | 2369 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2372 | 2370 | self.configurables.append(self.prefilter_manager) |
|
2373 | 2371 | # Ultimately this will be refactored in the new interpreter code, but |
|
2374 | 2372 | # for now, we should expose the main prefilter method (there's legacy |
|
2375 | 2373 | # code out there that may rely on this). |
|
2376 | 2374 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2377 | 2375 | |
|
2378 | 2376 | def auto_rewrite_input(self, cmd): |
|
2379 | 2377 | """Print to the screen the rewritten form of the user's command. |
|
2380 | 2378 | |
|
2381 | 2379 | This shows visual feedback by rewriting input lines that cause |
|
2382 | 2380 | automatic calling to kick in, like:: |
|
2383 | 2381 | |
|
2384 | 2382 | /f x |
|
2385 | 2383 | |
|
2386 | 2384 | into:: |
|
2387 | 2385 | |
|
2388 | 2386 | ------> f(x) |
|
2389 | 2387 | |
|
2390 | 2388 | after the user's input prompt. This helps the user understand that the |
|
2391 | 2389 | input line was transformed automatically by IPython. |
|
2392 | 2390 | """ |
|
2393 | 2391 | if not self.show_rewritten_input: |
|
2394 | 2392 | return |
|
2395 | 2393 | |
|
2396 | 2394 | # This is overridden in TerminalInteractiveShell to use fancy prompts |
|
2397 | 2395 | print("------> " + cmd) |
|
2398 | 2396 | |
|
2399 | 2397 | #------------------------------------------------------------------------- |
|
2400 | 2398 | # Things related to extracting values/expressions from kernel and user_ns |
|
2401 | 2399 | #------------------------------------------------------------------------- |
|
2402 | 2400 | |
|
2403 | 2401 | def _user_obj_error(self): |
|
2404 | 2402 | """return simple exception dict |
|
2405 | 2403 | |
|
2406 | 2404 | for use in user_expressions |
|
2407 | 2405 | """ |
|
2408 | 2406 | |
|
2409 | 2407 | etype, evalue, tb = self._get_exc_info() |
|
2410 | 2408 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2411 | 2409 | |
|
2412 | 2410 | exc_info = { |
|
2413 | 2411 | u'status' : 'error', |
|
2414 | 2412 | u'traceback' : stb, |
|
2415 | 2413 | u'ename' : unicode_type(etype.__name__), |
|
2416 | 2414 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2417 | 2415 | } |
|
2418 | 2416 | |
|
2419 | 2417 | return exc_info |
|
2420 | 2418 | |
|
2421 | 2419 | def _format_user_obj(self, obj): |
|
2422 | 2420 | """format a user object to display dict |
|
2423 | 2421 | |
|
2424 | 2422 | for use in user_expressions |
|
2425 | 2423 | """ |
|
2426 | 2424 | |
|
2427 | 2425 | data, md = self.display_formatter.format(obj) |
|
2428 | 2426 | value = { |
|
2429 | 2427 | 'status' : 'ok', |
|
2430 | 2428 | 'data' : data, |
|
2431 | 2429 | 'metadata' : md, |
|
2432 | 2430 | } |
|
2433 | 2431 | return value |
|
2434 | 2432 | |
|
2435 | 2433 | def user_expressions(self, expressions): |
|
2436 | 2434 | """Evaluate a dict of expressions in the user's namespace. |
|
2437 | 2435 | |
|
2438 | 2436 | Parameters |
|
2439 | 2437 | ---------- |
|
2440 | 2438 | expressions : dict |
|
2441 | 2439 | A dict with string keys and string values. The expression values |
|
2442 | 2440 | should be valid Python expressions, each of which will be evaluated |
|
2443 | 2441 | in the user namespace. |
|
2444 | 2442 | |
|
2445 | 2443 | Returns |
|
2446 | 2444 | ------- |
|
2447 | 2445 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2448 | 2446 | display_data of each value. |
|
2449 | 2447 | """ |
|
2450 | 2448 | out = {} |
|
2451 | 2449 | user_ns = self.user_ns |
|
2452 | 2450 | global_ns = self.user_global_ns |
|
2453 | 2451 | |
|
2454 | 2452 | for key, expr in iteritems(expressions): |
|
2455 | 2453 | try: |
|
2456 | 2454 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2457 | 2455 | except: |
|
2458 | 2456 | value = self._user_obj_error() |
|
2459 | 2457 | out[key] = value |
|
2460 | 2458 | return out |
|
2461 | 2459 | |
|
2462 | 2460 | #------------------------------------------------------------------------- |
|
2463 | 2461 | # Things related to the running of code |
|
2464 | 2462 | #------------------------------------------------------------------------- |
|
2465 | 2463 | |
|
2466 | 2464 | def ex(self, cmd): |
|
2467 | 2465 | """Execute a normal python statement in user namespace.""" |
|
2468 | 2466 | with self.builtin_trap: |
|
2469 | 2467 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2470 | 2468 | |
|
2471 | 2469 | def ev(self, expr): |
|
2472 | 2470 | """Evaluate python expression expr in user namespace. |
|
2473 | 2471 | |
|
2474 | 2472 | Returns the result of evaluation |
|
2475 | 2473 | """ |
|
2476 | 2474 | with self.builtin_trap: |
|
2477 | 2475 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2478 | 2476 | |
|
2479 | 2477 | def safe_execfile(self, fname, *where, **kw): |
|
2480 | 2478 | """A safe version of the builtin execfile(). |
|
2481 | 2479 | |
|
2482 | 2480 | This version will never throw an exception, but instead print |
|
2483 | 2481 | helpful error messages to the screen. This only works on pure |
|
2484 | 2482 | Python files with the .py extension. |
|
2485 | 2483 | |
|
2486 | 2484 | Parameters |
|
2487 | 2485 | ---------- |
|
2488 | 2486 | fname : string |
|
2489 | 2487 | The name of the file to be executed. |
|
2490 | 2488 | where : tuple |
|
2491 | 2489 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2492 | 2490 | If only one is given, it is passed as both. |
|
2493 | 2491 | exit_ignore : bool (False) |
|
2494 | 2492 | If True, then silence SystemExit for non-zero status (it is always |
|
2495 | 2493 | silenced for zero status, as it is so common). |
|
2496 | 2494 | raise_exceptions : bool (False) |
|
2497 | 2495 | If True raise exceptions everywhere. Meant for testing. |
|
2498 | 2496 | shell_futures : bool (False) |
|
2499 | 2497 | If True, the code will share future statements with the interactive |
|
2500 | 2498 | shell. It will both be affected by previous __future__ imports, and |
|
2501 | 2499 | any __future__ imports in the code will affect the shell. If False, |
|
2502 | 2500 | __future__ imports are not shared in either direction. |
|
2503 | 2501 | |
|
2504 | 2502 | """ |
|
2505 | 2503 | kw.setdefault('exit_ignore', False) |
|
2506 | 2504 | kw.setdefault('raise_exceptions', False) |
|
2507 | 2505 | kw.setdefault('shell_futures', False) |
|
2508 | 2506 | |
|
2509 | 2507 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2510 | 2508 | |
|
2511 | 2509 | # Make sure we can open the file |
|
2512 | 2510 | try: |
|
2513 | 2511 | with open(fname): |
|
2514 | 2512 | pass |
|
2515 | 2513 | except: |
|
2516 | 2514 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2517 | 2515 | return |
|
2518 | 2516 | |
|
2519 | 2517 | # Find things also in current directory. This is needed to mimic the |
|
2520 | 2518 | # behavior of running a script from the system command line, where |
|
2521 | 2519 | # Python inserts the script's directory into sys.path |
|
2522 | 2520 | dname = os.path.dirname(fname) |
|
2523 | 2521 | |
|
2524 | 2522 | with prepended_to_syspath(dname): |
|
2525 | 2523 | try: |
|
2526 | 2524 | glob, loc = (where + (None, ))[:2] |
|
2527 | 2525 | py3compat.execfile( |
|
2528 | 2526 | fname, glob, loc, |
|
2529 | 2527 | self.compile if kw['shell_futures'] else None) |
|
2530 | 2528 | except SystemExit as status: |
|
2531 | 2529 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2532 | 2530 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2533 | 2531 | # these are considered normal by the OS: |
|
2534 | 2532 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2535 | 2533 | # 0 |
|
2536 | 2534 | # > python -c'import sys;sys.exit()'; echo $? |
|
2537 | 2535 | # 0 |
|
2538 | 2536 | # For other exit status, we show the exception unless |
|
2539 | 2537 | # explicitly silenced, but only in short form. |
|
2540 | 2538 | if status.code: |
|
2541 | 2539 | if kw['raise_exceptions']: |
|
2542 | 2540 | raise |
|
2543 | 2541 | if not kw['exit_ignore']: |
|
2544 | 2542 | self.showtraceback(exception_only=True) |
|
2545 | 2543 | except: |
|
2546 | 2544 | if kw['raise_exceptions']: |
|
2547 | 2545 | raise |
|
2548 | 2546 | # tb offset is 2 because we wrap execfile |
|
2549 | 2547 | self.showtraceback(tb_offset=2) |
|
2550 | 2548 | |
|
2551 | 2549 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2552 | 2550 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2553 | 2551 | |
|
2554 | 2552 | Parameters |
|
2555 | 2553 | ---------- |
|
2556 | 2554 | fname : str |
|
2557 | 2555 | The name of the file to execute. The filename must have a |
|
2558 | 2556 | .ipy or .ipynb extension. |
|
2559 | 2557 | shell_futures : bool (False) |
|
2560 | 2558 | If True, the code will share future statements with the interactive |
|
2561 | 2559 | shell. It will both be affected by previous __future__ imports, and |
|
2562 | 2560 | any __future__ imports in the code will affect the shell. If False, |
|
2563 | 2561 | __future__ imports are not shared in either direction. |
|
2564 | 2562 | raise_exceptions : bool (False) |
|
2565 | 2563 | If True raise exceptions everywhere. Meant for testing. |
|
2566 | 2564 | """ |
|
2567 | 2565 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2568 | 2566 | |
|
2569 | 2567 | # Make sure we can open the file |
|
2570 | 2568 | try: |
|
2571 | 2569 | with open(fname): |
|
2572 | 2570 | pass |
|
2573 | 2571 | except: |
|
2574 | 2572 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2575 | 2573 | return |
|
2576 | 2574 | |
|
2577 | 2575 | # Find things also in current directory. This is needed to mimic the |
|
2578 | 2576 | # behavior of running a script from the system command line, where |
|
2579 | 2577 | # Python inserts the script's directory into sys.path |
|
2580 | 2578 | dname = os.path.dirname(fname) |
|
2581 | 2579 | |
|
2582 | 2580 | def get_cells(): |
|
2583 | 2581 | """generator for sequence of code blocks to run""" |
|
2584 | 2582 | if fname.endswith('.ipynb'): |
|
2585 | 2583 | from nbformat import read |
|
2586 | 2584 | with io_open(fname) as f: |
|
2587 | 2585 | nb = read(f, as_version=4) |
|
2588 | 2586 | if not nb.cells: |
|
2589 | 2587 | return |
|
2590 | 2588 | for cell in nb.cells: |
|
2591 | 2589 | if cell.cell_type == 'code': |
|
2592 | 2590 | yield cell.source |
|
2593 | 2591 | else: |
|
2594 | 2592 | with open(fname) as f: |
|
2595 | 2593 | yield f.read() |
|
2596 | 2594 | |
|
2597 | 2595 | with prepended_to_syspath(dname): |
|
2598 | 2596 | try: |
|
2599 | 2597 | for cell in get_cells(): |
|
2600 | 2598 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2601 | 2599 | if raise_exceptions: |
|
2602 | 2600 | result.raise_error() |
|
2603 | 2601 | elif not result.success: |
|
2604 | 2602 | break |
|
2605 | 2603 | except: |
|
2606 | 2604 | if raise_exceptions: |
|
2607 | 2605 | raise |
|
2608 | 2606 | self.showtraceback() |
|
2609 | 2607 | warn('Unknown failure executing file: <%s>' % fname) |
|
2610 | 2608 | |
|
2611 | 2609 | def safe_run_module(self, mod_name, where): |
|
2612 | 2610 | """A safe version of runpy.run_module(). |
|
2613 | 2611 | |
|
2614 | 2612 | This version will never throw an exception, but instead print |
|
2615 | 2613 | helpful error messages to the screen. |
|
2616 | 2614 | |
|
2617 | 2615 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2618 | 2616 | |
|
2619 | 2617 | Parameters |
|
2620 | 2618 | ---------- |
|
2621 | 2619 | mod_name : string |
|
2622 | 2620 | The name of the module to be executed. |
|
2623 | 2621 | where : dict |
|
2624 | 2622 | The globals namespace. |
|
2625 | 2623 | """ |
|
2626 | 2624 | try: |
|
2627 | 2625 | try: |
|
2628 | 2626 | where.update( |
|
2629 | 2627 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2630 | 2628 | alter_sys=True) |
|
2631 | 2629 | ) |
|
2632 | 2630 | except SystemExit as status: |
|
2633 | 2631 | if status.code: |
|
2634 | 2632 | raise |
|
2635 | 2633 | except: |
|
2636 | 2634 | self.showtraceback() |
|
2637 | 2635 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2638 | 2636 | |
|
2639 | 2637 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2640 | 2638 | """Run a complete IPython cell. |
|
2641 | 2639 | |
|
2642 | 2640 | Parameters |
|
2643 | 2641 | ---------- |
|
2644 | 2642 | raw_cell : str |
|
2645 | 2643 | The code (including IPython code such as %magic functions) to run. |
|
2646 | 2644 | store_history : bool |
|
2647 | 2645 | If True, the raw and translated cell will be stored in IPython's |
|
2648 | 2646 | history. For user code calling back into IPython's machinery, this |
|
2649 | 2647 | should be set to False. |
|
2650 | 2648 | silent : bool |
|
2651 | 2649 | If True, avoid side-effects, such as implicit displayhooks and |
|
2652 | 2650 | and logging. silent=True forces store_history=False. |
|
2653 | 2651 | shell_futures : bool |
|
2654 | 2652 | If True, the code will share future statements with the interactive |
|
2655 | 2653 | shell. It will both be affected by previous __future__ imports, and |
|
2656 | 2654 | any __future__ imports in the code will affect the shell. If False, |
|
2657 | 2655 | __future__ imports are not shared in either direction. |
|
2658 | 2656 | |
|
2659 | 2657 | Returns |
|
2660 | 2658 | ------- |
|
2661 | 2659 | result : :class:`ExecutionResult` |
|
2662 | 2660 | """ |
|
2663 | 2661 | result = ExecutionResult() |
|
2664 | 2662 | |
|
2665 | 2663 | if (not raw_cell) or raw_cell.isspace(): |
|
2666 | 2664 | self.last_execution_succeeded = True |
|
2667 | 2665 | return result |
|
2668 | 2666 | |
|
2669 | 2667 | if silent: |
|
2670 | 2668 | store_history = False |
|
2671 | 2669 | |
|
2672 | 2670 | if store_history: |
|
2673 | 2671 | result.execution_count = self.execution_count |
|
2674 | 2672 | |
|
2675 | 2673 | def error_before_exec(value): |
|
2676 | 2674 | result.error_before_exec = value |
|
2677 | 2675 | self.last_execution_succeeded = False |
|
2678 | 2676 | return result |
|
2679 | 2677 | |
|
2680 | 2678 | self.events.trigger('pre_execute') |
|
2681 | 2679 | if not silent: |
|
2682 | 2680 | self.events.trigger('pre_run_cell') |
|
2683 | 2681 | |
|
2684 | 2682 | # If any of our input transformation (input_transformer_manager or |
|
2685 | 2683 | # prefilter_manager) raises an exception, we store it in this variable |
|
2686 | 2684 | # so that we can display the error after logging the input and storing |
|
2687 | 2685 | # it in the history. |
|
2688 | 2686 | preprocessing_exc_tuple = None |
|
2689 | 2687 | try: |
|
2690 | 2688 | # Static input transformations |
|
2691 | 2689 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
2692 | 2690 | except SyntaxError: |
|
2693 | 2691 | preprocessing_exc_tuple = sys.exc_info() |
|
2694 | 2692 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2695 | 2693 | else: |
|
2696 | 2694 | if len(cell.splitlines()) == 1: |
|
2697 | 2695 | # Dynamic transformations - only applied for single line commands |
|
2698 | 2696 | with self.builtin_trap: |
|
2699 | 2697 | try: |
|
2700 | 2698 | # use prefilter_lines to handle trailing newlines |
|
2701 | 2699 | # restore trailing newline for ast.parse |
|
2702 | 2700 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2703 | 2701 | except Exception: |
|
2704 | 2702 | # don't allow prefilter errors to crash IPython |
|
2705 | 2703 | preprocessing_exc_tuple = sys.exc_info() |
|
2706 | 2704 | |
|
2707 | 2705 | # Store raw and processed history |
|
2708 | 2706 | if store_history: |
|
2709 | 2707 | self.history_manager.store_inputs(self.execution_count, |
|
2710 | 2708 | cell, raw_cell) |
|
2711 | 2709 | if not silent: |
|
2712 | 2710 | self.logger.log(cell, raw_cell) |
|
2713 | 2711 | |
|
2714 | 2712 | # Display the exception if input processing failed. |
|
2715 | 2713 | if preprocessing_exc_tuple is not None: |
|
2716 | 2714 | self.showtraceback(preprocessing_exc_tuple) |
|
2717 | 2715 | if store_history: |
|
2718 | 2716 | self.execution_count += 1 |
|
2719 | 2717 | return error_before_exec(preprocessing_exc_tuple[2]) |
|
2720 | 2718 | |
|
2721 | 2719 | # Our own compiler remembers the __future__ environment. If we want to |
|
2722 | 2720 | # run code with a separate __future__ environment, use the default |
|
2723 | 2721 | # compiler |
|
2724 | 2722 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2725 | 2723 | |
|
2726 | 2724 | with self.builtin_trap: |
|
2727 | 2725 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2728 | 2726 | |
|
2729 | 2727 | with self.display_trap: |
|
2730 | 2728 | # Compile to bytecode |
|
2731 | 2729 | try: |
|
2732 | 2730 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2733 | 2731 | except self.custom_exceptions as e: |
|
2734 | 2732 | etype, value, tb = sys.exc_info() |
|
2735 | 2733 | self.CustomTB(etype, value, tb) |
|
2736 | 2734 | return error_before_exec(e) |
|
2737 | 2735 | except IndentationError as e: |
|
2738 | 2736 | self.showindentationerror() |
|
2739 | 2737 | if store_history: |
|
2740 | 2738 | self.execution_count += 1 |
|
2741 | 2739 | return error_before_exec(e) |
|
2742 | 2740 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2743 | 2741 | MemoryError) as e: |
|
2744 | 2742 | self.showsyntaxerror() |
|
2745 | 2743 | if store_history: |
|
2746 | 2744 | self.execution_count += 1 |
|
2747 | 2745 | return error_before_exec(e) |
|
2748 | 2746 | |
|
2749 | 2747 | # Apply AST transformations |
|
2750 | 2748 | try: |
|
2751 | 2749 | code_ast = self.transform_ast(code_ast) |
|
2752 | 2750 | except InputRejected as e: |
|
2753 | 2751 | self.showtraceback() |
|
2754 | 2752 | if store_history: |
|
2755 | 2753 | self.execution_count += 1 |
|
2756 | 2754 | return error_before_exec(e) |
|
2757 | 2755 | |
|
2758 | 2756 | # Give the displayhook a reference to our ExecutionResult so it |
|
2759 | 2757 | # can fill in the output value. |
|
2760 | 2758 | self.displayhook.exec_result = result |
|
2761 | 2759 | |
|
2762 | 2760 | # Execute the user code |
|
2763 | 2761 | interactivity = "none" if silent else self.ast_node_interactivity |
|
2764 | 2762 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, |
|
2765 | 2763 | interactivity=interactivity, compiler=compiler, result=result) |
|
2766 | 2764 | |
|
2767 | 2765 | self.last_execution_succeeded = not has_raised |
|
2768 | 2766 | |
|
2769 | 2767 | # Reset this so later displayed values do not modify the |
|
2770 | 2768 | # ExecutionResult |
|
2771 | 2769 | self.displayhook.exec_result = None |
|
2772 | 2770 | |
|
2773 | 2771 | self.events.trigger('post_execute') |
|
2774 | 2772 | if not silent: |
|
2775 | 2773 | self.events.trigger('post_run_cell') |
|
2776 | 2774 | |
|
2777 | 2775 | if store_history: |
|
2778 | 2776 | # Write output to the database. Does nothing unless |
|
2779 | 2777 | # history output logging is enabled. |
|
2780 | 2778 | self.history_manager.store_output(self.execution_count) |
|
2781 | 2779 | # Each cell is a *single* input, regardless of how many lines it has |
|
2782 | 2780 | self.execution_count += 1 |
|
2783 | 2781 | |
|
2784 | 2782 | return result |
|
2785 | 2783 | |
|
2786 | 2784 | def transform_ast(self, node): |
|
2787 | 2785 | """Apply the AST transformations from self.ast_transformers |
|
2788 | 2786 | |
|
2789 | 2787 | Parameters |
|
2790 | 2788 | ---------- |
|
2791 | 2789 | node : ast.Node |
|
2792 | 2790 | The root node to be transformed. Typically called with the ast.Module |
|
2793 | 2791 | produced by parsing user input. |
|
2794 | 2792 | |
|
2795 | 2793 | Returns |
|
2796 | 2794 | ------- |
|
2797 | 2795 | An ast.Node corresponding to the node it was called with. Note that it |
|
2798 | 2796 | may also modify the passed object, so don't rely on references to the |
|
2799 | 2797 | original AST. |
|
2800 | 2798 | """ |
|
2801 | 2799 | for transformer in self.ast_transformers: |
|
2802 | 2800 | try: |
|
2803 | 2801 | node = transformer.visit(node) |
|
2804 | 2802 | except InputRejected: |
|
2805 | 2803 | # User-supplied AST transformers can reject an input by raising |
|
2806 | 2804 | # an InputRejected. Short-circuit in this case so that we |
|
2807 | 2805 | # don't unregister the transform. |
|
2808 | 2806 | raise |
|
2809 | 2807 | except Exception: |
|
2810 | 2808 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2811 | 2809 | self.ast_transformers.remove(transformer) |
|
2812 | 2810 | |
|
2813 | 2811 | if self.ast_transformers: |
|
2814 | 2812 | ast.fix_missing_locations(node) |
|
2815 | 2813 | return node |
|
2816 | 2814 | |
|
2817 | 2815 | |
|
2818 | 2816 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr', |
|
2819 | 2817 | compiler=compile, result=None): |
|
2820 | 2818 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2821 | 2819 | interactivity parameter. |
|
2822 | 2820 | |
|
2823 | 2821 | Parameters |
|
2824 | 2822 | ---------- |
|
2825 | 2823 | nodelist : list |
|
2826 | 2824 | A sequence of AST nodes to run. |
|
2827 | 2825 | cell_name : str |
|
2828 | 2826 | Will be passed to the compiler as the filename of the cell. Typically |
|
2829 | 2827 | the value returned by ip.compile.cache(cell). |
|
2830 | 2828 | interactivity : str |
|
2831 | 2829 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2832 | 2830 | run interactively (displaying output from expressions). 'last_expr' |
|
2833 | 2831 | will run the last node interactively only if it is an expression (i.e. |
|
2834 | 2832 | expressions in loops or other blocks are not displayed. Other values |
|
2835 | 2833 | for this parameter will raise a ValueError. |
|
2836 | 2834 | compiler : callable |
|
2837 | 2835 | A function with the same interface as the built-in compile(), to turn |
|
2838 | 2836 | the AST nodes into code objects. Default is the built-in compile(). |
|
2839 | 2837 | result : ExecutionResult, optional |
|
2840 | 2838 | An object to store exceptions that occur during execution. |
|
2841 | 2839 | |
|
2842 | 2840 | Returns |
|
2843 | 2841 | ------- |
|
2844 | 2842 | True if an exception occurred while running code, False if it finished |
|
2845 | 2843 | running. |
|
2846 | 2844 | """ |
|
2847 | 2845 | if not nodelist: |
|
2848 | 2846 | return |
|
2849 | 2847 | |
|
2850 | 2848 | if interactivity == 'last_expr': |
|
2851 | 2849 | if isinstance(nodelist[-1], ast.Expr): |
|
2852 | 2850 | interactivity = "last" |
|
2853 | 2851 | else: |
|
2854 | 2852 | interactivity = "none" |
|
2855 | 2853 | |
|
2856 | 2854 | if interactivity == 'none': |
|
2857 | 2855 | to_run_exec, to_run_interactive = nodelist, [] |
|
2858 | 2856 | elif interactivity == 'last': |
|
2859 | 2857 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2860 | 2858 | elif interactivity == 'all': |
|
2861 | 2859 | to_run_exec, to_run_interactive = [], nodelist |
|
2862 | 2860 | else: |
|
2863 | 2861 | raise ValueError("Interactivity was %r" % interactivity) |
|
2864 | 2862 | |
|
2865 | 2863 | try: |
|
2866 | 2864 | for i, node in enumerate(to_run_exec): |
|
2867 | 2865 | mod = ast.Module([node]) |
|
2868 | 2866 | code = compiler(mod, cell_name, "exec") |
|
2869 | 2867 | if self.run_code(code, result): |
|
2870 | 2868 | return True |
|
2871 | 2869 | |
|
2872 | 2870 | for i, node in enumerate(to_run_interactive): |
|
2873 | 2871 | mod = ast.Interactive([node]) |
|
2874 | 2872 | code = compiler(mod, cell_name, "single") |
|
2875 | 2873 | if self.run_code(code, result): |
|
2876 | 2874 | return True |
|
2877 | 2875 | |
|
2878 | 2876 | # Flush softspace |
|
2879 | 2877 | if softspace(sys.stdout, 0): |
|
2880 | 2878 | print() |
|
2881 | 2879 | |
|
2882 | 2880 | except: |
|
2883 | 2881 | # It's possible to have exceptions raised here, typically by |
|
2884 | 2882 | # compilation of odd code (such as a naked 'return' outside a |
|
2885 | 2883 | # function) that did parse but isn't valid. Typically the exception |
|
2886 | 2884 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2887 | 2885 | # the user a traceback. |
|
2888 | 2886 | |
|
2889 | 2887 | # We do only one try/except outside the loop to minimize the impact |
|
2890 | 2888 | # on runtime, and also because if any node in the node list is |
|
2891 | 2889 | # broken, we should stop execution completely. |
|
2892 | 2890 | if result: |
|
2893 | 2891 | result.error_before_exec = sys.exc_info()[1] |
|
2894 | 2892 | self.showtraceback() |
|
2895 | 2893 | return True |
|
2896 | 2894 | |
|
2897 | 2895 | return False |
|
2898 | 2896 | |
|
2899 | 2897 | def run_code(self, code_obj, result=None): |
|
2900 | 2898 | """Execute a code object. |
|
2901 | 2899 | |
|
2902 | 2900 | When an exception occurs, self.showtraceback() is called to display a |
|
2903 | 2901 | traceback. |
|
2904 | 2902 | |
|
2905 | 2903 | Parameters |
|
2906 | 2904 | ---------- |
|
2907 | 2905 | code_obj : code object |
|
2908 | 2906 | A compiled code object, to be executed |
|
2909 | 2907 | result : ExecutionResult, optional |
|
2910 | 2908 | An object to store exceptions that occur during execution. |
|
2911 | 2909 | |
|
2912 | 2910 | Returns |
|
2913 | 2911 | ------- |
|
2914 | 2912 | False : successful execution. |
|
2915 | 2913 | True : an error occurred. |
|
2916 | 2914 | """ |
|
2917 | 2915 | # Set our own excepthook in case the user code tries to call it |
|
2918 | 2916 | # directly, so that the IPython crash handler doesn't get triggered |
|
2919 | 2917 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
2920 | 2918 | |
|
2921 | 2919 | # we save the original sys.excepthook in the instance, in case config |
|
2922 | 2920 | # code (such as magics) needs access to it. |
|
2923 | 2921 | self.sys_excepthook = old_excepthook |
|
2924 | 2922 | outflag = 1 # happens in more places, so it's easier as default |
|
2925 | 2923 | try: |
|
2926 | 2924 | try: |
|
2927 | 2925 | self.hooks.pre_run_code_hook() |
|
2928 | 2926 | #rprint('Running code', repr(code_obj)) # dbg |
|
2929 | 2927 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
2930 | 2928 | finally: |
|
2931 | 2929 | # Reset our crash handler in place |
|
2932 | 2930 | sys.excepthook = old_excepthook |
|
2933 | 2931 | except SystemExit as e: |
|
2934 | 2932 | if result is not None: |
|
2935 | 2933 | result.error_in_exec = e |
|
2936 | 2934 | self.showtraceback(exception_only=True) |
|
2937 | 2935 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2938 | 2936 | except self.custom_exceptions: |
|
2939 | 2937 | etype, value, tb = sys.exc_info() |
|
2940 | 2938 | if result is not None: |
|
2941 | 2939 | result.error_in_exec = value |
|
2942 | 2940 | self.CustomTB(etype, value, tb) |
|
2943 | 2941 | except: |
|
2944 | 2942 | if result is not None: |
|
2945 | 2943 | result.error_in_exec = sys.exc_info()[1] |
|
2946 | 2944 | self.showtraceback() |
|
2947 | 2945 | else: |
|
2948 | 2946 | outflag = 0 |
|
2949 | 2947 | return outflag |
|
2950 | 2948 | |
|
2951 | 2949 | # For backwards compatibility |
|
2952 | 2950 | runcode = run_code |
|
2953 | 2951 | |
|
2954 | 2952 | #------------------------------------------------------------------------- |
|
2955 | 2953 | # Things related to GUI support and pylab |
|
2956 | 2954 | #------------------------------------------------------------------------- |
|
2957 | 2955 | |
|
2958 | 2956 | def enable_gui(self, gui=None): |
|
2959 | 2957 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
2960 | 2958 | |
|
2961 | 2959 | def enable_matplotlib(self, gui=None): |
|
2962 | 2960 | """Enable interactive matplotlib and inline figure support. |
|
2963 | 2961 | |
|
2964 | 2962 | This takes the following steps: |
|
2965 | 2963 | |
|
2966 | 2964 | 1. select the appropriate eventloop and matplotlib backend |
|
2967 | 2965 | 2. set up matplotlib for interactive use with that backend |
|
2968 | 2966 | 3. configure formatters for inline figure display |
|
2969 | 2967 | 4. enable the selected gui eventloop |
|
2970 | 2968 | |
|
2971 | 2969 | Parameters |
|
2972 | 2970 | ---------- |
|
2973 | 2971 | gui : optional, string |
|
2974 | 2972 | If given, dictates the choice of matplotlib GUI backend to use |
|
2975 | 2973 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
2976 | 2974 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
2977 | 2975 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
2978 | 2976 | user's matplotlibrc configuration file). Note that not all backends |
|
2979 | 2977 | make sense in all contexts, for example a terminal ipython can't |
|
2980 | 2978 | display figures inline. |
|
2981 | 2979 | """ |
|
2982 | 2980 | from IPython.core import pylabtools as pt |
|
2983 | 2981 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
2984 | 2982 | |
|
2985 | 2983 | if gui != 'inline': |
|
2986 | 2984 | # If we have our first gui selection, store it |
|
2987 | 2985 | if self.pylab_gui_select is None: |
|
2988 | 2986 | self.pylab_gui_select = gui |
|
2989 | 2987 | # Otherwise if they are different |
|
2990 | 2988 | elif gui != self.pylab_gui_select: |
|
2991 | 2989 | print ('Warning: Cannot change to a different GUI toolkit: %s.' |
|
2992 | 2990 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
2993 | 2991 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
2994 | 2992 | |
|
2995 | 2993 | pt.activate_matplotlib(backend) |
|
2996 | 2994 | pt.configure_inline_support(self, backend) |
|
2997 | 2995 | |
|
2998 | 2996 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
2999 | 2997 | # plot updates into account |
|
3000 | 2998 | self.enable_gui(gui) |
|
3001 | 2999 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
3002 | 3000 | pt.mpl_runner(self.safe_execfile) |
|
3003 | 3001 | |
|
3004 | 3002 | return gui, backend |
|
3005 | 3003 | |
|
3006 | 3004 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
3007 | 3005 | """Activate pylab support at runtime. |
|
3008 | 3006 | |
|
3009 | 3007 | This turns on support for matplotlib, preloads into the interactive |
|
3010 | 3008 | namespace all of numpy and pylab, and configures IPython to correctly |
|
3011 | 3009 | interact with the GUI event loop. The GUI backend to be used can be |
|
3012 | 3010 | optionally selected with the optional ``gui`` argument. |
|
3013 | 3011 | |
|
3014 | 3012 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
3015 | 3013 | |
|
3016 | 3014 | Parameters |
|
3017 | 3015 | ---------- |
|
3018 | 3016 | gui : optional, string |
|
3019 | 3017 | If given, dictates the choice of matplotlib GUI backend to use |
|
3020 | 3018 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3021 | 3019 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3022 | 3020 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3023 | 3021 | user's matplotlibrc configuration file). Note that not all backends |
|
3024 | 3022 | make sense in all contexts, for example a terminal ipython can't |
|
3025 | 3023 | display figures inline. |
|
3026 | 3024 | import_all : optional, bool, default: True |
|
3027 | 3025 | Whether to do `from numpy import *` and `from pylab import *` |
|
3028 | 3026 | in addition to module imports. |
|
3029 | 3027 | welcome_message : deprecated |
|
3030 | 3028 | This argument is ignored, no welcome message will be displayed. |
|
3031 | 3029 | """ |
|
3032 | 3030 | from IPython.core.pylabtools import import_pylab |
|
3033 | 3031 | |
|
3034 | 3032 | gui, backend = self.enable_matplotlib(gui) |
|
3035 | 3033 | |
|
3036 | 3034 | # We want to prevent the loading of pylab to pollute the user's |
|
3037 | 3035 | # namespace as shown by the %who* magics, so we execute the activation |
|
3038 | 3036 | # code in an empty namespace, and we update *both* user_ns and |
|
3039 | 3037 | # user_ns_hidden with this information. |
|
3040 | 3038 | ns = {} |
|
3041 | 3039 | import_pylab(ns, import_all) |
|
3042 | 3040 | # warn about clobbered names |
|
3043 | 3041 | ignored = {"__builtins__"} |
|
3044 | 3042 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
3045 | 3043 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
3046 | 3044 | self.user_ns.update(ns) |
|
3047 | 3045 | self.user_ns_hidden.update(ns) |
|
3048 | 3046 | return gui, backend, clobbered |
|
3049 | 3047 | |
|
3050 | 3048 | #------------------------------------------------------------------------- |
|
3051 | 3049 | # Utilities |
|
3052 | 3050 | #------------------------------------------------------------------------- |
|
3053 | 3051 | |
|
3054 | 3052 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
3055 | 3053 | """Expand python variables in a string. |
|
3056 | 3054 | |
|
3057 | 3055 | The depth argument indicates how many frames above the caller should |
|
3058 | 3056 | be walked to look for the local namespace where to expand variables. |
|
3059 | 3057 | |
|
3060 | 3058 | The global namespace for expansion is always the user's interactive |
|
3061 | 3059 | namespace. |
|
3062 | 3060 | """ |
|
3063 | 3061 | ns = self.user_ns.copy() |
|
3064 | 3062 | try: |
|
3065 | 3063 | frame = sys._getframe(depth+1) |
|
3066 | 3064 | except ValueError: |
|
3067 | 3065 | # This is thrown if there aren't that many frames on the stack, |
|
3068 | 3066 | # e.g. if a script called run_line_magic() directly. |
|
3069 | 3067 | pass |
|
3070 | 3068 | else: |
|
3071 | 3069 | ns.update(frame.f_locals) |
|
3072 | 3070 | |
|
3073 | 3071 | try: |
|
3074 | 3072 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3075 | 3073 | # name, and expanding **ns for .format() would make it collide with |
|
3076 | 3074 | # the 'self' argument of the method. |
|
3077 | 3075 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3078 | 3076 | except Exception: |
|
3079 | 3077 | # if formatter couldn't format, just let it go untransformed |
|
3080 | 3078 | pass |
|
3081 | 3079 | return cmd |
|
3082 | 3080 | |
|
3083 | 3081 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3084 | 3082 | """Make a new tempfile and return its filename. |
|
3085 | 3083 | |
|
3086 | 3084 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3087 | 3085 | but it registers the created filename internally so ipython cleans it up |
|
3088 | 3086 | at exit time. |
|
3089 | 3087 | |
|
3090 | 3088 | Optional inputs: |
|
3091 | 3089 | |
|
3092 | 3090 | - data(None): if data is given, it gets written out to the temp file |
|
3093 | 3091 | immediately, and the file is closed again.""" |
|
3094 | 3092 | |
|
3095 | 3093 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3096 | 3094 | self.tempdirs.append(dirname) |
|
3097 | 3095 | |
|
3098 | 3096 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3099 | 3097 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3100 | 3098 | self.tempfiles.append(filename) |
|
3101 | 3099 | |
|
3102 | 3100 | if data: |
|
3103 | 3101 | tmp_file = open(filename,'w') |
|
3104 | 3102 | tmp_file.write(data) |
|
3105 | 3103 | tmp_file.close() |
|
3106 | 3104 | return filename |
|
3107 | 3105 | |
|
3108 | 3106 | @undoc |
|
3109 | 3107 | def write(self,data): |
|
3110 | 3108 | """DEPRECATED: Write a string to the default output""" |
|
3111 | 3109 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3112 | 3110 | DeprecationWarning, stacklevel=2) |
|
3113 | 3111 | sys.stdout.write(data) |
|
3114 | 3112 | |
|
3115 | 3113 | @undoc |
|
3116 | 3114 | def write_err(self,data): |
|
3117 | 3115 | """DEPRECATED: Write a string to the default error output""" |
|
3118 | 3116 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3119 | 3117 | DeprecationWarning, stacklevel=2) |
|
3120 | 3118 | sys.stderr.write(data) |
|
3121 | 3119 | |
|
3122 | 3120 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3123 | 3121 | if self.quiet: |
|
3124 | 3122 | return True |
|
3125 | 3123 | return ask_yes_no(prompt,default,interrupt) |
|
3126 | 3124 | |
|
3127 | 3125 | def show_usage(self): |
|
3128 | 3126 | """Show a usage message""" |
|
3129 | 3127 | page.page(IPython.core.usage.interactive_usage) |
|
3130 | 3128 | |
|
3131 | 3129 | def extract_input_lines(self, range_str, raw=False): |
|
3132 | 3130 | """Return as a string a set of input history slices. |
|
3133 | 3131 | |
|
3134 | 3132 | Parameters |
|
3135 | 3133 | ---------- |
|
3136 | 3134 | range_str : string |
|
3137 | 3135 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3138 | 3136 | since this function is for use by magic functions which get their |
|
3139 | 3137 | arguments as strings. The number before the / is the session |
|
3140 | 3138 | number: ~n goes n back from the current session. |
|
3141 | 3139 | |
|
3142 | 3140 | raw : bool, optional |
|
3143 | 3141 | By default, the processed input is used. If this is true, the raw |
|
3144 | 3142 | input history is used instead. |
|
3145 | 3143 | |
|
3146 | 3144 | Notes |
|
3147 | 3145 | ----- |
|
3148 | 3146 | |
|
3149 | 3147 | Slices can be described with two notations: |
|
3150 | 3148 | |
|
3151 | 3149 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3152 | 3150 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3153 | 3151 | """ |
|
3154 | 3152 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3155 | 3153 | return "\n".join(x for _, _, x in lines) |
|
3156 | 3154 | |
|
3157 | 3155 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3158 | 3156 | """Get a code string from history, file, url, or a string or macro. |
|
3159 | 3157 | |
|
3160 | 3158 | This is mainly used by magic functions. |
|
3161 | 3159 | |
|
3162 | 3160 | Parameters |
|
3163 | 3161 | ---------- |
|
3164 | 3162 | |
|
3165 | 3163 | target : str |
|
3166 | 3164 | |
|
3167 | 3165 | A string specifying code to retrieve. This will be tried respectively |
|
3168 | 3166 | as: ranges of input history (see %history for syntax), url, |
|
3169 | 3167 | corresponding .py file, filename, or an expression evaluating to a |
|
3170 | 3168 | string or Macro in the user namespace. |
|
3171 | 3169 | |
|
3172 | 3170 | raw : bool |
|
3173 | 3171 | If true (default), retrieve raw history. Has no effect on the other |
|
3174 | 3172 | retrieval mechanisms. |
|
3175 | 3173 | |
|
3176 | 3174 | py_only : bool (default False) |
|
3177 | 3175 | Only try to fetch python code, do not try alternative methods to decode file |
|
3178 | 3176 | if unicode fails. |
|
3179 | 3177 | |
|
3180 | 3178 | Returns |
|
3181 | 3179 | ------- |
|
3182 | 3180 | A string of code. |
|
3183 | 3181 | |
|
3184 | 3182 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3185 | 3183 | to an object of another type. In each case, .args[0] is a printable |
|
3186 | 3184 | message. |
|
3187 | 3185 | """ |
|
3188 | 3186 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3189 | 3187 | if code: |
|
3190 | 3188 | return code |
|
3191 | 3189 | try: |
|
3192 | 3190 | if target.startswith(('http://', 'https://')): |
|
3193 | 3191 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
|
3194 | 3192 | except UnicodeDecodeError: |
|
3195 | 3193 | if not py_only : |
|
3196 | 3194 | # Deferred import |
|
3197 | 3195 | try: |
|
3198 | 3196 | from urllib.request import urlopen # Py3 |
|
3199 | 3197 | except ImportError: |
|
3200 | 3198 | from urllib import urlopen |
|
3201 | 3199 | response = urlopen(target) |
|
3202 | 3200 | return response.read().decode('latin1') |
|
3203 | 3201 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3204 | 3202 | |
|
3205 | 3203 | potential_target = [target] |
|
3206 | 3204 | try : |
|
3207 | 3205 | potential_target.insert(0,get_py_filename(target)) |
|
3208 | 3206 | except IOError: |
|
3209 | 3207 | pass |
|
3210 | 3208 | |
|
3211 | 3209 | for tgt in potential_target : |
|
3212 | 3210 | if os.path.isfile(tgt): # Read file |
|
3213 | 3211 | try : |
|
3214 | 3212 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3215 | 3213 | except UnicodeDecodeError : |
|
3216 | 3214 | if not py_only : |
|
3217 | 3215 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3218 | 3216 | return f.read() |
|
3219 | 3217 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3220 | 3218 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3221 | 3219 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3222 | 3220 | |
|
3223 | 3221 | if search_ns: |
|
3224 | 3222 | # Inspect namespace to load object source |
|
3225 | 3223 | object_info = self.object_inspect(target, detail_level=1) |
|
3226 | 3224 | if object_info['found'] and object_info['source']: |
|
3227 | 3225 | return object_info['source'] |
|
3228 | 3226 | |
|
3229 | 3227 | try: # User namespace |
|
3230 | 3228 | codeobj = eval(target, self.user_ns) |
|
3231 | 3229 | except Exception: |
|
3232 | 3230 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3233 | 3231 | "nor in the user namespace.") % target) |
|
3234 | 3232 | |
|
3235 | 3233 | if isinstance(codeobj, string_types): |
|
3236 | 3234 | return codeobj |
|
3237 | 3235 | elif isinstance(codeobj, Macro): |
|
3238 | 3236 | return codeobj.value |
|
3239 | 3237 | |
|
3240 | 3238 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3241 | 3239 | codeobj) |
|
3242 | 3240 | |
|
3243 | 3241 | #------------------------------------------------------------------------- |
|
3244 | 3242 | # Things related to IPython exiting |
|
3245 | 3243 | #------------------------------------------------------------------------- |
|
3246 | 3244 | def atexit_operations(self): |
|
3247 | 3245 | """This will be executed at the time of exit. |
|
3248 | 3246 | |
|
3249 | 3247 | Cleanup operations and saving of persistent data that is done |
|
3250 | 3248 | unconditionally by IPython should be performed here. |
|
3251 | 3249 | |
|
3252 | 3250 | For things that may depend on startup flags or platform specifics (such |
|
3253 | 3251 | as having readline or not), register a separate atexit function in the |
|
3254 | 3252 | code that has the appropriate information, rather than trying to |
|
3255 | 3253 | clutter |
|
3256 | 3254 | """ |
|
3257 | 3255 | # Close the history session (this stores the end time and line count) |
|
3258 | 3256 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3259 | 3257 | # history db |
|
3260 | 3258 | self.history_manager.end_session() |
|
3261 | 3259 | |
|
3262 | 3260 | # Cleanup all tempfiles and folders left around |
|
3263 | 3261 | for tfile in self.tempfiles: |
|
3264 | 3262 | try: |
|
3265 | 3263 | os.unlink(tfile) |
|
3266 | 3264 | except OSError: |
|
3267 | 3265 | pass |
|
3268 | 3266 | |
|
3269 | 3267 | for tdir in self.tempdirs: |
|
3270 | 3268 | try: |
|
3271 | 3269 | os.rmdir(tdir) |
|
3272 | 3270 | except OSError: |
|
3273 | 3271 | pass |
|
3274 | 3272 | |
|
3275 | 3273 | # Clear all user namespaces to release all references cleanly. |
|
3276 | 3274 | self.reset(new_session=False) |
|
3277 | 3275 | |
|
3278 | 3276 | # Run user hooks |
|
3279 | 3277 | self.hooks.shutdown_hook() |
|
3280 | 3278 | |
|
3281 | 3279 | def cleanup(self): |
|
3282 | 3280 | self.restore_sys_module_state() |
|
3283 | 3281 | |
|
3284 | 3282 | |
|
3285 | 3283 | # Overridden in terminal subclass to change prompts |
|
3286 | 3284 | def switch_doctest_mode(self, mode): |
|
3287 | 3285 | pass |
|
3288 | 3286 | |
|
3289 | 3287 | |
|
3290 | 3288 | class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)): |
|
3291 | 3289 | """An abstract base class for InteractiveShell.""" |
|
3292 | 3290 | |
|
3293 | 3291 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,599 +1,599 b'' | |||
|
1 | 1 | """Implementation of basic magic functions.""" |
|
2 | 2 | |
|
3 | 3 | from __future__ import print_function |
|
4 | 4 | from __future__ import absolute_import |
|
5 | 5 | |
|
6 | 6 | import io |
|
7 | 7 | import sys |
|
8 | 8 | from pprint import pformat |
|
9 | 9 | |
|
10 | 10 | from IPython.core import magic_arguments, page |
|
11 | 11 | from IPython.core.error import UsageError |
|
12 | 12 | from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes |
|
13 | 13 | from IPython.utils.text import format_screen, dedent, indent |
|
14 | 14 | from IPython.testing.skipdoctest import skip_doctest |
|
15 | 15 | from IPython.utils.ipstruct import Struct |
|
16 | 16 | from IPython.utils.py3compat import unicode_type |
|
17 | 17 | from warnings import warn |
|
18 | 18 | from logging import error |
|
19 | 19 | |
|
20 | 20 | |
|
21 | 21 | class MagicsDisplay(object): |
|
22 | 22 | def __init__(self, magics_manager): |
|
23 | 23 | self.magics_manager = magics_manager |
|
24 | 24 | |
|
25 | 25 | def _lsmagic(self): |
|
26 | 26 | """The main implementation of the %lsmagic""" |
|
27 | 27 | mesc = magic_escapes['line'] |
|
28 | 28 | cesc = magic_escapes['cell'] |
|
29 | 29 | mman = self.magics_manager |
|
30 | 30 | magics = mman.lsmagic() |
|
31 | 31 | out = ['Available line magics:', |
|
32 | 32 | mesc + (' '+mesc).join(sorted(magics['line'])), |
|
33 | 33 | '', |
|
34 | 34 | 'Available cell magics:', |
|
35 | 35 | cesc + (' '+cesc).join(sorted(magics['cell'])), |
|
36 | 36 | '', |
|
37 | 37 | mman.auto_status()] |
|
38 | 38 | return '\n'.join(out) |
|
39 | 39 | |
|
40 | 40 | def _repr_pretty_(self, p, cycle): |
|
41 | 41 | p.text(self._lsmagic()) |
|
42 | 42 | |
|
43 | 43 | def __str__(self): |
|
44 | 44 | return self._lsmagic() |
|
45 | 45 | |
|
46 | 46 | def _jsonable(self): |
|
47 | 47 | """turn magics dict into jsonable dict of the same structure |
|
48 | 48 | |
|
49 | 49 | replaces object instances with their class names as strings |
|
50 | 50 | """ |
|
51 | 51 | magic_dict = {} |
|
52 | 52 | mman = self.magics_manager |
|
53 | 53 | magics = mman.lsmagic() |
|
54 | 54 | for key, subdict in magics.items(): |
|
55 | 55 | d = {} |
|
56 | 56 | magic_dict[key] = d |
|
57 | 57 | for name, obj in subdict.items(): |
|
58 | 58 | try: |
|
59 | 59 | classname = obj.__self__.__class__.__name__ |
|
60 | 60 | except AttributeError: |
|
61 | 61 | classname = 'Other' |
|
62 | 62 | |
|
63 | 63 | d[name] = classname |
|
64 | 64 | return magic_dict |
|
65 | 65 | |
|
66 | 66 | def _repr_json_(self): |
|
67 | 67 | return self._jsonable() |
|
68 | 68 | |
|
69 | 69 | |
|
70 | 70 | @magics_class |
|
71 | 71 | class BasicMagics(Magics): |
|
72 | 72 | """Magics that provide central IPython functionality. |
|
73 | 73 | |
|
74 | 74 | These are various magics that don't fit into specific categories but that |
|
75 | 75 | are all part of the base 'IPython experience'.""" |
|
76 | 76 | |
|
77 | 77 | @magic_arguments.magic_arguments() |
|
78 | 78 | @magic_arguments.argument( |
|
79 | 79 | '-l', '--line', action='store_true', |
|
80 | 80 | help="""Create a line magic alias.""" |
|
81 | 81 | ) |
|
82 | 82 | @magic_arguments.argument( |
|
83 | 83 | '-c', '--cell', action='store_true', |
|
84 | 84 | help="""Create a cell magic alias.""" |
|
85 | 85 | ) |
|
86 | 86 | @magic_arguments.argument( |
|
87 | 87 | 'name', |
|
88 | 88 | help="""Name of the magic to be created.""" |
|
89 | 89 | ) |
|
90 | 90 | @magic_arguments.argument( |
|
91 | 91 | 'target', |
|
92 | 92 | help="""Name of the existing line or cell magic.""" |
|
93 | 93 | ) |
|
94 | 94 | @line_magic |
|
95 | 95 | def alias_magic(self, line=''): |
|
96 | 96 | """Create an alias for an existing line or cell magic. |
|
97 | 97 | |
|
98 | 98 | Examples |
|
99 | 99 | -------- |
|
100 | 100 | :: |
|
101 | 101 | |
|
102 | 102 | In [1]: %alias_magic t timeit |
|
103 | 103 | Created `%t` as an alias for `%timeit`. |
|
104 | 104 | Created `%%t` as an alias for `%%timeit`. |
|
105 | 105 | |
|
106 | 106 | In [2]: %t -n1 pass |
|
107 | 107 | 1 loops, best of 3: 954 ns per loop |
|
108 | 108 | |
|
109 | 109 | In [3]: %%t -n1 |
|
110 | 110 | ...: pass |
|
111 | 111 | ...: |
|
112 | 112 | 1 loops, best of 3: 954 ns per loop |
|
113 | 113 | |
|
114 | 114 | In [4]: %alias_magic --cell whereami pwd |
|
115 | 115 | UsageError: Cell magic function `%%pwd` not found. |
|
116 | 116 | In [5]: %alias_magic --line whereami pwd |
|
117 | 117 | Created `%whereami` as an alias for `%pwd`. |
|
118 | 118 | |
|
119 | 119 | In [6]: %whereami |
|
120 | 120 | Out[6]: u'/home/testuser' |
|
121 | 121 | """ |
|
122 | 122 | args = magic_arguments.parse_argstring(self.alias_magic, line) |
|
123 | 123 | shell = self.shell |
|
124 | 124 | mman = self.shell.magics_manager |
|
125 | 125 | escs = ''.join(magic_escapes.values()) |
|
126 | 126 | |
|
127 | 127 | target = args.target.lstrip(escs) |
|
128 | 128 | name = args.name.lstrip(escs) |
|
129 | 129 | |
|
130 | 130 | # Find the requested magics. |
|
131 | 131 | m_line = shell.find_magic(target, 'line') |
|
132 | 132 | m_cell = shell.find_magic(target, 'cell') |
|
133 | 133 | if args.line and m_line is None: |
|
134 | 134 | raise UsageError('Line magic function `%s%s` not found.' % |
|
135 | 135 | (magic_escapes['line'], target)) |
|
136 | 136 | if args.cell and m_cell is None: |
|
137 | 137 | raise UsageError('Cell magic function `%s%s` not found.' % |
|
138 | 138 | (magic_escapes['cell'], target)) |
|
139 | 139 | |
|
140 | 140 | # If --line and --cell are not specified, default to the ones |
|
141 | 141 | # that are available. |
|
142 | 142 | if not args.line and not args.cell: |
|
143 | 143 | if not m_line and not m_cell: |
|
144 | 144 | raise UsageError( |
|
145 | 145 | 'No line or cell magic with name `%s` found.' % target |
|
146 | 146 | ) |
|
147 | 147 | args.line = bool(m_line) |
|
148 | 148 | args.cell = bool(m_cell) |
|
149 | 149 | |
|
150 | 150 | if args.line: |
|
151 | 151 | mman.register_alias(name, target, 'line') |
|
152 | 152 | print('Created `%s%s` as an alias for `%s%s`.' % ( |
|
153 | 153 | magic_escapes['line'], name, |
|
154 | 154 | magic_escapes['line'], target)) |
|
155 | 155 | |
|
156 | 156 | if args.cell: |
|
157 | 157 | mman.register_alias(name, target, 'cell') |
|
158 | 158 | print('Created `%s%s` as an alias for `%s%s`.' % ( |
|
159 | 159 | magic_escapes['cell'], name, |
|
160 | 160 | magic_escapes['cell'], target)) |
|
161 | 161 | |
|
162 | 162 | @line_magic |
|
163 | 163 | def lsmagic(self, parameter_s=''): |
|
164 | 164 | """List currently available magic functions.""" |
|
165 | 165 | return MagicsDisplay(self.shell.magics_manager) |
|
166 | 166 | |
|
167 | 167 | def _magic_docs(self, brief=False, rest=False): |
|
168 | 168 | """Return docstrings from magic functions.""" |
|
169 | 169 | mman = self.shell.magics_manager |
|
170 | 170 | docs = mman.lsmagic_docs(brief, missing='No documentation') |
|
171 | 171 | |
|
172 | 172 | if rest: |
|
173 | 173 | format_string = '**%s%s**::\n\n%s\n\n' |
|
174 | 174 | else: |
|
175 | 175 | format_string = '%s%s:\n%s\n' |
|
176 | 176 | |
|
177 | 177 | return ''.join( |
|
178 | 178 | [format_string % (magic_escapes['line'], fname, |
|
179 | 179 | indent(dedent(fndoc))) |
|
180 | 180 | for fname, fndoc in sorted(docs['line'].items())] |
|
181 | 181 | + |
|
182 | 182 | [format_string % (magic_escapes['cell'], fname, |
|
183 | 183 | indent(dedent(fndoc))) |
|
184 | 184 | for fname, fndoc in sorted(docs['cell'].items())] |
|
185 | 185 | ) |
|
186 | 186 | |
|
187 | 187 | @line_magic |
|
188 | 188 | def magic(self, parameter_s=''): |
|
189 | 189 | """Print information about the magic function system. |
|
190 | 190 | |
|
191 | 191 | Supported formats: -latex, -brief, -rest |
|
192 | 192 | """ |
|
193 | 193 | |
|
194 | 194 | mode = '' |
|
195 | 195 | try: |
|
196 | 196 | mode = parameter_s.split()[0][1:] |
|
197 | 197 | except IndexError: |
|
198 | 198 | pass |
|
199 | 199 | |
|
200 | 200 | brief = (mode == 'brief') |
|
201 | 201 | rest = (mode == 'rest') |
|
202 | 202 | magic_docs = self._magic_docs(brief, rest) |
|
203 | 203 | |
|
204 | 204 | if mode == 'latex': |
|
205 | 205 | print(self.format_latex(magic_docs)) |
|
206 | 206 | return |
|
207 | 207 | else: |
|
208 | 208 | magic_docs = format_screen(magic_docs) |
|
209 | 209 | |
|
210 | 210 | out = [""" |
|
211 | 211 | IPython's 'magic' functions |
|
212 | 212 | =========================== |
|
213 | 213 | |
|
214 | 214 | The magic function system provides a series of functions which allow you to |
|
215 | 215 | control the behavior of IPython itself, plus a lot of system-type |
|
216 | 216 | features. There are two kinds of magics, line-oriented and cell-oriented. |
|
217 | 217 | |
|
218 | 218 | Line magics are prefixed with the % character and work much like OS |
|
219 | 219 | command-line calls: they get as an argument the rest of the line, where |
|
220 | 220 | arguments are passed without parentheses or quotes. For example, this will |
|
221 | 221 | time the given statement:: |
|
222 | 222 | |
|
223 | 223 | %timeit range(1000) |
|
224 | 224 | |
|
225 | 225 | Cell magics are prefixed with a double %%, and they are functions that get as |
|
226 | 226 | an argument not only the rest of the line, but also the lines below it in a |
|
227 | 227 | separate argument. These magics are called with two arguments: the rest of the |
|
228 | 228 | call line and the body of the cell, consisting of the lines below the first. |
|
229 | 229 | For example:: |
|
230 | 230 | |
|
231 | 231 | %%timeit x = numpy.random.randn((100, 100)) |
|
232 | 232 | numpy.linalg.svd(x) |
|
233 | 233 | |
|
234 | 234 | will time the execution of the numpy svd routine, running the assignment of x |
|
235 | 235 | as part of the setup phase, which is not timed. |
|
236 | 236 | |
|
237 | 237 | In a line-oriented client (the terminal or Qt console IPython), starting a new |
|
238 | 238 | input with %% will automatically enter cell mode, and IPython will continue |
|
239 | 239 | reading input until a blank line is given. In the notebook, simply type the |
|
240 | 240 | whole cell as one entity, but keep in mind that the %% escape can only be at |
|
241 | 241 | the very start of the cell. |
|
242 | 242 | |
|
243 | 243 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
244 | 244 | %automagic function), you don't need to type in the % explicitly for line |
|
245 | 245 | magics; cell magics always require an explicit '%%' escape. By default, |
|
246 | 246 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
247 | 247 | |
|
248 | 248 | Example: typing '%cd mydir' (without the quotes) changes your working directory |
|
249 | 249 | to 'mydir', if it exists. |
|
250 | 250 | |
|
251 | 251 | For a list of the available magic functions, use %lsmagic. For a description |
|
252 | 252 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
253 | 253 | |
|
254 | 254 | Currently the magic system has the following functions:""", |
|
255 | 255 | magic_docs, |
|
256 | 256 | "Summary of magic functions (from %slsmagic):" % magic_escapes['line'], |
|
257 | 257 | str(self.lsmagic()), |
|
258 | 258 | ] |
|
259 | 259 | page.page('\n'.join(out)) |
|
260 | 260 | |
|
261 | 261 | |
|
262 | 262 | @line_magic |
|
263 | 263 | def page(self, parameter_s=''): |
|
264 | 264 | """Pretty print the object and display it through a pager. |
|
265 | 265 | |
|
266 | 266 | %page [options] OBJECT |
|
267 | 267 | |
|
268 | 268 | If no object is given, use _ (last output). |
|
269 | 269 | |
|
270 | 270 | Options: |
|
271 | 271 | |
|
272 | 272 | -r: page str(object), don't pretty-print it.""" |
|
273 | 273 | |
|
274 | 274 | # After a function contributed by Olivier Aubert, slightly modified. |
|
275 | 275 | |
|
276 | 276 | # Process options/args |
|
277 | 277 | opts, args = self.parse_options(parameter_s, 'r') |
|
278 | 278 | raw = 'r' in opts |
|
279 | 279 | |
|
280 | 280 | oname = args and args or '_' |
|
281 | 281 | info = self.shell._ofind(oname) |
|
282 | 282 | if info['found']: |
|
283 | 283 | txt = (raw and str or pformat)( info['obj'] ) |
|
284 | 284 | page.page(txt) |
|
285 | 285 | else: |
|
286 | 286 | print('Object `%s` not found' % oname) |
|
287 | 287 | |
|
288 | 288 | @line_magic |
|
289 | 289 | def profile(self, parameter_s=''): |
|
290 | 290 | """Print your currently active IPython profile. |
|
291 | 291 | |
|
292 | 292 | See Also |
|
293 | 293 | -------- |
|
294 | 294 | prun : run code using the Python profiler |
|
295 | 295 | (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`) |
|
296 | 296 | """ |
|
297 | 297 | warn("%profile is now deprecated. Please use get_ipython().profile instead.") |
|
298 | 298 | from IPython.core.application import BaseIPythonApplication |
|
299 | 299 | if BaseIPythonApplication.initialized(): |
|
300 | 300 | print(BaseIPythonApplication.instance().profile) |
|
301 | 301 | else: |
|
302 | 302 | error("profile is an application-level value, but you don't appear to be in an IPython application") |
|
303 | 303 | |
|
304 | 304 | @line_magic |
|
305 | 305 | def pprint(self, parameter_s=''): |
|
306 | 306 | """Toggle pretty printing on/off.""" |
|
307 | 307 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
308 | 308 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
309 | 309 | print('Pretty printing has been turned', |
|
310 | 310 | ['OFF','ON'][ptformatter.pprint]) |
|
311 | 311 | |
|
312 | 312 | @line_magic |
|
313 | 313 | def colors(self, parameter_s=''): |
|
314 | 314 | """Switch color scheme for prompts, info system and exception handlers. |
|
315 | 315 | |
|
316 | 316 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
317 | 317 | |
|
318 | 318 | Color scheme names are not case-sensitive. |
|
319 | 319 | |
|
320 | 320 | Examples |
|
321 | 321 | -------- |
|
322 | 322 | To get a plain black and white terminal:: |
|
323 | 323 | |
|
324 | 324 | %colors nocolor |
|
325 | 325 | """ |
|
326 | 326 | def color_switch_err(name): |
|
327 | 327 | warn('Error changing %s color schemes.\n%s' % |
|
328 | (name, sys.exc_info()[1])) | |
|
328 | (name, sys.exc_info()[1]), stacklevel=2) | |
|
329 | 329 | |
|
330 | 330 | |
|
331 | 331 | new_scheme = parameter_s.strip() |
|
332 | 332 | if not new_scheme: |
|
333 | 333 | raise UsageError( |
|
334 | 334 | "%colors: you must specify a color scheme. See '%colors?'") |
|
335 | 335 | # local shortcut |
|
336 | 336 | shell = self.shell |
|
337 | 337 | |
|
338 | 338 | |
|
339 | 339 | |
|
340 | 340 | if not shell.colors_force: |
|
341 | 341 | if sys.platform in {'win32', 'cli'}: |
|
342 | 342 | import IPython.utils.rlineimpl as readline |
|
343 | 343 | if not readline.have_readline: |
|
344 | 344 | msg = """\ |
|
345 | 345 | Proper color support under MS Windows requires the pyreadline library. |
|
346 | 346 | You can find it at: |
|
347 | 347 | http://ipython.org/pyreadline.html |
|
348 | 348 | |
|
349 | 349 | Defaulting color scheme to 'NoColor'""" |
|
350 | 350 | new_scheme = 'NoColor' |
|
351 | 351 | warn(msg) |
|
352 | 352 | |
|
353 | 353 | elif not shell.has_readline: |
|
354 | 354 | # Coloured prompts get messed up without readline |
|
355 | 355 | # Will remove this check after switching to prompt_toolkit |
|
356 | 356 | new_scheme = 'NoColor' |
|
357 | 357 | |
|
358 | 358 | # Set exception colors |
|
359 | 359 | try: |
|
360 | 360 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
361 | 361 | shell.colors = new_scheme |
|
362 | 362 | shell.refresh_style() |
|
363 | 363 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
364 | 364 | except: |
|
365 | 365 | color_switch_err('exception') |
|
366 | 366 | |
|
367 | 367 | # Set info (for 'object?') colors |
|
368 | 368 | if shell.color_info: |
|
369 | 369 | try: |
|
370 | 370 | shell.inspector.set_active_scheme(new_scheme) |
|
371 | 371 | except: |
|
372 | 372 | color_switch_err('object inspector') |
|
373 | 373 | else: |
|
374 | 374 | shell.inspector.set_active_scheme('NoColor') |
|
375 | 375 | |
|
376 | 376 | @line_magic |
|
377 | 377 | def xmode(self, parameter_s=''): |
|
378 | 378 | """Switch modes for the exception handlers. |
|
379 | 379 | |
|
380 | 380 | Valid modes: Plain, Context and Verbose. |
|
381 | 381 | |
|
382 | 382 | If called without arguments, acts as a toggle.""" |
|
383 | 383 | |
|
384 | 384 | def xmode_switch_err(name): |
|
385 | 385 | warn('Error changing %s exception modes.\n%s' % |
|
386 | 386 | (name,sys.exc_info()[1])) |
|
387 | 387 | |
|
388 | 388 | shell = self.shell |
|
389 | 389 | new_mode = parameter_s.strip().capitalize() |
|
390 | 390 | try: |
|
391 | 391 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
392 | 392 | print('Exception reporting mode:',shell.InteractiveTB.mode) |
|
393 | 393 | except: |
|
394 | 394 | xmode_switch_err('user') |
|
395 | 395 | |
|
396 | 396 | @line_magic |
|
397 | 397 | def quickref(self,arg): |
|
398 | 398 | """ Show a quick reference sheet """ |
|
399 | 399 | from IPython.core.usage import quick_reference |
|
400 | 400 | qr = quick_reference + self._magic_docs(brief=True) |
|
401 | 401 | page.page(qr) |
|
402 | 402 | |
|
403 | 403 | @line_magic |
|
404 | 404 | def doctest_mode(self, parameter_s=''): |
|
405 | 405 | """Toggle doctest mode on and off. |
|
406 | 406 | |
|
407 | 407 | This mode is intended to make IPython behave as much as possible like a |
|
408 | 408 | plain Python shell, from the perspective of how its prompts, exceptions |
|
409 | 409 | and output look. This makes it easy to copy and paste parts of a |
|
410 | 410 | session into doctests. It does so by: |
|
411 | 411 | |
|
412 | 412 | - Changing the prompts to the classic ``>>>`` ones. |
|
413 | 413 | - Changing the exception reporting mode to 'Plain'. |
|
414 | 414 | - Disabling pretty-printing of output. |
|
415 | 415 | |
|
416 | 416 | Note that IPython also supports the pasting of code snippets that have |
|
417 | 417 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
418 | 418 | doctests from files or docstrings (even if they have leading |
|
419 | 419 | whitespace), and the code will execute correctly. You can then use |
|
420 | 420 | '%history -t' to see the translated history; this will give you the |
|
421 | 421 | input after removal of all the leading prompts and whitespace, which |
|
422 | 422 | can be pasted back into an editor. |
|
423 | 423 | |
|
424 | 424 | With these features, you can switch into this mode easily whenever you |
|
425 | 425 | need to do testing and changes to doctests, without having to leave |
|
426 | 426 | your existing IPython session. |
|
427 | 427 | """ |
|
428 | 428 | |
|
429 | 429 | # Shorthands |
|
430 | 430 | shell = self.shell |
|
431 | 431 | meta = shell.meta |
|
432 | 432 | disp_formatter = self.shell.display_formatter |
|
433 | 433 | ptformatter = disp_formatter.formatters['text/plain'] |
|
434 | 434 | # dstore is a data store kept in the instance metadata bag to track any |
|
435 | 435 | # changes we make, so we can undo them later. |
|
436 | 436 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
437 | 437 | save_dstore = dstore.setdefault |
|
438 | 438 | |
|
439 | 439 | # save a few values we'll need to recover later |
|
440 | 440 | mode = save_dstore('mode',False) |
|
441 | 441 | save_dstore('rc_pprint',ptformatter.pprint) |
|
442 | 442 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
443 | 443 | save_dstore('rc_separate_out',shell.separate_out) |
|
444 | 444 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
445 | 445 | save_dstore('rc_separate_in',shell.separate_in) |
|
446 | 446 | save_dstore('rc_active_types',disp_formatter.active_types) |
|
447 | 447 | |
|
448 | 448 | if not mode: |
|
449 | 449 | # turn on |
|
450 | 450 | |
|
451 | 451 | # Prompt separators like plain python |
|
452 | 452 | shell.separate_in = '' |
|
453 | 453 | shell.separate_out = '' |
|
454 | 454 | shell.separate_out2 = '' |
|
455 | 455 | |
|
456 | 456 | |
|
457 | 457 | ptformatter.pprint = False |
|
458 | 458 | disp_formatter.active_types = ['text/plain'] |
|
459 | 459 | |
|
460 | 460 | shell.magic('xmode Plain') |
|
461 | 461 | else: |
|
462 | 462 | # turn off |
|
463 | 463 | shell.separate_in = dstore.rc_separate_in |
|
464 | 464 | |
|
465 | 465 | shell.separate_out = dstore.rc_separate_out |
|
466 | 466 | shell.separate_out2 = dstore.rc_separate_out2 |
|
467 | 467 | |
|
468 | 468 | ptformatter.pprint = dstore.rc_pprint |
|
469 | 469 | disp_formatter.active_types = dstore.rc_active_types |
|
470 | 470 | |
|
471 | 471 | shell.magic('xmode ' + dstore.xmode) |
|
472 | 472 | |
|
473 | 473 | # mode here is the state before we switch; switch_doctest_mode takes |
|
474 | 474 | # the mode we're switching to. |
|
475 | 475 | shell.switch_doctest_mode(not mode) |
|
476 | 476 | |
|
477 | 477 | # Store new mode and inform |
|
478 | 478 | dstore.mode = bool(not mode) |
|
479 | 479 | mode_label = ['OFF','ON'][dstore.mode] |
|
480 | 480 | print('Doctest mode is:', mode_label) |
|
481 | 481 | |
|
482 | 482 | @line_magic |
|
483 | 483 | def gui(self, parameter_s=''): |
|
484 | 484 | """Enable or disable IPython GUI event loop integration. |
|
485 | 485 | |
|
486 | 486 | %gui [GUINAME] |
|
487 | 487 | |
|
488 | 488 | This magic replaces IPython's threaded shells that were activated |
|
489 | 489 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
490 | 490 | can now be enabled at runtime and keyboard |
|
491 | 491 | interrupts should work without any problems. The following toolkits |
|
492 | 492 | are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX):: |
|
493 | 493 | |
|
494 | 494 | %gui wx # enable wxPython event loop integration |
|
495 | 495 | %gui qt4|qt # enable PyQt4 event loop integration |
|
496 | 496 | %gui qt5 # enable PyQt5 event loop integration |
|
497 | 497 | %gui gtk # enable PyGTK event loop integration |
|
498 | 498 | %gui gtk3 # enable Gtk3 event loop integration |
|
499 | 499 | %gui tk # enable Tk event loop integration |
|
500 | 500 | %gui osx # enable Cocoa event loop integration |
|
501 | 501 | # (requires %matplotlib 1.1) |
|
502 | 502 | %gui # disable all event loop integration |
|
503 | 503 | |
|
504 | 504 | WARNING: after any of these has been called you can simply create |
|
505 | 505 | an application object, but DO NOT start the event loop yourself, as |
|
506 | 506 | we have already handled that. |
|
507 | 507 | """ |
|
508 | 508 | opts, arg = self.parse_options(parameter_s, '') |
|
509 | 509 | if arg=='': arg = None |
|
510 | 510 | try: |
|
511 | 511 | return self.shell.enable_gui(arg) |
|
512 | 512 | except Exception as e: |
|
513 | 513 | # print simple error message, rather than traceback if we can't |
|
514 | 514 | # hook up the GUI |
|
515 | 515 | error(str(e)) |
|
516 | 516 | |
|
517 | 517 | @skip_doctest |
|
518 | 518 | @line_magic |
|
519 | 519 | def precision(self, s=''): |
|
520 | 520 | """Set floating point precision for pretty printing. |
|
521 | 521 | |
|
522 | 522 | Can set either integer precision or a format string. |
|
523 | 523 | |
|
524 | 524 | If numpy has been imported and precision is an int, |
|
525 | 525 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
526 | 526 | |
|
527 | 527 | If no argument is given, defaults will be restored. |
|
528 | 528 | |
|
529 | 529 | Examples |
|
530 | 530 | -------- |
|
531 | 531 | :: |
|
532 | 532 | |
|
533 | 533 | In [1]: from math import pi |
|
534 | 534 | |
|
535 | 535 | In [2]: %precision 3 |
|
536 | 536 | Out[2]: u'%.3f' |
|
537 | 537 | |
|
538 | 538 | In [3]: pi |
|
539 | 539 | Out[3]: 3.142 |
|
540 | 540 | |
|
541 | 541 | In [4]: %precision %i |
|
542 | 542 | Out[4]: u'%i' |
|
543 | 543 | |
|
544 | 544 | In [5]: pi |
|
545 | 545 | Out[5]: 3 |
|
546 | 546 | |
|
547 | 547 | In [6]: %precision %e |
|
548 | 548 | Out[6]: u'%e' |
|
549 | 549 | |
|
550 | 550 | In [7]: pi**10 |
|
551 | 551 | Out[7]: 9.364805e+04 |
|
552 | 552 | |
|
553 | 553 | In [8]: %precision |
|
554 | 554 | Out[8]: u'%r' |
|
555 | 555 | |
|
556 | 556 | In [9]: pi**10 |
|
557 | 557 | Out[9]: 93648.047476082982 |
|
558 | 558 | """ |
|
559 | 559 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
560 | 560 | ptformatter.float_precision = s |
|
561 | 561 | return ptformatter.float_format |
|
562 | 562 | |
|
563 | 563 | @magic_arguments.magic_arguments() |
|
564 | 564 | @magic_arguments.argument( |
|
565 | 565 | '-e', '--export', action='store_true', default=False, |
|
566 | 566 | help='Export IPython history as a notebook. The filename argument ' |
|
567 | 567 | 'is used to specify the notebook name and format. For example ' |
|
568 | 568 | 'a filename of notebook.ipynb will result in a notebook name ' |
|
569 | 569 | 'of "notebook" and a format of "json". Likewise using a ".py" ' |
|
570 | 570 | 'file extension will write the notebook as a Python script' |
|
571 | 571 | ) |
|
572 | 572 | @magic_arguments.argument( |
|
573 | 573 | 'filename', type=unicode_type, |
|
574 | 574 | help='Notebook name or filename' |
|
575 | 575 | ) |
|
576 | 576 | @line_magic |
|
577 | 577 | def notebook(self, s): |
|
578 | 578 | """Export and convert IPython notebooks. |
|
579 | 579 | |
|
580 | 580 | This function can export the current IPython history to a notebook file. |
|
581 | 581 | For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb". |
|
582 | 582 | To export the history to "foo.py" do "%notebook -e foo.py". |
|
583 | 583 | """ |
|
584 | 584 | args = magic_arguments.parse_argstring(self.notebook, s) |
|
585 | 585 | |
|
586 | 586 | from nbformat import write, v4 |
|
587 | 587 | if args.export: |
|
588 | 588 | cells = [] |
|
589 | 589 | hist = list(self.shell.history_manager.get_range()) |
|
590 | 590 | if(len(hist)<=1): |
|
591 | 591 | raise ValueError('History is empty, cannot export') |
|
592 | 592 | for session, execution_count, source in hist[:-1]: |
|
593 | 593 | cells.append(v4.new_code_cell( |
|
594 | 594 | execution_count=execution_count, |
|
595 | 595 | source=source |
|
596 | 596 | )) |
|
597 | 597 | nb = v4.new_notebook(cells=cells) |
|
598 | 598 | with io.open(args.filename, 'w', encoding='utf-8') as f: |
|
599 | 599 | write(nb, f, version=4) |
@@ -1,1492 +1,1495 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Verbose and colourful traceback formatting. |
|
4 | 4 | |
|
5 | 5 | **ColorTB** |
|
6 | 6 | |
|
7 | 7 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
8 | 8 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
9 | 9 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
10 | 10 | text editor. |
|
11 | 11 | |
|
12 | 12 | Installation instructions for ColorTB:: |
|
13 | 13 | |
|
14 | 14 | import sys,ultratb |
|
15 | 15 | sys.excepthook = ultratb.ColorTB() |
|
16 | 16 | |
|
17 | 17 | **VerboseTB** |
|
18 | 18 | |
|
19 | 19 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
20 | 20 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
21 | 21 | and intended it for CGI programmers, but why should they have all the fun? I |
|
22 | 22 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
23 | 23 | but kind of neat, and maybe useful for long-running programs that you believe |
|
24 | 24 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
25 | 25 | Give it a shot--you'll love it or you'll hate it. |
|
26 | 26 | |
|
27 | 27 | .. note:: |
|
28 | 28 | |
|
29 | 29 | The Verbose mode prints the variables currently visible where the exception |
|
30 | 30 | happened (shortening their strings if too long). This can potentially be |
|
31 | 31 | very slow, if you happen to have a huge data structure whose string |
|
32 | 32 | representation is complex to compute. Your computer may appear to freeze for |
|
33 | 33 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
34 | 34 | with Ctrl-C (maybe hitting it more than once). |
|
35 | 35 | |
|
36 | 36 | If you encounter this kind of situation often, you may want to use the |
|
37 | 37 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
38 | 38 | variables (but otherwise includes the information and context given by |
|
39 | 39 | Verbose). |
|
40 | 40 | |
|
41 | 41 | .. note:: |
|
42 | 42 | |
|
43 | 43 | The verbose mode print all variables in the stack, which means it can |
|
44 | 44 | potentially leak sensitive information like access keys, or unencryted |
|
45 | 45 | password. |
|
46 | 46 | |
|
47 | 47 | Installation instructions for VerboseTB:: |
|
48 | 48 | |
|
49 | 49 | import sys,ultratb |
|
50 | 50 | sys.excepthook = ultratb.VerboseTB() |
|
51 | 51 | |
|
52 | 52 | Note: Much of the code in this module was lifted verbatim from the standard |
|
53 | 53 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
54 | 54 | |
|
55 | 55 | Color schemes |
|
56 | 56 | ------------- |
|
57 | 57 | |
|
58 | 58 | The colors are defined in the class TBTools through the use of the |
|
59 | 59 | ColorSchemeTable class. Currently the following exist: |
|
60 | 60 | |
|
61 | 61 | - NoColor: allows all of this module to be used in any terminal (the color |
|
62 | 62 | escapes are just dummy blank strings). |
|
63 | 63 | |
|
64 | 64 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
65 | 65 | or very dark background). |
|
66 | 66 | |
|
67 | 67 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
68 | 68 | in light background terminals. |
|
69 | 69 | |
|
70 | - Neutral: a neutral color scheme that should be readable on both light and | |
|
71 | dark background | |
|
72 | ||
|
70 | 73 | You can implement other color schemes easily, the syntax is fairly |
|
71 | 74 | self-explanatory. Please send back new schemes you develop to the author for |
|
72 | 75 | possible inclusion in future releases. |
|
73 | 76 | |
|
74 | 77 | Inheritance diagram: |
|
75 | 78 | |
|
76 | 79 | .. inheritance-diagram:: IPython.core.ultratb |
|
77 | 80 | :parts: 3 |
|
78 | 81 | """ |
|
79 | 82 | |
|
80 | 83 | #***************************************************************************** |
|
81 | 84 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
82 | 85 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
83 | 86 | # |
|
84 | 87 | # Distributed under the terms of the BSD License. The full license is in |
|
85 | 88 | # the file COPYING, distributed as part of this software. |
|
86 | 89 | #***************************************************************************** |
|
87 | 90 | |
|
88 | 91 | from __future__ import absolute_import |
|
89 | 92 | from __future__ import unicode_literals |
|
90 | 93 | from __future__ import print_function |
|
91 | 94 | |
|
92 | 95 | import dis |
|
93 | 96 | import inspect |
|
94 | 97 | import keyword |
|
95 | 98 | import linecache |
|
96 | 99 | import os |
|
97 | 100 | import pydoc |
|
98 | 101 | import re |
|
99 | 102 | import sys |
|
100 | 103 | import time |
|
101 | 104 | import tokenize |
|
102 | 105 | import traceback |
|
103 | 106 | import types |
|
104 | 107 | |
|
105 | 108 | try: # Python 2 |
|
106 | 109 | generate_tokens = tokenize.generate_tokens |
|
107 | 110 | except AttributeError: # Python 3 |
|
108 | 111 | generate_tokens = tokenize.tokenize |
|
109 | 112 | |
|
110 | 113 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
111 | 114 | from inspect import getsourcefile, getfile, getmodule, \ |
|
112 | 115 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
113 | 116 | |
|
114 | 117 | # IPython's own modules |
|
115 | 118 | # Modified pdb which doesn't damage IPython's readline handling |
|
116 | 119 | from IPython import get_ipython |
|
117 | 120 | from IPython.core import debugger |
|
118 | 121 | from IPython.core.display_trap import DisplayTrap |
|
119 | 122 | from IPython.core.excolors import exception_colors |
|
120 | 123 | from IPython.utils import PyColorize |
|
121 | 124 | from IPython.utils import openpy |
|
122 | 125 | from IPython.utils import path as util_path |
|
123 | 126 | from IPython.utils import py3compat |
|
124 | 127 | from IPython.utils import ulinecache |
|
125 | 128 | from IPython.utils.data import uniq_stable |
|
126 | 129 | from IPython.utils.terminal import get_terminal_size |
|
127 | 130 | from logging import info, error |
|
128 | 131 | |
|
129 | 132 | import IPython.utils.colorable as colorable |
|
130 | 133 | |
|
131 | 134 | # Globals |
|
132 | 135 | # amount of space to put line numbers before verbose tracebacks |
|
133 | 136 | INDENT_SIZE = 8 |
|
134 | 137 | |
|
135 | 138 | # Default color scheme. This is used, for example, by the traceback |
|
136 | 139 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
137 | 140 | # value is used, but having a module global makes this functionality available |
|
138 | 141 | # to users of ultratb who are NOT running inside ipython. |
|
139 | 142 | DEFAULT_SCHEME = 'NoColor' |
|
140 | 143 | |
|
141 | 144 | # --------------------------------------------------------------------------- |
|
142 | 145 | # Code begins |
|
143 | 146 | |
|
144 | 147 | # Utility functions |
|
145 | 148 | def inspect_error(): |
|
146 | 149 | """Print a message about internal inspect errors. |
|
147 | 150 | |
|
148 | 151 | These are unfortunately quite common.""" |
|
149 | 152 | |
|
150 | 153 | error('Internal Python error in the inspect module.\n' |
|
151 | 154 | 'Below is the traceback from this internal error.\n') |
|
152 | 155 | |
|
153 | 156 | |
|
154 | 157 | # This function is a monkeypatch we apply to the Python inspect module. We have |
|
155 | 158 | # now found when it's needed (see discussion on issue gh-1456), and we have a |
|
156 | 159 | # test case (IPython.core.tests.test_ultratb.ChangedPyFileTest) that fails if |
|
157 | 160 | # the monkeypatch is not applied. TK, Aug 2012. |
|
158 | 161 | def findsource(object): |
|
159 | 162 | """Return the entire source file and starting line number for an object. |
|
160 | 163 | |
|
161 | 164 | The argument may be a module, class, method, function, traceback, frame, |
|
162 | 165 | or code object. The source code is returned as a list of all the lines |
|
163 | 166 | in the file and the line number indexes a line in that list. An IOError |
|
164 | 167 | is raised if the source code cannot be retrieved. |
|
165 | 168 | |
|
166 | 169 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
167 | 170 | |
|
168 | 171 | file = getsourcefile(object) or getfile(object) |
|
169 | 172 | # If the object is a frame, then trying to get the globals dict from its |
|
170 | 173 | # module won't work. Instead, the frame object itself has the globals |
|
171 | 174 | # dictionary. |
|
172 | 175 | globals_dict = None |
|
173 | 176 | if inspect.isframe(object): |
|
174 | 177 | # XXX: can this ever be false? |
|
175 | 178 | globals_dict = object.f_globals |
|
176 | 179 | else: |
|
177 | 180 | module = getmodule(object, file) |
|
178 | 181 | if module: |
|
179 | 182 | globals_dict = module.__dict__ |
|
180 | 183 | lines = linecache.getlines(file, globals_dict) |
|
181 | 184 | if not lines: |
|
182 | 185 | raise IOError('could not get source code') |
|
183 | 186 | |
|
184 | 187 | if ismodule(object): |
|
185 | 188 | return lines, 0 |
|
186 | 189 | |
|
187 | 190 | if isclass(object): |
|
188 | 191 | name = object.__name__ |
|
189 | 192 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
190 | 193 | # make some effort to find the best matching class definition: |
|
191 | 194 | # use the one with the least indentation, which is the one |
|
192 | 195 | # that's most probably not inside a function definition. |
|
193 | 196 | candidates = [] |
|
194 | 197 | for i in range(len(lines)): |
|
195 | 198 | match = pat.match(lines[i]) |
|
196 | 199 | if match: |
|
197 | 200 | # if it's at toplevel, it's already the best one |
|
198 | 201 | if lines[i][0] == 'c': |
|
199 | 202 | return lines, i |
|
200 | 203 | # else add whitespace to candidate list |
|
201 | 204 | candidates.append((match.group(1), i)) |
|
202 | 205 | if candidates: |
|
203 | 206 | # this will sort by whitespace, and by line number, |
|
204 | 207 | # less whitespace first |
|
205 | 208 | candidates.sort() |
|
206 | 209 | return lines, candidates[0][1] |
|
207 | 210 | else: |
|
208 | 211 | raise IOError('could not find class definition') |
|
209 | 212 | |
|
210 | 213 | if ismethod(object): |
|
211 | 214 | object = object.__func__ |
|
212 | 215 | if isfunction(object): |
|
213 | 216 | object = object.__code__ |
|
214 | 217 | if istraceback(object): |
|
215 | 218 | object = object.tb_frame |
|
216 | 219 | if isframe(object): |
|
217 | 220 | object = object.f_code |
|
218 | 221 | if iscode(object): |
|
219 | 222 | if not hasattr(object, 'co_firstlineno'): |
|
220 | 223 | raise IOError('could not find function definition') |
|
221 | 224 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
222 | 225 | pmatch = pat.match |
|
223 | 226 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
224 | 227 | # the length of lines, which causes an error. Safeguard against that. |
|
225 | 228 | lnum = min(object.co_firstlineno, len(lines)) - 1 |
|
226 | 229 | while lnum > 0: |
|
227 | 230 | if pmatch(lines[lnum]): |
|
228 | 231 | break |
|
229 | 232 | lnum -= 1 |
|
230 | 233 | |
|
231 | 234 | return lines, lnum |
|
232 | 235 | raise IOError('could not find code object') |
|
233 | 236 | |
|
234 | 237 | |
|
235 | 238 | # This is a patched version of inspect.getargs that applies the (unmerged) |
|
236 | 239 | # patch for http://bugs.python.org/issue14611 by Stefano Taschini. This fixes |
|
237 | 240 | # https://github.com/ipython/ipython/issues/8205 and |
|
238 | 241 | # https://github.com/ipython/ipython/issues/8293 |
|
239 | 242 | def getargs(co): |
|
240 | 243 | """Get information about the arguments accepted by a code object. |
|
241 | 244 | |
|
242 | 245 | Three things are returned: (args, varargs, varkw), where 'args' is |
|
243 | 246 | a list of argument names (possibly containing nested lists), and |
|
244 | 247 | 'varargs' and 'varkw' are the names of the * and ** arguments or None.""" |
|
245 | 248 | if not iscode(co): |
|
246 | 249 | raise TypeError('{!r} is not a code object'.format(co)) |
|
247 | 250 | |
|
248 | 251 | nargs = co.co_argcount |
|
249 | 252 | names = co.co_varnames |
|
250 | 253 | args = list(names[:nargs]) |
|
251 | 254 | step = 0 |
|
252 | 255 | |
|
253 | 256 | # The following acrobatics are for anonymous (tuple) arguments. |
|
254 | 257 | for i in range(nargs): |
|
255 | 258 | if args[i][:1] in ('', '.'): |
|
256 | 259 | stack, remain, count = [], [], [] |
|
257 | 260 | while step < len(co.co_code): |
|
258 | 261 | op = ord(co.co_code[step]) |
|
259 | 262 | step = step + 1 |
|
260 | 263 | if op >= dis.HAVE_ARGUMENT: |
|
261 | 264 | opname = dis.opname[op] |
|
262 | 265 | value = ord(co.co_code[step]) + ord(co.co_code[step+1])*256 |
|
263 | 266 | step = step + 2 |
|
264 | 267 | if opname in ('UNPACK_TUPLE', 'UNPACK_SEQUENCE'): |
|
265 | 268 | remain.append(value) |
|
266 | 269 | count.append(value) |
|
267 | 270 | elif opname in ('STORE_FAST', 'STORE_DEREF'): |
|
268 | 271 | if op in dis.haslocal: |
|
269 | 272 | stack.append(co.co_varnames[value]) |
|
270 | 273 | elif op in dis.hasfree: |
|
271 | 274 | stack.append((co.co_cellvars + co.co_freevars)[value]) |
|
272 | 275 | # Special case for sublists of length 1: def foo((bar)) |
|
273 | 276 | # doesn't generate the UNPACK_TUPLE bytecode, so if |
|
274 | 277 | # `remain` is empty here, we have such a sublist. |
|
275 | 278 | if not remain: |
|
276 | 279 | stack[0] = [stack[0]] |
|
277 | 280 | break |
|
278 | 281 | else: |
|
279 | 282 | remain[-1] = remain[-1] - 1 |
|
280 | 283 | while remain[-1] == 0: |
|
281 | 284 | remain.pop() |
|
282 | 285 | size = count.pop() |
|
283 | 286 | stack[-size:] = [stack[-size:]] |
|
284 | 287 | if not remain: |
|
285 | 288 | break |
|
286 | 289 | remain[-1] = remain[-1] - 1 |
|
287 | 290 | if not remain: |
|
288 | 291 | break |
|
289 | 292 | args[i] = stack[0] |
|
290 | 293 | |
|
291 | 294 | varargs = None |
|
292 | 295 | if co.co_flags & inspect.CO_VARARGS: |
|
293 | 296 | varargs = co.co_varnames[nargs] |
|
294 | 297 | nargs = nargs + 1 |
|
295 | 298 | varkw = None |
|
296 | 299 | if co.co_flags & inspect.CO_VARKEYWORDS: |
|
297 | 300 | varkw = co.co_varnames[nargs] |
|
298 | 301 | return inspect.Arguments(args, varargs, varkw) |
|
299 | 302 | |
|
300 | 303 | |
|
301 | 304 | # Monkeypatch inspect to apply our bugfix. |
|
302 | 305 | def with_patch_inspect(f): |
|
303 | 306 | """decorator for monkeypatching inspect.findsource""" |
|
304 | 307 | |
|
305 | 308 | def wrapped(*args, **kwargs): |
|
306 | 309 | save_findsource = inspect.findsource |
|
307 | 310 | save_getargs = inspect.getargs |
|
308 | 311 | inspect.findsource = findsource |
|
309 | 312 | inspect.getargs = getargs |
|
310 | 313 | try: |
|
311 | 314 | return f(*args, **kwargs) |
|
312 | 315 | finally: |
|
313 | 316 | inspect.findsource = save_findsource |
|
314 | 317 | inspect.getargs = save_getargs |
|
315 | 318 | |
|
316 | 319 | return wrapped |
|
317 | 320 | |
|
318 | 321 | |
|
319 | 322 | if py3compat.PY3: |
|
320 | 323 | fixed_getargvalues = inspect.getargvalues |
|
321 | 324 | else: |
|
322 | 325 | # Fixes for https://github.com/ipython/ipython/issues/8293 |
|
323 | 326 | # and https://github.com/ipython/ipython/issues/8205. |
|
324 | 327 | # The relevant bug is caused by failure to correctly handle anonymous tuple |
|
325 | 328 | # unpacking, which only exists in Python 2. |
|
326 | 329 | fixed_getargvalues = with_patch_inspect(inspect.getargvalues) |
|
327 | 330 | |
|
328 | 331 | |
|
329 | 332 | def fix_frame_records_filenames(records): |
|
330 | 333 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
331 | 334 | |
|
332 | 335 | Particularly, modules loaded from within zip files have useless filenames |
|
333 | 336 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
334 | 337 | """ |
|
335 | 338 | fixed_records = [] |
|
336 | 339 | for frame, filename, line_no, func_name, lines, index in records: |
|
337 | 340 | # Look inside the frame's globals dictionary for __file__, |
|
338 | 341 | # which should be better. However, keep Cython filenames since |
|
339 | 342 | # we prefer the source filenames over the compiled .so file. |
|
340 | 343 | filename = py3compat.cast_unicode_py2(filename, "utf-8") |
|
341 | 344 | if not filename.endswith(('.pyx', '.pxd', '.pxi')): |
|
342 | 345 | better_fn = frame.f_globals.get('__file__', None) |
|
343 | 346 | if isinstance(better_fn, str): |
|
344 | 347 | # Check the type just in case someone did something weird with |
|
345 | 348 | # __file__. It might also be None if the error occurred during |
|
346 | 349 | # import. |
|
347 | 350 | filename = better_fn |
|
348 | 351 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
349 | 352 | return fixed_records |
|
350 | 353 | |
|
351 | 354 | |
|
352 | 355 | @with_patch_inspect |
|
353 | 356 | def _fixed_getinnerframes(etb, context=1, tb_offset=0): |
|
354 | 357 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
355 | 358 | |
|
356 | 359 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
357 | 360 | # If the error is at the console, don't build any context, since it would |
|
358 | 361 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
359 | 362 | # console) |
|
360 | 363 | rec_check = records[tb_offset:] |
|
361 | 364 | try: |
|
362 | 365 | rname = rec_check[0][1] |
|
363 | 366 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
364 | 367 | return rec_check |
|
365 | 368 | except IndexError: |
|
366 | 369 | pass |
|
367 | 370 | |
|
368 | 371 | aux = traceback.extract_tb(etb) |
|
369 | 372 | assert len(records) == len(aux) |
|
370 | 373 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
371 | 374 | maybeStart = lnum - 1 - context // 2 |
|
372 | 375 | start = max(maybeStart, 0) |
|
373 | 376 | end = start + context |
|
374 | 377 | lines = ulinecache.getlines(file)[start:end] |
|
375 | 378 | buf = list(records[i]) |
|
376 | 379 | buf[LNUM_POS] = lnum |
|
377 | 380 | buf[INDEX_POS] = lnum - 1 - start |
|
378 | 381 | buf[LINES_POS] = lines |
|
379 | 382 | records[i] = tuple(buf) |
|
380 | 383 | return records[tb_offset:] |
|
381 | 384 | |
|
382 | 385 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
383 | 386 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
384 | 387 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
385 | 388 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
386 | 389 | |
|
387 | 390 | _parser = PyColorize.Parser() |
|
388 | 391 | |
|
389 | 392 | |
|
390 | 393 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None): |
|
391 | 394 | numbers_width = INDENT_SIZE - 1 |
|
392 | 395 | res = [] |
|
393 | 396 | i = lnum - index |
|
394 | 397 | |
|
395 | 398 | # This lets us get fully syntax-highlighted tracebacks. |
|
396 | 399 | if scheme is None: |
|
397 | 400 | ipinst = get_ipython() |
|
398 | 401 | if ipinst is not None: |
|
399 | 402 | scheme = ipinst.colors |
|
400 | 403 | else: |
|
401 | 404 | scheme = DEFAULT_SCHEME |
|
402 | 405 | |
|
403 | 406 | _line_format = _parser.format2 |
|
404 | 407 | |
|
405 | 408 | for line in lines: |
|
406 | 409 | line = py3compat.cast_unicode(line) |
|
407 | 410 | |
|
408 | 411 | new_line, err = _line_format(line, 'str', scheme) |
|
409 | 412 | if not err: line = new_line |
|
410 | 413 | |
|
411 | 414 | if i == lnum: |
|
412 | 415 | # This is the line with the error |
|
413 | 416 | pad = numbers_width - len(str(i)) |
|
414 | 417 | num = '%s%s' % (debugger.make_arrow(pad), str(lnum)) |
|
415 | 418 | line = '%s%s%s %s%s' % (Colors.linenoEm, num, |
|
416 | 419 | Colors.line, line, Colors.Normal) |
|
417 | 420 | else: |
|
418 | 421 | num = '%*s' % (numbers_width, i) |
|
419 | 422 | line = '%s%s%s %s' % (Colors.lineno, num, |
|
420 | 423 | Colors.Normal, line) |
|
421 | 424 | |
|
422 | 425 | res.append(line) |
|
423 | 426 | if lvals and i == lnum: |
|
424 | 427 | res.append(lvals + '\n') |
|
425 | 428 | i = i + 1 |
|
426 | 429 | return res |
|
427 | 430 | |
|
428 | 431 | def is_recursion_error(etype, value, records): |
|
429 | 432 | try: |
|
430 | 433 | # RecursionError is new in Python 3.5 |
|
431 | 434 | recursion_error_type = RecursionError |
|
432 | 435 | except NameError: |
|
433 | 436 | recursion_error_type = RuntimeError |
|
434 | 437 | |
|
435 | 438 | # The default recursion limit is 1000, but some of that will be taken up |
|
436 | 439 | # by stack frames in IPython itself. >500 frames probably indicates |
|
437 | 440 | # a recursion error. |
|
438 | 441 | return (etype is recursion_error_type) \ |
|
439 | 442 | and "recursion" in str(value).lower() \ |
|
440 | 443 | and len(records) > 500 |
|
441 | 444 | |
|
442 | 445 | def find_recursion(etype, value, records): |
|
443 | 446 | """Identify the repeating stack frames from a RecursionError traceback |
|
444 | 447 | |
|
445 | 448 | 'records' is a list as returned by VerboseTB.get_records() |
|
446 | 449 | |
|
447 | 450 | Returns (last_unique, repeat_length) |
|
448 | 451 | """ |
|
449 | 452 | # This involves a bit of guesswork - we want to show enough of the traceback |
|
450 | 453 | # to indicate where the recursion is occurring. We guess that the innermost |
|
451 | 454 | # quarter of the traceback (250 frames by default) is repeats, and find the |
|
452 | 455 | # first frame (from in to out) that looks different. |
|
453 | 456 | if not is_recursion_error(etype, value, records): |
|
454 | 457 | return len(records), 0 |
|
455 | 458 | |
|
456 | 459 | # Select filename, lineno, func_name to track frames with |
|
457 | 460 | records = [r[1:4] for r in records] |
|
458 | 461 | inner_frames = records[-(len(records)//4):] |
|
459 | 462 | frames_repeated = set(inner_frames) |
|
460 | 463 | |
|
461 | 464 | last_seen_at = {} |
|
462 | 465 | longest_repeat = 0 |
|
463 | 466 | i = len(records) |
|
464 | 467 | for frame in reversed(records): |
|
465 | 468 | i -= 1 |
|
466 | 469 | if frame not in frames_repeated: |
|
467 | 470 | last_unique = i |
|
468 | 471 | break |
|
469 | 472 | |
|
470 | 473 | if frame in last_seen_at: |
|
471 | 474 | distance = last_seen_at[frame] - i |
|
472 | 475 | longest_repeat = max(longest_repeat, distance) |
|
473 | 476 | |
|
474 | 477 | last_seen_at[frame] = i |
|
475 | 478 | else: |
|
476 | 479 | last_unique = 0 # The whole traceback was recursion |
|
477 | 480 | |
|
478 | 481 | return last_unique, longest_repeat |
|
479 | 482 | |
|
480 | 483 | #--------------------------------------------------------------------------- |
|
481 | 484 | # Module classes |
|
482 | 485 | class TBTools(colorable.Colorable): |
|
483 | 486 | """Basic tools used by all traceback printer classes.""" |
|
484 | 487 | |
|
485 | 488 | # Number of frames to skip when reporting tracebacks |
|
486 | 489 | tb_offset = 0 |
|
487 | 490 | |
|
488 | 491 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None): |
|
489 | 492 | # Whether to call the interactive pdb debugger after printing |
|
490 | 493 | # tracebacks or not |
|
491 | 494 | super(TBTools, self).__init__(parent=parent, config=config) |
|
492 | 495 | self.call_pdb = call_pdb |
|
493 | 496 | |
|
494 | 497 | # Output stream to write to. Note that we store the original value in |
|
495 | 498 | # a private attribute and then make the public ostream a property, so |
|
496 | 499 | # that we can delay accessing io.stdout until runtime. The way |
|
497 | 500 | # things are written now, the io.stdout object is dynamically managed |
|
498 | 501 | # so a reference to it should NEVER be stored statically. This |
|
499 | 502 | # property approach confines this detail to a single location, and all |
|
500 | 503 | # subclasses can simply access self.ostream for writing. |
|
501 | 504 | self._ostream = ostream |
|
502 | 505 | |
|
503 | 506 | # Create color table |
|
504 | 507 | self.color_scheme_table = exception_colors() |
|
505 | 508 | |
|
506 | 509 | self.set_colors(color_scheme) |
|
507 | 510 | self.old_scheme = color_scheme # save initial value for toggles |
|
508 | 511 | |
|
509 | 512 | if call_pdb: |
|
510 | 513 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
511 | 514 | else: |
|
512 | 515 | self.pdb = None |
|
513 | 516 | |
|
514 | 517 | def _get_ostream(self): |
|
515 | 518 | """Output stream that exceptions are written to. |
|
516 | 519 | |
|
517 | 520 | Valid values are: |
|
518 | 521 | |
|
519 | 522 | - None: the default, which means that IPython will dynamically resolve |
|
520 | 523 | to io.stdout. This ensures compatibility with most tools, including |
|
521 | 524 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
522 | 525 | |
|
523 | 526 | - Any object with 'write' and 'flush' attributes. |
|
524 | 527 | """ |
|
525 | 528 | return sys.stdout if self._ostream is None else self._ostream |
|
526 | 529 | |
|
527 | 530 | def _set_ostream(self, val): |
|
528 | 531 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
529 | 532 | self._ostream = val |
|
530 | 533 | |
|
531 | 534 | ostream = property(_get_ostream, _set_ostream) |
|
532 | 535 | |
|
533 | 536 | def set_colors(self, *args, **kw): |
|
534 | 537 | """Shorthand access to the color table scheme selector method.""" |
|
535 | 538 | |
|
536 | 539 | # Set own color table |
|
537 | 540 | self.color_scheme_table.set_active_scheme(*args, **kw) |
|
538 | 541 | # for convenience, set Colors to the active scheme |
|
539 | 542 | self.Colors = self.color_scheme_table.active_colors |
|
540 | 543 | # Also set colors of debugger |
|
541 | 544 | if hasattr(self, 'pdb') and self.pdb is not None: |
|
542 | 545 | self.pdb.set_colors(*args, **kw) |
|
543 | 546 | |
|
544 | 547 | def color_toggle(self): |
|
545 | 548 | """Toggle between the currently active color scheme and NoColor.""" |
|
546 | 549 | |
|
547 | 550 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
548 | 551 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
549 | 552 | self.Colors = self.color_scheme_table.active_colors |
|
550 | 553 | else: |
|
551 | 554 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
552 | 555 | self.color_scheme_table.set_active_scheme('NoColor') |
|
553 | 556 | self.Colors = self.color_scheme_table.active_colors |
|
554 | 557 | |
|
555 | 558 | def stb2text(self, stb): |
|
556 | 559 | """Convert a structured traceback (a list) to a string.""" |
|
557 | 560 | return '\n'.join(stb) |
|
558 | 561 | |
|
559 | 562 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
560 | 563 | """Return formatted traceback. |
|
561 | 564 | |
|
562 | 565 | Subclasses may override this if they add extra arguments. |
|
563 | 566 | """ |
|
564 | 567 | tb_list = self.structured_traceback(etype, value, tb, |
|
565 | 568 | tb_offset, context) |
|
566 | 569 | return self.stb2text(tb_list) |
|
567 | 570 | |
|
568 | 571 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
569 | 572 | context=5, mode=None): |
|
570 | 573 | """Return a list of traceback frames. |
|
571 | 574 | |
|
572 | 575 | Must be implemented by each class. |
|
573 | 576 | """ |
|
574 | 577 | raise NotImplementedError() |
|
575 | 578 | |
|
576 | 579 | |
|
577 | 580 | #--------------------------------------------------------------------------- |
|
578 | 581 | class ListTB(TBTools): |
|
579 | 582 | """Print traceback information from a traceback list, with optional color. |
|
580 | 583 | |
|
581 | 584 | Calling requires 3 arguments: (etype, evalue, elist) |
|
582 | 585 | as would be obtained by:: |
|
583 | 586 | |
|
584 | 587 | etype, evalue, tb = sys.exc_info() |
|
585 | 588 | if tb: |
|
586 | 589 | elist = traceback.extract_tb(tb) |
|
587 | 590 | else: |
|
588 | 591 | elist = None |
|
589 | 592 | |
|
590 | 593 | It can thus be used by programs which need to process the traceback before |
|
591 | 594 | printing (such as console replacements based on the code module from the |
|
592 | 595 | standard library). |
|
593 | 596 | |
|
594 | 597 | Because they are meant to be called without a full traceback (only a |
|
595 | 598 | list), instances of this class can't call the interactive pdb debugger.""" |
|
596 | 599 | |
|
597 | 600 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None): |
|
598 | 601 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
599 | 602 | ostream=ostream, parent=parent) |
|
600 | 603 | |
|
601 | 604 | def __call__(self, etype, value, elist): |
|
602 | 605 | self.ostream.flush() |
|
603 | 606 | self.ostream.write(self.text(etype, value, elist)) |
|
604 | 607 | self.ostream.write('\n') |
|
605 | 608 | |
|
606 | 609 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
607 | 610 | context=5): |
|
608 | 611 | """Return a color formatted string with the traceback info. |
|
609 | 612 | |
|
610 | 613 | Parameters |
|
611 | 614 | ---------- |
|
612 | 615 | etype : exception type |
|
613 | 616 | Type of the exception raised. |
|
614 | 617 | |
|
615 | 618 | value : object |
|
616 | 619 | Data stored in the exception |
|
617 | 620 | |
|
618 | 621 | elist : list |
|
619 | 622 | List of frames, see class docstring for details. |
|
620 | 623 | |
|
621 | 624 | tb_offset : int, optional |
|
622 | 625 | Number of frames in the traceback to skip. If not given, the |
|
623 | 626 | instance value is used (set in constructor). |
|
624 | 627 | |
|
625 | 628 | context : int, optional |
|
626 | 629 | Number of lines of context information to print. |
|
627 | 630 | |
|
628 | 631 | Returns |
|
629 | 632 | ------- |
|
630 | 633 | String with formatted exception. |
|
631 | 634 | """ |
|
632 | 635 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
633 | 636 | Colors = self.Colors |
|
634 | 637 | out_list = [] |
|
635 | 638 | if elist: |
|
636 | 639 | |
|
637 | 640 | if tb_offset and len(elist) > tb_offset: |
|
638 | 641 | elist = elist[tb_offset:] |
|
639 | 642 | |
|
640 | 643 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
641 | 644 | (Colors.normalEm, Colors.Normal) + '\n') |
|
642 | 645 | out_list.extend(self._format_list(elist)) |
|
643 | 646 | # The exception info should be a single entry in the list. |
|
644 | 647 | lines = ''.join(self._format_exception_only(etype, value)) |
|
645 | 648 | out_list.append(lines) |
|
646 | 649 | |
|
647 | 650 | # Note: this code originally read: |
|
648 | 651 | |
|
649 | 652 | ## for line in lines[:-1]: |
|
650 | 653 | ## out_list.append(" "+line) |
|
651 | 654 | ## out_list.append(lines[-1]) |
|
652 | 655 | |
|
653 | 656 | # This means it was indenting everything but the last line by a little |
|
654 | 657 | # bit. I've disabled this for now, but if we see ugliness somewhere we |
|
655 | 658 | # can restore it. |
|
656 | 659 | |
|
657 | 660 | return out_list |
|
658 | 661 | |
|
659 | 662 | def _format_list(self, extracted_list): |
|
660 | 663 | """Format a list of traceback entry tuples for printing. |
|
661 | 664 | |
|
662 | 665 | Given a list of tuples as returned by extract_tb() or |
|
663 | 666 | extract_stack(), return a list of strings ready for printing. |
|
664 | 667 | Each string in the resulting list corresponds to the item with the |
|
665 | 668 | same index in the argument list. Each string ends in a newline; |
|
666 | 669 | the strings may contain internal newlines as well, for those items |
|
667 | 670 | whose source text line is not None. |
|
668 | 671 | |
|
669 | 672 | Lifted almost verbatim from traceback.py |
|
670 | 673 | """ |
|
671 | 674 | |
|
672 | 675 | Colors = self.Colors |
|
673 | 676 | list = [] |
|
674 | 677 | for filename, lineno, name, line in extracted_list[:-1]: |
|
675 | 678 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
676 | 679 | (Colors.filename, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.Normal, |
|
677 | 680 | Colors.lineno, lineno, Colors.Normal, |
|
678 | 681 | Colors.name, py3compat.cast_unicode_py2(name, "utf-8"), Colors.Normal) |
|
679 | 682 | if line: |
|
680 | 683 | item += ' %s\n' % line.strip() |
|
681 | 684 | list.append(item) |
|
682 | 685 | # Emphasize the last entry |
|
683 | 686 | filename, lineno, name, line = extracted_list[-1] |
|
684 | 687 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
685 | 688 | (Colors.normalEm, |
|
686 | 689 | Colors.filenameEm, py3compat.cast_unicode_py2(filename, "utf-8"), Colors.normalEm, |
|
687 | 690 | Colors.linenoEm, lineno, Colors.normalEm, |
|
688 | 691 | Colors.nameEm, py3compat.cast_unicode_py2(name, "utf-8"), Colors.normalEm, |
|
689 | 692 | Colors.Normal) |
|
690 | 693 | if line: |
|
691 | 694 | item += '%s %s%s\n' % (Colors.line, line.strip(), |
|
692 | 695 | Colors.Normal) |
|
693 | 696 | list.append(item) |
|
694 | 697 | return list |
|
695 | 698 | |
|
696 | 699 | def _format_exception_only(self, etype, value): |
|
697 | 700 | """Format the exception part of a traceback. |
|
698 | 701 | |
|
699 | 702 | The arguments are the exception type and value such as given by |
|
700 | 703 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
701 | 704 | in a newline. Normally, the list contains a single string; however, |
|
702 | 705 | for SyntaxError exceptions, it contains several lines that (when |
|
703 | 706 | printed) display detailed information about where the syntax error |
|
704 | 707 | occurred. The message indicating which exception occurred is the |
|
705 | 708 | always last string in the list. |
|
706 | 709 | |
|
707 | 710 | Also lifted nearly verbatim from traceback.py |
|
708 | 711 | """ |
|
709 | 712 | have_filedata = False |
|
710 | 713 | Colors = self.Colors |
|
711 | 714 | list = [] |
|
712 | 715 | stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal) |
|
713 | 716 | if value is None: |
|
714 | 717 | # Not sure if this can still happen in Python 2.6 and above |
|
715 | 718 | list.append(stype + '\n') |
|
716 | 719 | else: |
|
717 | 720 | if issubclass(etype, SyntaxError): |
|
718 | 721 | have_filedata = True |
|
719 | 722 | if not value.filename: value.filename = "<string>" |
|
720 | 723 | if value.lineno: |
|
721 | 724 | lineno = value.lineno |
|
722 | 725 | textline = ulinecache.getline(value.filename, value.lineno) |
|
723 | 726 | else: |
|
724 | 727 | lineno = 'unknown' |
|
725 | 728 | textline = '' |
|
726 | 729 | list.append('%s File %s"%s"%s, line %s%s%s\n' % \ |
|
727 | 730 | (Colors.normalEm, |
|
728 | 731 | Colors.filenameEm, py3compat.cast_unicode(value.filename), Colors.normalEm, |
|
729 | 732 | Colors.linenoEm, lineno, Colors.Normal )) |
|
730 | 733 | if textline == '': |
|
731 | 734 | textline = py3compat.cast_unicode(value.text, "utf-8") |
|
732 | 735 | |
|
733 | 736 | if textline is not None: |
|
734 | 737 | i = 0 |
|
735 | 738 | while i < len(textline) and textline[i].isspace(): |
|
736 | 739 | i += 1 |
|
737 | 740 | list.append('%s %s%s\n' % (Colors.line, |
|
738 | 741 | textline.strip(), |
|
739 | 742 | Colors.Normal)) |
|
740 | 743 | if value.offset is not None: |
|
741 | 744 | s = ' ' |
|
742 | 745 | for c in textline[i:value.offset - 1]: |
|
743 | 746 | if c.isspace(): |
|
744 | 747 | s += c |
|
745 | 748 | else: |
|
746 | 749 | s += ' ' |
|
747 | 750 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
748 | 751 | Colors.Normal)) |
|
749 | 752 | |
|
750 | 753 | try: |
|
751 | 754 | s = value.msg |
|
752 | 755 | except Exception: |
|
753 | 756 | s = self._some_str(value) |
|
754 | 757 | if s: |
|
755 | 758 | list.append('%s%s:%s %s\n' % (stype, Colors.excName, |
|
756 | 759 | Colors.Normal, s)) |
|
757 | 760 | else: |
|
758 | 761 | list.append('%s\n' % stype) |
|
759 | 762 | |
|
760 | 763 | # sync with user hooks |
|
761 | 764 | if have_filedata: |
|
762 | 765 | ipinst = get_ipython() |
|
763 | 766 | if ipinst is not None: |
|
764 | 767 | ipinst.hooks.synchronize_with_editor(value.filename, value.lineno, 0) |
|
765 | 768 | |
|
766 | 769 | return list |
|
767 | 770 | |
|
768 | 771 | def get_exception_only(self, etype, value): |
|
769 | 772 | """Only print the exception type and message, without a traceback. |
|
770 | 773 | |
|
771 | 774 | Parameters |
|
772 | 775 | ---------- |
|
773 | 776 | etype : exception type |
|
774 | 777 | value : exception value |
|
775 | 778 | """ |
|
776 | 779 | return ListTB.structured_traceback(self, etype, value, []) |
|
777 | 780 | |
|
778 | 781 | def show_exception_only(self, etype, evalue): |
|
779 | 782 | """Only print the exception type and message, without a traceback. |
|
780 | 783 | |
|
781 | 784 | Parameters |
|
782 | 785 | ---------- |
|
783 | 786 | etype : exception type |
|
784 | 787 | value : exception value |
|
785 | 788 | """ |
|
786 | 789 | # This method needs to use __call__ from *this* class, not the one from |
|
787 | 790 | # a subclass whose signature or behavior may be different |
|
788 | 791 | ostream = self.ostream |
|
789 | 792 | ostream.flush() |
|
790 | 793 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
791 | 794 | ostream.flush() |
|
792 | 795 | |
|
793 | 796 | def _some_str(self, value): |
|
794 | 797 | # Lifted from traceback.py |
|
795 | 798 | try: |
|
796 | 799 | return py3compat.cast_unicode(str(value)) |
|
797 | 800 | except: |
|
798 | 801 | return u'<unprintable %s object>' % type(value).__name__ |
|
799 | 802 | |
|
800 | 803 | |
|
801 | 804 | #---------------------------------------------------------------------------- |
|
802 | 805 | class VerboseTB(TBTools): |
|
803 | 806 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
804 | 807 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
805 | 808 | |
|
806 | 809 | Modified version which optionally strips the topmost entries from the |
|
807 | 810 | traceback, to be used with alternate interpreters (because their own code |
|
808 | 811 | would appear in the traceback).""" |
|
809 | 812 | |
|
810 | 813 | def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None, |
|
811 | 814 | tb_offset=0, long_header=False, include_vars=True, |
|
812 | 815 | check_cache=None, debugger_cls = None): |
|
813 | 816 | """Specify traceback offset, headers and color scheme. |
|
814 | 817 | |
|
815 | 818 | Define how many frames to drop from the tracebacks. Calling it with |
|
816 | 819 | tb_offset=1 allows use of this handler in interpreters which will have |
|
817 | 820 | their own code at the top of the traceback (VerboseTB will first |
|
818 | 821 | remove that frame before printing the traceback info).""" |
|
819 | 822 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
820 | 823 | ostream=ostream) |
|
821 | 824 | self.tb_offset = tb_offset |
|
822 | 825 | self.long_header = long_header |
|
823 | 826 | self.include_vars = include_vars |
|
824 | 827 | # By default we use linecache.checkcache, but the user can provide a |
|
825 | 828 | # different check_cache implementation. This is used by the IPython |
|
826 | 829 | # kernel to provide tracebacks for interactive code that is cached, |
|
827 | 830 | # by a compiler instance that flushes the linecache but preserves its |
|
828 | 831 | # own code cache. |
|
829 | 832 | if check_cache is None: |
|
830 | 833 | check_cache = linecache.checkcache |
|
831 | 834 | self.check_cache = check_cache |
|
832 | 835 | |
|
833 | 836 | self.debugger_cls = debugger_cls or debugger.Pdb |
|
834 | 837 | |
|
835 | 838 | def format_records(self, records, last_unique, recursion_repeat): |
|
836 | 839 | """Format the stack frames of the traceback""" |
|
837 | 840 | frames = [] |
|
838 | 841 | for r in records[:last_unique+recursion_repeat+1]: |
|
839 | 842 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
840 | 843 | frames.append(self.format_record(*r)) |
|
841 | 844 | |
|
842 | 845 | if recursion_repeat: |
|
843 | 846 | frames.append('... last %d frames repeated, from the frame below ...\n' % recursion_repeat) |
|
844 | 847 | frames.append(self.format_record(*records[last_unique+recursion_repeat+1])) |
|
845 | 848 | |
|
846 | 849 | return frames |
|
847 | 850 | |
|
848 | 851 | def format_record(self, frame, file, lnum, func, lines, index): |
|
849 | 852 | """Format a single stack frame""" |
|
850 | 853 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
851 | 854 | ColorsNormal = Colors.Normal # used a lot |
|
852 | 855 | col_scheme = self.color_scheme_table.active_scheme_name |
|
853 | 856 | indent = ' ' * INDENT_SIZE |
|
854 | 857 | em_normal = '%s\n%s%s' % (Colors.valEm, indent, ColorsNormal) |
|
855 | 858 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
856 | 859 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
857 | 860 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
858 | 861 | ColorsNormal) |
|
859 | 862 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
860 | 863 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
861 | 864 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
862 | 865 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
863 | 866 | Colors.vName, ColorsNormal) |
|
864 | 867 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
865 | 868 | |
|
866 | 869 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
867 | 870 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm, Colors.line, |
|
868 | 871 | ColorsNormal) |
|
869 | 872 | |
|
870 | 873 | abspath = os.path.abspath |
|
871 | 874 | |
|
872 | 875 | |
|
873 | 876 | if not file: |
|
874 | 877 | file = '?' |
|
875 | 878 | elif file.startswith(str("<")) and file.endswith(str(">")): |
|
876 | 879 | # Not a real filename, no problem... |
|
877 | 880 | pass |
|
878 | 881 | elif not os.path.isabs(file): |
|
879 | 882 | # Try to make the filename absolute by trying all |
|
880 | 883 | # sys.path entries (which is also what linecache does) |
|
881 | 884 | for dirname in sys.path: |
|
882 | 885 | try: |
|
883 | 886 | fullname = os.path.join(dirname, file) |
|
884 | 887 | if os.path.isfile(fullname): |
|
885 | 888 | file = os.path.abspath(fullname) |
|
886 | 889 | break |
|
887 | 890 | except Exception: |
|
888 | 891 | # Just in case that sys.path contains very |
|
889 | 892 | # strange entries... |
|
890 | 893 | pass |
|
891 | 894 | |
|
892 | 895 | file = py3compat.cast_unicode(file, util_path.fs_encoding) |
|
893 | 896 | link = tpl_link % file |
|
894 | 897 | args, varargs, varkw, locals = fixed_getargvalues(frame) |
|
895 | 898 | |
|
896 | 899 | if func == '?': |
|
897 | 900 | call = '' |
|
898 | 901 | else: |
|
899 | 902 | # Decide whether to include variable details or not |
|
900 | 903 | var_repr = self.include_vars and eqrepr or nullrepr |
|
901 | 904 | try: |
|
902 | 905 | call = tpl_call % (func, inspect.formatargvalues(args, |
|
903 | 906 | varargs, varkw, |
|
904 | 907 | locals, formatvalue=var_repr)) |
|
905 | 908 | except KeyError: |
|
906 | 909 | # This happens in situations like errors inside generator |
|
907 | 910 | # expressions, where local variables are listed in the |
|
908 | 911 | # line, but can't be extracted from the frame. I'm not |
|
909 | 912 | # 100% sure this isn't actually a bug in inspect itself, |
|
910 | 913 | # but since there's no info for us to compute with, the |
|
911 | 914 | # best we can do is report the failure and move on. Here |
|
912 | 915 | # we must *not* call any traceback construction again, |
|
913 | 916 | # because that would mess up use of %debug later on. So we |
|
914 | 917 | # simply report the failure and move on. The only |
|
915 | 918 | # limitation will be that this frame won't have locals |
|
916 | 919 | # listed in the call signature. Quite subtle problem... |
|
917 | 920 | # I can't think of a good way to validate this in a unit |
|
918 | 921 | # test, but running a script consisting of: |
|
919 | 922 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
920 | 923 | # will illustrate the error, if this exception catch is |
|
921 | 924 | # disabled. |
|
922 | 925 | call = tpl_call_fail % func |
|
923 | 926 | |
|
924 | 927 | # Don't attempt to tokenize binary files. |
|
925 | 928 | if file.endswith(('.so', '.pyd', '.dll')): |
|
926 | 929 | return '%s %s\n' % (link, call) |
|
927 | 930 | |
|
928 | 931 | elif file.endswith(('.pyc', '.pyo')): |
|
929 | 932 | # Look up the corresponding source file. |
|
930 | 933 | try: |
|
931 | 934 | file = openpy.source_from_cache(file) |
|
932 | 935 | except ValueError: |
|
933 | 936 | # Failed to get the source file for some reason |
|
934 | 937 | # E.g. https://github.com/ipython/ipython/issues/9486 |
|
935 | 938 | return '%s %s\n' % (link, call) |
|
936 | 939 | |
|
937 | 940 | def linereader(file=file, lnum=[lnum], getline=ulinecache.getline): |
|
938 | 941 | line = getline(file, lnum[0]) |
|
939 | 942 | lnum[0] += 1 |
|
940 | 943 | return line |
|
941 | 944 | |
|
942 | 945 | # Build the list of names on this line of code where the exception |
|
943 | 946 | # occurred. |
|
944 | 947 | try: |
|
945 | 948 | names = [] |
|
946 | 949 | name_cont = False |
|
947 | 950 | |
|
948 | 951 | for token_type, token, start, end, line in generate_tokens(linereader): |
|
949 | 952 | # build composite names |
|
950 | 953 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
951 | 954 | if name_cont: |
|
952 | 955 | # Continuation of a dotted name |
|
953 | 956 | try: |
|
954 | 957 | names[-1].append(token) |
|
955 | 958 | except IndexError: |
|
956 | 959 | names.append([token]) |
|
957 | 960 | name_cont = False |
|
958 | 961 | else: |
|
959 | 962 | # Regular new names. We append everything, the caller |
|
960 | 963 | # will be responsible for pruning the list later. It's |
|
961 | 964 | # very tricky to try to prune as we go, b/c composite |
|
962 | 965 | # names can fool us. The pruning at the end is easy |
|
963 | 966 | # to do (or the caller can print a list with repeated |
|
964 | 967 | # names if so desired. |
|
965 | 968 | names.append([token]) |
|
966 | 969 | elif token == '.': |
|
967 | 970 | name_cont = True |
|
968 | 971 | elif token_type == tokenize.NEWLINE: |
|
969 | 972 | break |
|
970 | 973 | |
|
971 | 974 | except (IndexError, UnicodeDecodeError, SyntaxError): |
|
972 | 975 | # signals exit of tokenizer |
|
973 | 976 | # SyntaxError can occur if the file is not actually Python |
|
974 | 977 | # - see gh-6300 |
|
975 | 978 | pass |
|
976 | 979 | except tokenize.TokenError as msg: |
|
977 | 980 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
978 | 981 | "The following traceback may be corrupted or invalid\n" |
|
979 | 982 | "The error message is: %s\n" % msg) |
|
980 | 983 | error(_m) |
|
981 | 984 | |
|
982 | 985 | # Join composite names (e.g. "dict.fromkeys") |
|
983 | 986 | names = ['.'.join(n) for n in names] |
|
984 | 987 | # prune names list of duplicates, but keep the right order |
|
985 | 988 | unique_names = uniq_stable(names) |
|
986 | 989 | |
|
987 | 990 | # Start loop over vars |
|
988 | 991 | lvals = [] |
|
989 | 992 | if self.include_vars: |
|
990 | 993 | for name_full in unique_names: |
|
991 | 994 | name_base = name_full.split('.', 1)[0] |
|
992 | 995 | if name_base in frame.f_code.co_varnames: |
|
993 | 996 | if name_base in locals: |
|
994 | 997 | try: |
|
995 | 998 | value = repr(eval(name_full, locals)) |
|
996 | 999 | except: |
|
997 | 1000 | value = undefined |
|
998 | 1001 | else: |
|
999 | 1002 | value = undefined |
|
1000 | 1003 | name = tpl_local_var % name_full |
|
1001 | 1004 | else: |
|
1002 | 1005 | if name_base in frame.f_globals: |
|
1003 | 1006 | try: |
|
1004 | 1007 | value = repr(eval(name_full, frame.f_globals)) |
|
1005 | 1008 | except: |
|
1006 | 1009 | value = undefined |
|
1007 | 1010 | else: |
|
1008 | 1011 | value = undefined |
|
1009 | 1012 | name = tpl_global_var % name_full |
|
1010 | 1013 | lvals.append(tpl_name_val % (name, value)) |
|
1011 | 1014 | if lvals: |
|
1012 | 1015 | lvals = '%s%s' % (indent, em_normal.join(lvals)) |
|
1013 | 1016 | else: |
|
1014 | 1017 | lvals = '' |
|
1015 | 1018 | |
|
1016 | 1019 | level = '%s %s\n' % (link, call) |
|
1017 | 1020 | |
|
1018 | 1021 | if index is None: |
|
1019 | 1022 | return level |
|
1020 | 1023 | else: |
|
1021 | 1024 | return '%s%s' % (level, ''.join( |
|
1022 | 1025 | _format_traceback_lines(lnum, index, lines, Colors, lvals, |
|
1023 | 1026 | col_scheme))) |
|
1024 | 1027 | |
|
1025 | 1028 | def prepare_chained_exception_message(self, cause): |
|
1026 | 1029 | direct_cause = "\nThe above exception was the direct cause of the following exception:\n" |
|
1027 | 1030 | exception_during_handling = "\nDuring handling of the above exception, another exception occurred:\n" |
|
1028 | 1031 | |
|
1029 | 1032 | if cause: |
|
1030 | 1033 | message = [[direct_cause]] |
|
1031 | 1034 | else: |
|
1032 | 1035 | message = [[exception_during_handling]] |
|
1033 | 1036 | return message |
|
1034 | 1037 | |
|
1035 | 1038 | def prepare_header(self, etype, long_version=False): |
|
1036 | 1039 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1037 | 1040 | colorsnormal = colors.Normal # used a lot |
|
1038 | 1041 | exc = '%s%s%s' % (colors.excName, etype, colorsnormal) |
|
1039 | 1042 | width = min(75, get_terminal_size()[0]) |
|
1040 | 1043 | if long_version: |
|
1041 | 1044 | # Header with the exception type, python version, and date |
|
1042 | 1045 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
1043 | 1046 | date = time.ctime(time.time()) |
|
1044 | 1047 | |
|
1045 | 1048 | head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal, |
|
1046 | 1049 | exc, ' ' * (width - len(str(etype)) - len(pyver)), |
|
1047 | 1050 | pyver, date.rjust(width) ) |
|
1048 | 1051 | head += "\nA problem occurred executing Python code. Here is the sequence of function" \ |
|
1049 | 1052 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
1050 | 1053 | else: |
|
1051 | 1054 | # Simplified header |
|
1052 | 1055 | head = '%s%s' % (exc, 'Traceback (most recent call last)'. \ |
|
1053 | 1056 | rjust(width - len(str(etype))) ) |
|
1054 | 1057 | |
|
1055 | 1058 | return head |
|
1056 | 1059 | |
|
1057 | 1060 | def format_exception(self, etype, evalue): |
|
1058 | 1061 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1059 | 1062 | colorsnormal = colors.Normal # used a lot |
|
1060 | 1063 | indent = ' ' * INDENT_SIZE |
|
1061 | 1064 | # Get (safely) a string form of the exception info |
|
1062 | 1065 | try: |
|
1063 | 1066 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1064 | 1067 | except: |
|
1065 | 1068 | # User exception is improperly defined. |
|
1066 | 1069 | etype, evalue = str, sys.exc_info()[:2] |
|
1067 | 1070 | etype_str, evalue_str = map(str, (etype, evalue)) |
|
1068 | 1071 | # ... and format it |
|
1069 | 1072 | exception = ['%s%s%s: %s' % (colors.excName, etype_str, |
|
1070 | 1073 | colorsnormal, py3compat.cast_unicode(evalue_str))] |
|
1071 | 1074 | |
|
1072 | 1075 | if (not py3compat.PY3) and type(evalue) is types.InstanceType: |
|
1073 | 1076 | try: |
|
1074 | 1077 | names = [w for w in dir(evalue) if isinstance(w, py3compat.string_types)] |
|
1075 | 1078 | except: |
|
1076 | 1079 | # Every now and then, an object with funny internals blows up |
|
1077 | 1080 | # when dir() is called on it. We do the best we can to report |
|
1078 | 1081 | # the problem and continue |
|
1079 | 1082 | _m = '%sException reporting error (object with broken dir())%s:' |
|
1080 | 1083 | exception.append(_m % (colors.excName, colorsnormal)) |
|
1081 | 1084 | etype_str, evalue_str = map(str, sys.exc_info()[:2]) |
|
1082 | 1085 | exception.append('%s%s%s: %s' % (colors.excName, etype_str, |
|
1083 | 1086 | colorsnormal, py3compat.cast_unicode(evalue_str))) |
|
1084 | 1087 | names = [] |
|
1085 | 1088 | for name in names: |
|
1086 | 1089 | value = text_repr(getattr(evalue, name)) |
|
1087 | 1090 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
1088 | 1091 | |
|
1089 | 1092 | return exception |
|
1090 | 1093 | |
|
1091 | 1094 | def format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset): |
|
1092 | 1095 | """Formats the header, traceback and exception message for a single exception. |
|
1093 | 1096 | |
|
1094 | 1097 | This may be called multiple times by Python 3 exception chaining |
|
1095 | 1098 | (PEP 3134). |
|
1096 | 1099 | """ |
|
1097 | 1100 | # some locals |
|
1098 | 1101 | orig_etype = etype |
|
1099 | 1102 | try: |
|
1100 | 1103 | etype = etype.__name__ |
|
1101 | 1104 | except AttributeError: |
|
1102 | 1105 | pass |
|
1103 | 1106 | |
|
1104 | 1107 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1105 | 1108 | head = self.prepare_header(etype, self.long_header) |
|
1106 | 1109 | records = self.get_records(etb, number_of_lines_of_context, tb_offset) |
|
1107 | 1110 | |
|
1108 | 1111 | if records is None: |
|
1109 | 1112 | return "" |
|
1110 | 1113 | |
|
1111 | 1114 | last_unique, recursion_repeat = find_recursion(orig_etype, evalue, records) |
|
1112 | 1115 | |
|
1113 | 1116 | frames = self.format_records(records, last_unique, recursion_repeat) |
|
1114 | 1117 | |
|
1115 | 1118 | formatted_exception = self.format_exception(etype, evalue) |
|
1116 | 1119 | if records: |
|
1117 | 1120 | filepath, lnum = records[-1][1:3] |
|
1118 | 1121 | filepath = os.path.abspath(filepath) |
|
1119 | 1122 | ipinst = get_ipython() |
|
1120 | 1123 | if ipinst is not None: |
|
1121 | 1124 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
1122 | 1125 | |
|
1123 | 1126 | return [[head] + frames + [''.join(formatted_exception[0])]] |
|
1124 | 1127 | |
|
1125 | 1128 | def get_records(self, etb, number_of_lines_of_context, tb_offset): |
|
1126 | 1129 | try: |
|
1127 | 1130 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
1128 | 1131 | # problems, but it generates empty tracebacks for console errors |
|
1129 | 1132 | # (5 blanks lines) where none should be returned. |
|
1130 | 1133 | return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset) |
|
1131 | 1134 | except: |
|
1132 | 1135 | # FIXME: I've been getting many crash reports from python 2.3 |
|
1133 | 1136 | # users, traceable to inspect.py. If I can find a small test-case |
|
1134 | 1137 | # to reproduce this, I should either write a better workaround or |
|
1135 | 1138 | # file a bug report against inspect (if that's the real problem). |
|
1136 | 1139 | # So far, I haven't been able to find an isolated example to |
|
1137 | 1140 | # reproduce the problem. |
|
1138 | 1141 | inspect_error() |
|
1139 | 1142 | traceback.print_exc(file=self.ostream) |
|
1140 | 1143 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
1141 | 1144 | return None |
|
1142 | 1145 | |
|
1143 | 1146 | def get_parts_of_chained_exception(self, evalue): |
|
1144 | 1147 | def get_chained_exception(exception_value): |
|
1145 | 1148 | cause = getattr(exception_value, '__cause__', None) |
|
1146 | 1149 | if cause: |
|
1147 | 1150 | return cause |
|
1148 | 1151 | if getattr(exception_value, '__suppress_context__', False): |
|
1149 | 1152 | return None |
|
1150 | 1153 | return getattr(exception_value, '__context__', None) |
|
1151 | 1154 | |
|
1152 | 1155 | chained_evalue = get_chained_exception(evalue) |
|
1153 | 1156 | |
|
1154 | 1157 | if chained_evalue: |
|
1155 | 1158 | return chained_evalue.__class__, chained_evalue, chained_evalue.__traceback__ |
|
1156 | 1159 | |
|
1157 | 1160 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
1158 | 1161 | number_of_lines_of_context=5): |
|
1159 | 1162 | """Return a nice text document describing the traceback.""" |
|
1160 | 1163 | |
|
1161 | 1164 | formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context, |
|
1162 | 1165 | tb_offset) |
|
1163 | 1166 | |
|
1164 | 1167 | colors = self.Colors # just a shorthand + quicker name lookup |
|
1165 | 1168 | colorsnormal = colors.Normal # used a lot |
|
1166 | 1169 | head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal) |
|
1167 | 1170 | structured_traceback_parts = [head] |
|
1168 | 1171 | if py3compat.PY3: |
|
1169 | 1172 | chained_exceptions_tb_offset = 0 |
|
1170 | 1173 | lines_of_context = 3 |
|
1171 | 1174 | formatted_exceptions = formatted_exception |
|
1172 | 1175 | exception = self.get_parts_of_chained_exception(evalue) |
|
1173 | 1176 | if exception: |
|
1174 | 1177 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1175 | 1178 | etype, evalue, etb = exception |
|
1176 | 1179 | else: |
|
1177 | 1180 | evalue = None |
|
1178 | 1181 | chained_exc_ids = set() |
|
1179 | 1182 | while evalue: |
|
1180 | 1183 | formatted_exceptions += self.format_exception_as_a_whole(etype, evalue, etb, lines_of_context, |
|
1181 | 1184 | chained_exceptions_tb_offset) |
|
1182 | 1185 | exception = self.get_parts_of_chained_exception(evalue) |
|
1183 | 1186 | |
|
1184 | 1187 | if exception and not id(exception[1]) in chained_exc_ids: |
|
1185 | 1188 | chained_exc_ids.add(id(exception[1])) # trace exception to avoid infinite 'cause' loop |
|
1186 | 1189 | formatted_exceptions += self.prepare_chained_exception_message(evalue.__cause__) |
|
1187 | 1190 | etype, evalue, etb = exception |
|
1188 | 1191 | else: |
|
1189 | 1192 | evalue = None |
|
1190 | 1193 | |
|
1191 | 1194 | # we want to see exceptions in a reversed order: |
|
1192 | 1195 | # the first exception should be on top |
|
1193 | 1196 | for formatted_exception in reversed(formatted_exceptions): |
|
1194 | 1197 | structured_traceback_parts += formatted_exception |
|
1195 | 1198 | else: |
|
1196 | 1199 | structured_traceback_parts += formatted_exception[0] |
|
1197 | 1200 | |
|
1198 | 1201 | return structured_traceback_parts |
|
1199 | 1202 | |
|
1200 | 1203 | def debugger(self, force=False): |
|
1201 | 1204 | """Call up the pdb debugger if desired, always clean up the tb |
|
1202 | 1205 | reference. |
|
1203 | 1206 | |
|
1204 | 1207 | Keywords: |
|
1205 | 1208 | |
|
1206 | 1209 | - force(False): by default, this routine checks the instance call_pdb |
|
1207 | 1210 | flag and does not actually invoke the debugger if the flag is false. |
|
1208 | 1211 | The 'force' option forces the debugger to activate even if the flag |
|
1209 | 1212 | is false. |
|
1210 | 1213 | |
|
1211 | 1214 | If the call_pdb flag is set, the pdb interactive debugger is |
|
1212 | 1215 | invoked. In all cases, the self.tb reference to the current traceback |
|
1213 | 1216 | is deleted to prevent lingering references which hamper memory |
|
1214 | 1217 | management. |
|
1215 | 1218 | |
|
1216 | 1219 | Note that each call to pdb() does an 'import readline', so if your app |
|
1217 | 1220 | requires a special setup for the readline completers, you'll have to |
|
1218 | 1221 | fix that by hand after invoking the exception handler.""" |
|
1219 | 1222 | |
|
1220 | 1223 | if force or self.call_pdb: |
|
1221 | 1224 | if self.pdb is None: |
|
1222 | 1225 | self.pdb = self.debugger_cls( |
|
1223 | 1226 | self.color_scheme_table.active_scheme_name) |
|
1224 | 1227 | # the system displayhook may have changed, restore the original |
|
1225 | 1228 | # for pdb |
|
1226 | 1229 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
1227 | 1230 | with display_trap: |
|
1228 | 1231 | self.pdb.reset() |
|
1229 | 1232 | # Find the right frame so we don't pop up inside ipython itself |
|
1230 | 1233 | if hasattr(self, 'tb') and self.tb is not None: |
|
1231 | 1234 | etb = self.tb |
|
1232 | 1235 | else: |
|
1233 | 1236 | etb = self.tb = sys.last_traceback |
|
1234 | 1237 | while self.tb is not None and self.tb.tb_next is not None: |
|
1235 | 1238 | self.tb = self.tb.tb_next |
|
1236 | 1239 | if etb and etb.tb_next: |
|
1237 | 1240 | etb = etb.tb_next |
|
1238 | 1241 | self.pdb.botframe = etb.tb_frame |
|
1239 | 1242 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1240 | 1243 | |
|
1241 | 1244 | if hasattr(self, 'tb'): |
|
1242 | 1245 | del self.tb |
|
1243 | 1246 | |
|
1244 | 1247 | def handler(self, info=None): |
|
1245 | 1248 | (etype, evalue, etb) = info or sys.exc_info() |
|
1246 | 1249 | self.tb = etb |
|
1247 | 1250 | ostream = self.ostream |
|
1248 | 1251 | ostream.flush() |
|
1249 | 1252 | ostream.write(self.text(etype, evalue, etb)) |
|
1250 | 1253 | ostream.write('\n') |
|
1251 | 1254 | ostream.flush() |
|
1252 | 1255 | |
|
1253 | 1256 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1254 | 1257 | # out the right info on its own. |
|
1255 | 1258 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1256 | 1259 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1257 | 1260 | if etb is None: |
|
1258 | 1261 | self.handler() |
|
1259 | 1262 | else: |
|
1260 | 1263 | self.handler((etype, evalue, etb)) |
|
1261 | 1264 | try: |
|
1262 | 1265 | self.debugger() |
|
1263 | 1266 | except KeyboardInterrupt: |
|
1264 | 1267 | print("\nKeyboardInterrupt") |
|
1265 | 1268 | |
|
1266 | 1269 | |
|
1267 | 1270 | #---------------------------------------------------------------------------- |
|
1268 | 1271 | class FormattedTB(VerboseTB, ListTB): |
|
1269 | 1272 | """Subclass ListTB but allow calling with a traceback. |
|
1270 | 1273 | |
|
1271 | 1274 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1272 | 1275 | |
|
1273 | 1276 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1274 | 1277 | |
|
1275 | 1278 | Allows a tb_offset to be specified. This is useful for situations where |
|
1276 | 1279 | one needs to remove a number of topmost frames from the traceback (such as |
|
1277 | 1280 | occurs with python programs that themselves execute other python code, |
|
1278 | 1281 | like Python shells). """ |
|
1279 | 1282 | |
|
1280 | 1283 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1281 | 1284 | ostream=None, |
|
1282 | 1285 | tb_offset=0, long_header=False, include_vars=False, |
|
1283 | 1286 | check_cache=None, debugger_cls=None): |
|
1284 | 1287 | |
|
1285 | 1288 | # NEVER change the order of this list. Put new modes at the end: |
|
1286 | 1289 | self.valid_modes = ['Plain', 'Context', 'Verbose'] |
|
1287 | 1290 | self.verbose_modes = self.valid_modes[1:3] |
|
1288 | 1291 | |
|
1289 | 1292 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1290 | 1293 | ostream=ostream, tb_offset=tb_offset, |
|
1291 | 1294 | long_header=long_header, include_vars=include_vars, |
|
1292 | 1295 | check_cache=check_cache, debugger_cls=debugger_cls) |
|
1293 | 1296 | |
|
1294 | 1297 | # Different types of tracebacks are joined with different separators to |
|
1295 | 1298 | # form a single string. They are taken from this dict |
|
1296 | 1299 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1297 | 1300 | # set_mode also sets the tb_join_char attribute |
|
1298 | 1301 | self.set_mode(mode) |
|
1299 | 1302 | |
|
1300 | 1303 | def _extract_tb(self, tb): |
|
1301 | 1304 | if tb: |
|
1302 | 1305 | return traceback.extract_tb(tb) |
|
1303 | 1306 | else: |
|
1304 | 1307 | return None |
|
1305 | 1308 | |
|
1306 | 1309 | def structured_traceback(self, etype, value, tb, tb_offset=None, number_of_lines_of_context=5): |
|
1307 | 1310 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1308 | 1311 | mode = self.mode |
|
1309 | 1312 | if mode in self.verbose_modes: |
|
1310 | 1313 | # Verbose modes need a full traceback |
|
1311 | 1314 | return VerboseTB.structured_traceback( |
|
1312 | 1315 | self, etype, value, tb, tb_offset, number_of_lines_of_context |
|
1313 | 1316 | ) |
|
1314 | 1317 | else: |
|
1315 | 1318 | # We must check the source cache because otherwise we can print |
|
1316 | 1319 | # out-of-date source code. |
|
1317 | 1320 | self.check_cache() |
|
1318 | 1321 | # Now we can extract and format the exception |
|
1319 | 1322 | elist = self._extract_tb(tb) |
|
1320 | 1323 | return ListTB.structured_traceback( |
|
1321 | 1324 | self, etype, value, elist, tb_offset, number_of_lines_of_context |
|
1322 | 1325 | ) |
|
1323 | 1326 | |
|
1324 | 1327 | def stb2text(self, stb): |
|
1325 | 1328 | """Convert a structured traceback (a list) to a string.""" |
|
1326 | 1329 | return self.tb_join_char.join(stb) |
|
1327 | 1330 | |
|
1328 | 1331 | |
|
1329 | 1332 | def set_mode(self, mode=None): |
|
1330 | 1333 | """Switch to the desired mode. |
|
1331 | 1334 | |
|
1332 | 1335 | If mode is not specified, cycles through the available modes.""" |
|
1333 | 1336 | |
|
1334 | 1337 | if not mode: |
|
1335 | 1338 | new_idx = (self.valid_modes.index(self.mode) + 1 ) % \ |
|
1336 | 1339 | len(self.valid_modes) |
|
1337 | 1340 | self.mode = self.valid_modes[new_idx] |
|
1338 | 1341 | elif mode not in self.valid_modes: |
|
1339 | 1342 | raise ValueError('Unrecognized mode in FormattedTB: <' + mode + '>\n' |
|
1340 | 1343 | 'Valid modes: ' + str(self.valid_modes)) |
|
1341 | 1344 | else: |
|
1342 | 1345 | self.mode = mode |
|
1343 | 1346 | # include variable details only in 'Verbose' mode |
|
1344 | 1347 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1345 | 1348 | # Set the join character for generating text tracebacks |
|
1346 | 1349 | self.tb_join_char = self._join_chars[self.mode] |
|
1347 | 1350 | |
|
1348 | 1351 | # some convenient shortcuts |
|
1349 | 1352 | def plain(self): |
|
1350 | 1353 | self.set_mode(self.valid_modes[0]) |
|
1351 | 1354 | |
|
1352 | 1355 | def context(self): |
|
1353 | 1356 | self.set_mode(self.valid_modes[1]) |
|
1354 | 1357 | |
|
1355 | 1358 | def verbose(self): |
|
1356 | 1359 | self.set_mode(self.valid_modes[2]) |
|
1357 | 1360 | |
|
1358 | 1361 | |
|
1359 | 1362 | #---------------------------------------------------------------------------- |
|
1360 | 1363 | class AutoFormattedTB(FormattedTB): |
|
1361 | 1364 | """A traceback printer which can be called on the fly. |
|
1362 | 1365 | |
|
1363 | 1366 | It will find out about exceptions by itself. |
|
1364 | 1367 | |
|
1365 | 1368 | A brief example:: |
|
1366 | 1369 | |
|
1367 | 1370 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1368 | 1371 | try: |
|
1369 | 1372 | ... |
|
1370 | 1373 | except: |
|
1371 | 1374 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1372 | 1375 | """ |
|
1373 | 1376 | |
|
1374 | 1377 | def __call__(self, etype=None, evalue=None, etb=None, |
|
1375 | 1378 | out=None, tb_offset=None): |
|
1376 | 1379 | """Print out a formatted exception traceback. |
|
1377 | 1380 | |
|
1378 | 1381 | Optional arguments: |
|
1379 | 1382 | - out: an open file-like object to direct output to. |
|
1380 | 1383 | |
|
1381 | 1384 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1382 | 1385 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1383 | 1386 | given at initialization time. """ |
|
1384 | 1387 | |
|
1385 | 1388 | if out is None: |
|
1386 | 1389 | out = self.ostream |
|
1387 | 1390 | out.flush() |
|
1388 | 1391 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1389 | 1392 | out.write('\n') |
|
1390 | 1393 | out.flush() |
|
1391 | 1394 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1392 | 1395 | # that to the clients. |
|
1393 | 1396 | try: |
|
1394 | 1397 | self.debugger() |
|
1395 | 1398 | except KeyboardInterrupt: |
|
1396 | 1399 | print("\nKeyboardInterrupt") |
|
1397 | 1400 | |
|
1398 | 1401 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1399 | 1402 | tb_offset=None, number_of_lines_of_context=5): |
|
1400 | 1403 | if etype is None: |
|
1401 | 1404 | etype, value, tb = sys.exc_info() |
|
1402 | 1405 | self.tb = tb |
|
1403 | 1406 | return FormattedTB.structured_traceback( |
|
1404 | 1407 | self, etype, value, tb, tb_offset, number_of_lines_of_context) |
|
1405 | 1408 | |
|
1406 | 1409 | |
|
1407 | 1410 | #--------------------------------------------------------------------------- |
|
1408 | 1411 | |
|
1409 | 1412 | # A simple class to preserve Nathan's original functionality. |
|
1410 | 1413 | class ColorTB(FormattedTB): |
|
1411 | 1414 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1412 | 1415 | |
|
1413 | 1416 | def __init__(self, color_scheme='Linux', call_pdb=0, **kwargs): |
|
1414 | 1417 | FormattedTB.__init__(self, color_scheme=color_scheme, |
|
1415 | 1418 | call_pdb=call_pdb, **kwargs) |
|
1416 | 1419 | |
|
1417 | 1420 | |
|
1418 | 1421 | class SyntaxTB(ListTB): |
|
1419 | 1422 | """Extension which holds some state: the last exception value""" |
|
1420 | 1423 | |
|
1421 | 1424 | def __init__(self, color_scheme='NoColor'): |
|
1422 | 1425 | ListTB.__init__(self, color_scheme) |
|
1423 | 1426 | self.last_syntax_error = None |
|
1424 | 1427 | |
|
1425 | 1428 | def __call__(self, etype, value, elist): |
|
1426 | 1429 | self.last_syntax_error = value |
|
1427 | 1430 | |
|
1428 | 1431 | ListTB.__call__(self, etype, value, elist) |
|
1429 | 1432 | |
|
1430 | 1433 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
1431 | 1434 | context=5): |
|
1432 | 1435 | # If the source file has been edited, the line in the syntax error can |
|
1433 | 1436 | # be wrong (retrieved from an outdated cache). This replaces it with |
|
1434 | 1437 | # the current value. |
|
1435 | 1438 | if isinstance(value, SyntaxError) \ |
|
1436 | 1439 | and isinstance(value.filename, py3compat.string_types) \ |
|
1437 | 1440 | and isinstance(value.lineno, int): |
|
1438 | 1441 | linecache.checkcache(value.filename) |
|
1439 | 1442 | newtext = ulinecache.getline(value.filename, value.lineno) |
|
1440 | 1443 | if newtext: |
|
1441 | 1444 | value.text = newtext |
|
1442 | 1445 | self.last_syntax_error = value |
|
1443 | 1446 | return super(SyntaxTB, self).structured_traceback(etype, value, elist, |
|
1444 | 1447 | tb_offset=tb_offset, context=context) |
|
1445 | 1448 | |
|
1446 | 1449 | def clear_err_state(self): |
|
1447 | 1450 | """Return the current error state and clear it""" |
|
1448 | 1451 | e = self.last_syntax_error |
|
1449 | 1452 | self.last_syntax_error = None |
|
1450 | 1453 | return e |
|
1451 | 1454 | |
|
1452 | 1455 | def stb2text(self, stb): |
|
1453 | 1456 | """Convert a structured traceback (a list) to a string.""" |
|
1454 | 1457 | return ''.join(stb) |
|
1455 | 1458 | |
|
1456 | 1459 | |
|
1457 | 1460 | # some internal-use functions |
|
1458 | 1461 | def text_repr(value): |
|
1459 | 1462 | """Hopefully pretty robust repr equivalent.""" |
|
1460 | 1463 | # this is pretty horrible but should always return *something* |
|
1461 | 1464 | try: |
|
1462 | 1465 | return pydoc.text.repr(value) |
|
1463 | 1466 | except KeyboardInterrupt: |
|
1464 | 1467 | raise |
|
1465 | 1468 | except: |
|
1466 | 1469 | try: |
|
1467 | 1470 | return repr(value) |
|
1468 | 1471 | except KeyboardInterrupt: |
|
1469 | 1472 | raise |
|
1470 | 1473 | except: |
|
1471 | 1474 | try: |
|
1472 | 1475 | # all still in an except block so we catch |
|
1473 | 1476 | # getattr raising |
|
1474 | 1477 | name = getattr(value, '__name__', None) |
|
1475 | 1478 | if name: |
|
1476 | 1479 | # ick, recursion |
|
1477 | 1480 | return text_repr(name) |
|
1478 | 1481 | klass = getattr(value, '__class__', None) |
|
1479 | 1482 | if klass: |
|
1480 | 1483 | return '%s instance' % text_repr(klass) |
|
1481 | 1484 | except KeyboardInterrupt: |
|
1482 | 1485 | raise |
|
1483 | 1486 | except: |
|
1484 | 1487 | return 'UNRECOVERABLE REPR FAILURE' |
|
1485 | 1488 | |
|
1486 | 1489 | |
|
1487 | 1490 | def eqrepr(value, repr=text_repr): |
|
1488 | 1491 | return '=%s' % repr(value) |
|
1489 | 1492 | |
|
1490 | 1493 | |
|
1491 | 1494 | def nullrepr(value, repr=text_repr): |
|
1492 | 1495 | return '' |
@@ -1,571 +1,578 b'' | |||
|
1 | 1 | """IPython terminal interface using prompt_toolkit""" |
|
2 | 2 | from __future__ import print_function |
|
3 | 3 | |
|
4 | 4 | import os |
|
5 | 5 | import sys |
|
6 | 6 | import signal |
|
7 | 7 | from warnings import warn |
|
8 | 8 | |
|
9 | 9 | from IPython.core.error import TryNext |
|
10 | 10 | from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC |
|
11 | 11 | from IPython.utils.py3compat import PY3, cast_unicode_py2, input |
|
12 | 12 | from IPython.utils.terminal import toggle_set_term_title, set_term_title |
|
13 | 13 | from IPython.utils.process import abbrev_cwd |
|
14 | 14 | from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum |
|
15 | 15 | |
|
16 | 16 | from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER, EditingMode |
|
17 | 17 | from prompt_toolkit.filters import (HasFocus, HasSelection, Condition, |
|
18 | 18 | ViInsertMode, EmacsInsertMode, IsDone, HasCompletions) |
|
19 | 19 | from prompt_toolkit.filters.cli import ViMode |
|
20 | 20 | from prompt_toolkit.history import InMemoryHistory |
|
21 | 21 | from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout |
|
22 | 22 | from prompt_toolkit.interface import CommandLineInterface |
|
23 | 23 | from prompt_toolkit.key_binding.manager import KeyBindingManager |
|
24 | 24 | from prompt_toolkit.keys import Keys |
|
25 | 25 | from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor |
|
26 | 26 | from prompt_toolkit.styles import PygmentsStyle, DynamicStyle |
|
27 | 27 | from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline |
|
28 | 28 | |
|
29 | 29 | from pygments.styles import get_style_by_name, get_all_styles |
|
30 | 30 | from pygments.token import Token |
|
31 | 31 | |
|
32 | 32 | from .debugger import TerminalPdb, Pdb |
|
33 | 33 | from .magics import TerminalMagics |
|
34 | 34 | from .pt_inputhooks import get_inputhook_func |
|
35 | 35 | from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook |
|
36 | 36 | from .ptutils import IPythonPTCompleter, IPythonPTLexer |
|
37 | 37 | |
|
38 | 38 | DISPLAY_BANNER_DEPRECATED = object() |
|
39 | 39 | |
|
40 | 40 | |
|
41 | 41 | from pygments.style import Style |
|
42 | 42 | |
|
43 | 43 | class _NoStyle(Style): pass |
|
44 | 44 | |
|
45 | 45 | |
|
46 | 46 | |
|
47 | 47 | _style_overrides_light_bg = { |
|
48 | 48 | Token.Prompt: '#0000ff', |
|
49 | 49 | Token.PromptNum: '#0000ee bold', |
|
50 | 50 | Token.OutPrompt: '#cc0000', |
|
51 | 51 | Token.OutPromptNum: '#bb0000 bold', |
|
52 | 52 | } |
|
53 | 53 | |
|
54 | 54 | _style_overrides_linux = { |
|
55 | 55 | Token.Prompt: '#00cc00', |
|
56 | 56 | Token.PromptNum: '#00bb00 bold', |
|
57 | 57 | Token.OutPrompt: '#cc0000', |
|
58 | 58 | Token.OutPromptNum: '#bb0000 bold', |
|
59 | 59 | } |
|
60 | 60 | |
|
61 | 61 | |
|
62 | 62 | |
|
63 | 63 | def get_default_editor(): |
|
64 | 64 | try: |
|
65 | 65 | ed = os.environ['EDITOR'] |
|
66 | 66 | if not PY3: |
|
67 | 67 | ed = ed.decode() |
|
68 | 68 | return ed |
|
69 | 69 | except KeyError: |
|
70 | 70 | pass |
|
71 | 71 | except UnicodeError: |
|
72 | 72 | warn("$EDITOR environment variable is not pure ASCII. Using platform " |
|
73 | 73 | "default editor.") |
|
74 | 74 | |
|
75 | 75 | if os.name == 'posix': |
|
76 | 76 | return 'vi' # the only one guaranteed to be there! |
|
77 | 77 | else: |
|
78 | 78 | return 'notepad' # same in Windows! |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | if sys.stdin and sys.stdout and sys.stderr: |
|
82 | 82 | _is_tty = (sys.stdin.isatty()) and (sys.stdout.isatty()) and (sys.stderr.isatty()) |
|
83 | 83 | else: |
|
84 | 84 | _is_tty = False |
|
85 | 85 | |
|
86 | 86 | |
|
87 | 87 | _use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty) |
|
88 | 88 | |
|
89 | 89 | class TerminalInteractiveShell(InteractiveShell): |
|
90 | 90 | colors_force = True |
|
91 | 91 | |
|
92 | 92 | space_for_menu = Integer(6, help='Number of line at the bottom of the screen ' |
|
93 | 93 | 'to reserve for the completion menu' |
|
94 | 94 | ).tag(config=True) |
|
95 | 95 | |
|
96 | 96 | def _space_for_menu_changed(self, old, new): |
|
97 | 97 | self._update_layout() |
|
98 | 98 | |
|
99 | 99 | pt_cli = None |
|
100 | 100 | debugger_history = None |
|
101 | 101 | |
|
102 | 102 | simple_prompt = Bool(_use_simple_prompt, |
|
103 | 103 | help="""Use `raw_input` for the REPL, without completion, multiline input, and prompt colors. |
|
104 | 104 | |
|
105 | 105 | Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are: |
|
106 | 106 | IPython own testing machinery, and emacs inferior-shell integration through elpy. |
|
107 | 107 | |
|
108 | 108 | This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT` |
|
109 | 109 | environment variable is set, or the current terminal is not a tty. |
|
110 | 110 | |
|
111 | 111 | """ |
|
112 | 112 | ).tag(config=True) |
|
113 | 113 | |
|
114 | 114 | @property |
|
115 | 115 | def debugger_cls(self): |
|
116 | 116 | return Pdb if self.simple_prompt else TerminalPdb |
|
117 | 117 | |
|
118 | 118 | confirm_exit = Bool(True, |
|
119 | 119 | help=""" |
|
120 | 120 | Set to confirm when you try to exit IPython with an EOF (Control-D |
|
121 | 121 | in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit', |
|
122 | 122 | you can force a direct exit without any confirmation.""", |
|
123 | 123 | ).tag(config=True) |
|
124 | 124 | |
|
125 | 125 | editing_mode = Unicode('emacs', |
|
126 | 126 | help="Shortcut style to use at the prompt. 'vi' or 'emacs'.", |
|
127 | 127 | ).tag(config=True) |
|
128 | 128 | |
|
129 | 129 | mouse_support = Bool(False, |
|
130 | 130 | help="Enable mouse support in the prompt" |
|
131 | 131 | ).tag(config=True) |
|
132 | 132 | |
|
133 | 133 | highlighting_style = Unicode('legacy', |
|
134 | 134 | help="The name of a Pygments style to use for syntax highlighting: \n %s" % ', '.join(get_all_styles()) |
|
135 | 135 | ).tag(config=True) |
|
136 | 136 | |
|
137 | 137 | |
|
138 | 138 | @observe('highlighting_style') |
|
139 | 139 | @observe('colors') |
|
140 | 140 | def _highlighting_style_changed(self, change): |
|
141 | 141 | self.refresh_style() |
|
142 | 142 | |
|
143 | 143 | def refresh_style(self): |
|
144 | 144 | self._style = self._make_style_from_name(self.highlighting_style) |
|
145 | 145 | |
|
146 | 146 | |
|
147 | 147 | highlighting_style_overrides = Dict( |
|
148 | 148 | help="Override highlighting format for specific tokens" |
|
149 | 149 | ).tag(config=True) |
|
150 | 150 | |
|
151 | 151 | editor = Unicode(get_default_editor(), |
|
152 | 152 | help="Set the editor used by IPython (default to $EDITOR/vi/notepad)." |
|
153 | 153 | ).tag(config=True) |
|
154 | 154 | |
|
155 | 155 | prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True) |
|
156 | 156 | |
|
157 | 157 | prompts = Instance(Prompts) |
|
158 | 158 | |
|
159 | 159 | @default('prompts') |
|
160 | 160 | def _prompts_default(self): |
|
161 | 161 | return self.prompts_class(self) |
|
162 | 162 | |
|
163 | 163 | @observe('prompts') |
|
164 | 164 | def _(self, change): |
|
165 | 165 | self._update_layout() |
|
166 | 166 | |
|
167 | 167 | @default('displayhook_class') |
|
168 | 168 | def _displayhook_class_default(self): |
|
169 | 169 | return RichPromptDisplayHook |
|
170 | 170 | |
|
171 | 171 | term_title = Bool(True, |
|
172 | 172 | help="Automatically set the terminal title" |
|
173 | 173 | ).tag(config=True) |
|
174 | 174 | |
|
175 | 175 | # Leaving that for beta/rc tester, shoudl remove for 5.0.0 final. |
|
176 | 176 | display_completions_in_columns = Bool(None, |
|
177 | 177 | help="DEPRECATED", allow_none=True |
|
178 | 178 | ).tag(config=True) |
|
179 | 179 | |
|
180 | 180 | @observe('display_completions_in_columns') |
|
181 | 181 | def _display_completions_in_columns_changed(self, new): |
|
182 | 182 | raise DeprecationWarning("The `display_completions_in_columns` Boolean has been replaced by the enum `display_completions`" |
|
183 | 183 | "with the following acceptable value: 'column', 'multicolumn','readlinelike'. ") |
|
184 | 184 | |
|
185 | 185 | display_completions = Enum(('column', 'multicolumn','readlinelike'), default_value='multicolumn').tag(config=True) |
|
186 | 186 | |
|
187 | 187 | highlight_matching_brackets = Bool(True, |
|
188 | 188 | help="Highlight matching brackets .", |
|
189 | 189 | ).tag(config=True) |
|
190 | 190 | |
|
191 | 191 | @observe('term_title') |
|
192 | 192 | def init_term_title(self, change=None): |
|
193 | 193 | # Enable or disable the terminal title. |
|
194 | 194 | if self.term_title: |
|
195 | 195 | toggle_set_term_title(True) |
|
196 | 196 | set_term_title('IPython: ' + abbrev_cwd()) |
|
197 | 197 | else: |
|
198 | 198 | toggle_set_term_title(False) |
|
199 | 199 | |
|
200 | 200 | def init_display_formatter(self): |
|
201 | 201 | super(TerminalInteractiveShell, self).init_display_formatter() |
|
202 | 202 | # terminal only supports plain text |
|
203 | 203 | self.display_formatter.active_types = ['text/plain'] |
|
204 | 204 | |
|
205 | 205 | def init_prompt_toolkit_cli(self): |
|
206 | 206 | self._app = None |
|
207 | 207 | if self.simple_prompt: |
|
208 | 208 | # Fall back to plain non-interactive output for tests. |
|
209 | 209 | # This is very limited, and only accepts a single line. |
|
210 | 210 | def prompt(): |
|
211 | 211 | return cast_unicode_py2(input('In [%d]: ' % self.execution_count)) |
|
212 | 212 | self.prompt_for_code = prompt |
|
213 | 213 | return |
|
214 | 214 | |
|
215 | 215 | kbmanager = KeyBindingManager.for_prompt() |
|
216 | 216 | insert_mode = ViInsertMode() | EmacsInsertMode() |
|
217 | 217 | # Ctrl+J == Enter, seemingly |
|
218 | 218 | @kbmanager.registry.add_binding(Keys.ControlJ, |
|
219 | 219 | filter=(HasFocus(DEFAULT_BUFFER) |
|
220 | 220 | & ~HasSelection() |
|
221 | 221 | & insert_mode |
|
222 | 222 | )) |
|
223 | 223 | def _(event): |
|
224 | 224 | b = event.current_buffer |
|
225 | 225 | d = b.document |
|
226 | 226 | |
|
227 | 227 | if b.complete_state: |
|
228 | 228 | cc = b.complete_state.current_completion |
|
229 | 229 | if cc: |
|
230 | 230 | b.apply_completion(cc) |
|
231 | 231 | else: |
|
232 | 232 | b.cancel_completion() |
|
233 | 233 | return |
|
234 | 234 | |
|
235 | 235 | if not (d.on_last_line or d.cursor_position_row >= d.line_count |
|
236 | 236 | - d.empty_line_count_at_the_end()): |
|
237 | 237 | b.newline() |
|
238 | 238 | return |
|
239 | 239 | |
|
240 | 240 | status, indent = self.input_splitter.check_complete(d.text + '\n') |
|
241 | 241 | |
|
242 | 242 | if (status != 'incomplete') and b.accept_action.is_returnable: |
|
243 | 243 | b.accept_action.validate_and_handle(event.cli, b) |
|
244 | 244 | else: |
|
245 | 245 | b.insert_text('\n' + (' ' * (indent or 0))) |
|
246 | 246 | |
|
247 | 247 | @kbmanager.registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER))) |
|
248 | 248 | def _previous_history_or_previous_completion(event): |
|
249 | 249 | """ |
|
250 | 250 | Control-P in vi edit mode on readline is history next, unlike default prompt toolkit. |
|
251 | 251 | |
|
252 | 252 | If completer is open this still select previous completion. |
|
253 | 253 | """ |
|
254 | 254 | event.current_buffer.auto_up() |
|
255 | 255 | |
|
256 | 256 | @kbmanager.registry.add_binding(Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER))) |
|
257 | 257 | def _next_history_or_next_completion(event): |
|
258 | 258 | """ |
|
259 | 259 | Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit. |
|
260 | 260 | |
|
261 | 261 | If completer is open this still select next completion. |
|
262 | 262 | """ |
|
263 | 263 | event.current_buffer.auto_down() |
|
264 | 264 | |
|
265 | 265 | @kbmanager.registry.add_binding(Keys.ControlG, filter=( |
|
266 | 266 | HasFocus(DEFAULT_BUFFER) & HasCompletions() |
|
267 | 267 | )) |
|
268 | 268 | def _dismiss_completion(event): |
|
269 | 269 | b = event.current_buffer |
|
270 | 270 | if b.complete_state: |
|
271 | 271 | b.cancel_completion() |
|
272 | 272 | |
|
273 | 273 | @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) |
|
274 | 274 | def _reset_buffer(event): |
|
275 | 275 | b = event.current_buffer |
|
276 | 276 | if b.complete_state: |
|
277 | 277 | b.cancel_completion() |
|
278 | 278 | else: |
|
279 | 279 | b.reset() |
|
280 | 280 | |
|
281 | 281 | @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)) |
|
282 | 282 | def _reset_search_buffer(event): |
|
283 | 283 | if event.current_buffer.document.text: |
|
284 | 284 | event.current_buffer.reset() |
|
285 | 285 | else: |
|
286 | 286 | event.cli.push_focus(DEFAULT_BUFFER) |
|
287 | 287 | |
|
288 | 288 | supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) |
|
289 | 289 | |
|
290 | 290 | @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend) |
|
291 | 291 | def _suspend_to_bg(event): |
|
292 | 292 | event.cli.suspend_to_background() |
|
293 | 293 | |
|
294 | 294 | @Condition |
|
295 | 295 | def cursor_in_leading_ws(cli): |
|
296 | 296 | before = cli.application.buffer.document.current_line_before_cursor |
|
297 | 297 | return (not before) or before.isspace() |
|
298 | 298 | |
|
299 | 299 | # Ctrl+I == Tab |
|
300 | 300 | @kbmanager.registry.add_binding(Keys.ControlI, |
|
301 | 301 | filter=(HasFocus(DEFAULT_BUFFER) |
|
302 | 302 | & ~HasSelection() |
|
303 | 303 | & insert_mode |
|
304 | 304 | & cursor_in_leading_ws |
|
305 | 305 | )) |
|
306 | 306 | def _indent_buffer(event): |
|
307 | 307 | event.current_buffer.insert_text(' ' * 4) |
|
308 | 308 | |
|
309 | 309 | |
|
310 | 310 | if self.display_completions == 'readlinelike': |
|
311 | 311 | @kbmanager.registry.add_binding(Keys.ControlI, |
|
312 | 312 | filter=(HasFocus(DEFAULT_BUFFER) |
|
313 | 313 | & ~HasSelection() |
|
314 | 314 | & insert_mode |
|
315 | 315 | & ~cursor_in_leading_ws |
|
316 | 316 | )) |
|
317 | 317 | def _disaply_compl(ev): |
|
318 | 318 | display_completions_like_readline(ev) |
|
319 | 319 | |
|
320 | 320 | |
|
321 | 321 | if sys.platform == 'win32': |
|
322 | 322 | from IPython.lib.clipboard import (ClipboardEmpty, |
|
323 | 323 | win32_clipboard_get, tkinter_clipboard_get) |
|
324 | 324 | @kbmanager.registry.add_binding(Keys.ControlV, |
|
325 | 325 | filter=(HasFocus(DEFAULT_BUFFER) & ~ViMode())) |
|
326 | 326 | def _paste(event): |
|
327 | 327 | try: |
|
328 | 328 | text = win32_clipboard_get() |
|
329 | 329 | except TryNext: |
|
330 | 330 | try: |
|
331 | 331 | text = tkinter_clipboard_get() |
|
332 | 332 | except (TryNext, ClipboardEmpty): |
|
333 | 333 | return |
|
334 | 334 | except ClipboardEmpty: |
|
335 | 335 | return |
|
336 | 336 | event.current_buffer.insert_text(text.replace('\t', ' ' * 4)) |
|
337 | 337 | |
|
338 | 338 | # Pre-populate history from IPython's history database |
|
339 | 339 | history = InMemoryHistory() |
|
340 | 340 | last_cell = u"" |
|
341 | 341 | for __, ___, cell in self.history_manager.get_tail(self.history_load_length, |
|
342 | 342 | include_latest=True): |
|
343 | 343 | # Ignore blank lines and consecutive duplicates |
|
344 | 344 | cell = cell.rstrip() |
|
345 | 345 | if cell and (cell != last_cell): |
|
346 | 346 | history.append(cell) |
|
347 | 347 | |
|
348 | 348 | self._style = self._make_style_from_name(self.highlighting_style) |
|
349 | 349 | style = DynamicStyle(lambda: self._style) |
|
350 | 350 | |
|
351 | 351 | editing_mode = getattr(EditingMode, self.editing_mode.upper()) |
|
352 | 352 | |
|
353 | 353 | self._app = create_prompt_application( |
|
354 | 354 | editing_mode=editing_mode, |
|
355 | 355 | key_bindings_registry=kbmanager.registry, |
|
356 | 356 | history=history, |
|
357 | 357 | completer=IPythonPTCompleter(self.Completer), |
|
358 | 358 | enable_history_search=True, |
|
359 | 359 | style=style, |
|
360 | 360 | mouse_support=self.mouse_support, |
|
361 | 361 | **self._layout_options() |
|
362 | 362 | ) |
|
363 | 363 | self._eventloop = create_eventloop(self.inputhook) |
|
364 | 364 | self.pt_cli = CommandLineInterface(self._app, eventloop=self._eventloop) |
|
365 | 365 | |
|
366 | 366 | def _make_style_from_name(self, name): |
|
367 | 367 | """ |
|
368 | 368 | Small wrapper that make an IPython compatible style from a style name |
|
369 | 369 | |
|
370 | 370 | We need that to add style for prompt ... etc. |
|
371 | 371 | """ |
|
372 | style_overrides = {} | |
|
372 | 373 | if name == 'legacy': |
|
373 | 374 | legacy = self.colors.lower() |
|
374 | 375 | if legacy == 'linux': |
|
375 | 376 | style_cls = get_style_by_name('monokai') |
|
376 | 377 | style_overrides = _style_overrides_linux |
|
377 | 378 | elif legacy == 'lightbg': |
|
378 | 379 | style_overrides = _style_overrides_light_bg |
|
379 |
style_cls = get_style_by_name(' |
|
|
380 | style_cls = get_style_by_name('pastie') | |
|
381 | elif legacy == 'neutral': | |
|
380 | 382 | # The default theme needs to be visible on both a dark background |
|
381 | 383 | # and a light background, because we can't tell what the terminal |
|
382 | 384 | # looks like. These tweaks to the default theme help with that. |
|
385 | style_cls = get_style_by_name('default') | |
|
383 | 386 | style_overrides.update({ |
|
384 | 387 | Token.Number: '#007700', |
|
385 | 388 | Token.Operator: 'noinherit', |
|
386 | 389 | Token.String: '#BB6622', |
|
387 | 390 | Token.Name.Function: '#2080D0', |
|
388 | 391 | Token.Name.Class: 'bold #2080D0', |
|
389 | 392 | Token.Name.Namespace: 'bold #2080D0', |
|
393 | Token.Prompt: '#009900', | |
|
394 | Token.PromptNum: '#00ff00 bold', | |
|
395 | Token.OutPrompt: '#990000', | |
|
396 | Token.OutPromptNum: '#ff0000 bold', | |
|
390 | 397 | }) |
|
391 | 398 | elif legacy =='nocolor': |
|
392 | 399 | style_cls=_NoStyle |
|
393 | 400 | style_overrides = {} |
|
394 | 401 | else : |
|
395 | 402 | raise ValueError('Got unknown colors: ', legacy) |
|
396 | 403 | else : |
|
397 | 404 | style_cls = get_style_by_name(name) |
|
398 | 405 | style_overrides = { |
|
399 | 406 | Token.Prompt: '#009900', |
|
400 | 407 | Token.PromptNum: '#00ff00 bold', |
|
401 | 408 | Token.OutPrompt: '#990000', |
|
402 | 409 | Token.OutPromptNum: '#ff0000 bold', |
|
403 | 410 | } |
|
404 | 411 | style_overrides.update(self.highlighting_style_overrides) |
|
405 | 412 | style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls, |
|
406 | 413 | style_dict=style_overrides) |
|
407 | 414 | |
|
408 | 415 | return style |
|
409 | 416 | |
|
410 | 417 | def _layout_options(self): |
|
411 | 418 | """ |
|
412 | 419 | Return the current layout option for the current Terminal InteractiveShell |
|
413 | 420 | """ |
|
414 | 421 | return { |
|
415 | 422 | 'lexer':IPythonPTLexer(), |
|
416 | 423 | 'reserve_space_for_menu':self.space_for_menu, |
|
417 | 424 | 'get_prompt_tokens':self.prompts.in_prompt_tokens, |
|
418 | 425 | 'get_continuation_tokens':self.prompts.continuation_prompt_tokens, |
|
419 | 426 | 'multiline':True, |
|
420 | 427 | 'display_completions_in_columns': (self.display_completions == 'multicolumn'), |
|
421 | 428 | |
|
422 | 429 | # Highlight matching brackets, but only when this setting is |
|
423 | 430 | # enabled, and only when the DEFAULT_BUFFER has the focus. |
|
424 | 431 | 'extra_input_processors': [ConditionalProcessor( |
|
425 | 432 | processor=HighlightMatchingBracketProcessor(chars='[](){}'), |
|
426 | 433 | filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() & |
|
427 | 434 | Condition(lambda cli: self.highlight_matching_brackets))], |
|
428 | 435 | } |
|
429 | 436 | |
|
430 | 437 | def _update_layout(self): |
|
431 | 438 | """ |
|
432 | 439 | Ask for a re computation of the application layout, if for example , |
|
433 | 440 | some configuration options have changed. |
|
434 | 441 | """ |
|
435 | 442 | if getattr(self, '._app', None): |
|
436 | 443 | self._app.layout = create_prompt_layout(**self._layout_options()) |
|
437 | 444 | |
|
438 | 445 | def prompt_for_code(self): |
|
439 | 446 | document = self.pt_cli.run( |
|
440 | 447 | pre_run=self.pre_prompt, reset_current_buffer=True) |
|
441 | 448 | return document.text |
|
442 | 449 | |
|
443 | 450 | def init_io(self): |
|
444 | 451 | if sys.platform not in {'win32', 'cli'}: |
|
445 | 452 | return |
|
446 | 453 | |
|
447 | 454 | import win_unicode_console |
|
448 | 455 | import colorama |
|
449 | 456 | |
|
450 | 457 | win_unicode_console.enable() |
|
451 | 458 | colorama.init() |
|
452 | 459 | |
|
453 | 460 | # For some reason we make these wrappers around stdout/stderr. |
|
454 | 461 | # For now, we need to reset them so all output gets coloured. |
|
455 | 462 | # https://github.com/ipython/ipython/issues/8669 |
|
456 | 463 | from IPython.utils import io |
|
457 | 464 | io.stdout = io.IOStream(sys.stdout) |
|
458 | 465 | io.stderr = io.IOStream(sys.stderr) |
|
459 | 466 | |
|
460 | 467 | def init_magics(self): |
|
461 | 468 | super(TerminalInteractiveShell, self).init_magics() |
|
462 | 469 | self.register_magics(TerminalMagics) |
|
463 | 470 | |
|
464 | 471 | def init_alias(self): |
|
465 | 472 | # The parent class defines aliases that can be safely used with any |
|
466 | 473 | # frontend. |
|
467 | 474 | super(TerminalInteractiveShell, self).init_alias() |
|
468 | 475 | |
|
469 | 476 | # Now define aliases that only make sense on the terminal, because they |
|
470 | 477 | # need direct access to the console in a way that we can't emulate in |
|
471 | 478 | # GUI or web frontend |
|
472 | 479 | if os.name == 'posix': |
|
473 | 480 | for cmd in ['clear', 'more', 'less', 'man']: |
|
474 | 481 | self.alias_manager.soft_define_alias(cmd, cmd) |
|
475 | 482 | |
|
476 | 483 | |
|
477 | 484 | def __init__(self, *args, **kwargs): |
|
478 | 485 | super(TerminalInteractiveShell, self).__init__(*args, **kwargs) |
|
479 | 486 | self.init_prompt_toolkit_cli() |
|
480 | 487 | self.init_term_title() |
|
481 | 488 | self.keep_running = True |
|
482 | 489 | |
|
483 | 490 | self.debugger_history = InMemoryHistory() |
|
484 | 491 | |
|
485 | 492 | def ask_exit(self): |
|
486 | 493 | self.keep_running = False |
|
487 | 494 | |
|
488 | 495 | rl_next_input = None |
|
489 | 496 | |
|
490 | 497 | def pre_prompt(self): |
|
491 | 498 | if self.rl_next_input: |
|
492 | 499 | self.pt_cli.application.buffer.text = cast_unicode_py2(self.rl_next_input) |
|
493 | 500 | self.rl_next_input = None |
|
494 | 501 | |
|
495 | 502 | def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED): |
|
496 | 503 | |
|
497 | 504 | if display_banner is not DISPLAY_BANNER_DEPRECATED: |
|
498 | 505 | warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2) |
|
499 | 506 | |
|
500 | 507 | while self.keep_running: |
|
501 | 508 | print(self.separate_in, end='') |
|
502 | 509 | |
|
503 | 510 | try: |
|
504 | 511 | code = self.prompt_for_code() |
|
505 | 512 | except EOFError: |
|
506 | 513 | if (not self.confirm_exit) \ |
|
507 | 514 | or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'): |
|
508 | 515 | self.ask_exit() |
|
509 | 516 | |
|
510 | 517 | else: |
|
511 | 518 | if code: |
|
512 | 519 | self.run_cell(code, store_history=True) |
|
513 | 520 | |
|
514 | 521 | def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED): |
|
515 | 522 | # An extra layer of protection in case someone mashing Ctrl-C breaks |
|
516 | 523 | # out of our internal code. |
|
517 | 524 | if display_banner is not DISPLAY_BANNER_DEPRECATED: |
|
518 | 525 | warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2) |
|
519 | 526 | while True: |
|
520 | 527 | try: |
|
521 | 528 | self.interact() |
|
522 | 529 | break |
|
523 | 530 | except KeyboardInterrupt: |
|
524 | 531 | print("\nKeyboardInterrupt escaped interact()\n") |
|
525 | 532 | |
|
526 | 533 | if hasattr(self, '_eventloop'): |
|
527 | 534 | self._eventloop.close() |
|
528 | 535 | |
|
529 | 536 | _inputhook = None |
|
530 | 537 | def inputhook(self, context): |
|
531 | 538 | if self._inputhook is not None: |
|
532 | 539 | self._inputhook(context) |
|
533 | 540 | |
|
534 | 541 | def enable_gui(self, gui=None): |
|
535 | 542 | if gui: |
|
536 | 543 | self._inputhook = get_inputhook_func(gui) |
|
537 | 544 | else: |
|
538 | 545 | self._inputhook = None |
|
539 | 546 | |
|
540 | 547 | # Run !system commands directly, not through pipes, so terminal programs |
|
541 | 548 | # work correctly. |
|
542 | 549 | system = InteractiveShell.system_raw |
|
543 | 550 | |
|
544 | 551 | def auto_rewrite_input(self, cmd): |
|
545 | 552 | """Overridden from the parent class to use fancy rewriting prompt""" |
|
546 | 553 | if not self.show_rewritten_input: |
|
547 | 554 | return |
|
548 | 555 | |
|
549 | 556 | tokens = self.prompts.rewrite_prompt_tokens() |
|
550 | 557 | if self.pt_cli: |
|
551 | 558 | self.pt_cli.print_tokens(tokens) |
|
552 | 559 | print(cmd) |
|
553 | 560 | else: |
|
554 | 561 | prompt = ''.join(s for t, s in tokens) |
|
555 | 562 | print(prompt, cmd, sep='') |
|
556 | 563 | |
|
557 | 564 | _prompts_before = None |
|
558 | 565 | def switch_doctest_mode(self, mode): |
|
559 | 566 | """Switch prompts to classic for %doctest_mode""" |
|
560 | 567 | if mode: |
|
561 | 568 | self._prompts_before = self.prompts |
|
562 | 569 | self.prompts = ClassicPrompts(self) |
|
563 | 570 | elif self._prompts_before: |
|
564 | 571 | self.prompts = self._prompts_before |
|
565 | 572 | self._prompts_before = None |
|
566 | 573 | |
|
567 | 574 | |
|
568 | 575 | InteractiveShellABC.register(TerminalInteractiveShell) |
|
569 | 576 | |
|
570 | 577 | if __name__ == '__main__': |
|
571 | 578 | TerminalInteractiveShell.instance().interact() |
@@ -1,347 +1,374 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Class and program to colorize python source code for ANSI terminals. |
|
4 | 4 | |
|
5 | 5 | Based on an HTML code highlighter by Jurgen Hermann found at: |
|
6 | 6 | http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52298 |
|
7 | 7 | |
|
8 | 8 | Modifications by Fernando Perez (fperez@colorado.edu). |
|
9 | 9 | |
|
10 | 10 | Information on the original HTML highlighter follows: |
|
11 | 11 | |
|
12 | 12 | MoinMoin - Python Source Parser |
|
13 | 13 | |
|
14 | 14 | Title: Colorize Python source using the built-in tokenizer |
|
15 | 15 | |
|
16 | 16 | Submitter: Jurgen Hermann |
|
17 | 17 | Last Updated:2001/04/06 |
|
18 | 18 | |
|
19 | 19 | Version no:1.2 |
|
20 | 20 | |
|
21 | 21 | Description: |
|
22 | 22 | |
|
23 | 23 | This code is part of MoinMoin (http://moin.sourceforge.net/) and converts |
|
24 | 24 | Python source code to HTML markup, rendering comments, keywords, |
|
25 | 25 | operators, numeric and string literals in different colors. |
|
26 | 26 | |
|
27 | 27 | It shows how to use the built-in keyword, token and tokenize modules to |
|
28 | 28 | scan Python source code and re-emit it with no changes to its original |
|
29 | 29 | formatting (which is the hard part). |
|
30 | 30 | """ |
|
31 | 31 | from __future__ import print_function |
|
32 | 32 | from __future__ import absolute_import |
|
33 | 33 | from __future__ import unicode_literals |
|
34 | 34 | |
|
35 | 35 | __all__ = ['ANSICodeColors','Parser'] |
|
36 | 36 | |
|
37 | 37 | _scheme_default = 'Linux' |
|
38 | 38 | |
|
39 | 39 | |
|
40 | 40 | # Imports |
|
41 | 41 | import keyword |
|
42 | 42 | import os |
|
43 | 43 | import sys |
|
44 | 44 | import token |
|
45 | 45 | import tokenize |
|
46 | 46 | |
|
47 | 47 | try: |
|
48 | 48 | generate_tokens = tokenize.generate_tokens |
|
49 | 49 | except AttributeError: |
|
50 | 50 | # Python 3. Note that we use the undocumented _tokenize because it expects |
|
51 | 51 | # strings, not bytes. See also Python issue #9969. |
|
52 | 52 | generate_tokens = tokenize._tokenize |
|
53 | 53 | |
|
54 | 54 | from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable |
|
55 | 55 | from IPython.utils.py3compat import PY3 |
|
56 | 56 | |
|
57 | 57 | from .colorable import Colorable |
|
58 | 58 | |
|
59 | 59 | if PY3: |
|
60 | 60 | from io import StringIO |
|
61 | 61 | else: |
|
62 | 62 | from StringIO import StringIO |
|
63 | 63 | |
|
64 | 64 | ############################################################################# |
|
65 | 65 | ### Python Source Parser (does Hilighting) |
|
66 | 66 | ############################################################################# |
|
67 | 67 | |
|
68 | 68 | _KEYWORD = token.NT_OFFSET + 1 |
|
69 | 69 | _TEXT = token.NT_OFFSET + 2 |
|
70 | 70 | |
|
71 | 71 | #**************************************************************************** |
|
72 | 72 | # Builtin color schemes |
|
73 | 73 | |
|
74 | 74 | Colors = TermColors # just a shorthand |
|
75 | 75 | |
|
76 | 76 | # Build a few color schemes |
|
77 | 77 | NoColor = ColorScheme( |
|
78 | 78 | 'NoColor',{ |
|
79 | 79 | 'header' : Colors.NoColor, |
|
80 | 80 | token.NUMBER : Colors.NoColor, |
|
81 | 81 | token.OP : Colors.NoColor, |
|
82 | 82 | token.STRING : Colors.NoColor, |
|
83 | 83 | tokenize.COMMENT : Colors.NoColor, |
|
84 | 84 | token.NAME : Colors.NoColor, |
|
85 | 85 | token.ERRORTOKEN : Colors.NoColor, |
|
86 | 86 | |
|
87 | 87 | _KEYWORD : Colors.NoColor, |
|
88 | 88 | _TEXT : Colors.NoColor, |
|
89 | 89 | |
|
90 | 90 | 'in_prompt' : InputTermColors.NoColor, # Input prompt |
|
91 | 91 | 'in_number' : InputTermColors.NoColor, # Input prompt number |
|
92 | 92 | 'in_prompt2' : InputTermColors.NoColor, # Continuation prompt |
|
93 | 93 | 'in_normal' : InputTermColors.NoColor, # color off (usu. Colors.Normal) |
|
94 | 94 | |
|
95 | 95 | 'out_prompt' : Colors.NoColor, # Output prompt |
|
96 | 96 | 'out_number' : Colors.NoColor, # Output prompt number |
|
97 | 97 | |
|
98 | 98 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) |
|
99 | 99 | } ) |
|
100 | 100 | |
|
101 | 101 | LinuxColors = ColorScheme( |
|
102 | 102 | 'Linux',{ |
|
103 | 103 | 'header' : Colors.LightRed, |
|
104 | 104 | token.NUMBER : Colors.LightCyan, |
|
105 | 105 | token.OP : Colors.Yellow, |
|
106 | 106 | token.STRING : Colors.LightBlue, |
|
107 | 107 | tokenize.COMMENT : Colors.LightRed, |
|
108 | 108 | token.NAME : Colors.Normal, |
|
109 | 109 | token.ERRORTOKEN : Colors.Red, |
|
110 | 110 | |
|
111 | 111 | _KEYWORD : Colors.LightGreen, |
|
112 | 112 | _TEXT : Colors.Yellow, |
|
113 | 113 | |
|
114 | 114 | 'in_prompt' : InputTermColors.Green, |
|
115 | 115 | 'in_number' : InputTermColors.LightGreen, |
|
116 | 116 | 'in_prompt2' : InputTermColors.Green, |
|
117 | 117 | 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal) |
|
118 | 118 | |
|
119 | 119 | 'out_prompt' : Colors.Red, |
|
120 | 120 | 'out_number' : Colors.LightRed, |
|
121 | 121 | |
|
122 | 122 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
123 | 123 | } ) |
|
124 | 124 | |
|
125 | NeutralColors = ColorScheme( | |
|
126 | 'Neutral',{ | |
|
127 | 'header' : Colors.Red, | |
|
128 | token.NUMBER : Colors.Cyan, | |
|
129 | token.OP : Colors.Blue, | |
|
130 | token.STRING : Colors.Blue, | |
|
131 | tokenize.COMMENT : Colors.Red, | |
|
132 | token.NAME : Colors.Normal, | |
|
133 | token.ERRORTOKEN : Colors.Red, | |
|
134 | ||
|
135 | _KEYWORD : Colors.Green, | |
|
136 | _TEXT : Colors.Blue, | |
|
137 | ||
|
138 | 'in_prompt' : InputTermColors.Blue, | |
|
139 | 'in_number' : InputTermColors.LightBlue, | |
|
140 | 'in_prompt2' : InputTermColors.Blue, | |
|
141 | 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal) | |
|
142 | ||
|
143 | 'out_prompt' : Colors.Red, | |
|
144 | 'out_number' : Colors.LightRed, | |
|
145 | ||
|
146 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) | |
|
147 | } ) | |
|
148 | ||
|
149 | ||
|
150 | ||
|
125 | 151 | LightBGColors = ColorScheme( |
|
126 | 152 | 'LightBG',{ |
|
127 | 153 | 'header' : Colors.Red, |
|
128 | 154 | token.NUMBER : Colors.Cyan, |
|
129 | 155 | token.OP : Colors.Blue, |
|
130 | 156 | token.STRING : Colors.Blue, |
|
131 | 157 | tokenize.COMMENT : Colors.Red, |
|
132 | 158 | token.NAME : Colors.Normal, |
|
133 | 159 | token.ERRORTOKEN : Colors.Red, |
|
134 | 160 | |
|
161 | ||
|
135 | 162 | _KEYWORD : Colors.Green, |
|
136 | 163 | _TEXT : Colors.Blue, |
|
137 | 164 | |
|
138 | 165 | 'in_prompt' : InputTermColors.Blue, |
|
139 | 166 | 'in_number' : InputTermColors.LightBlue, |
|
140 | 167 | 'in_prompt2' : InputTermColors.Blue, |
|
141 | 168 | 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal) |
|
142 | 169 | |
|
143 | 170 | 'out_prompt' : Colors.Red, |
|
144 | 171 | 'out_number' : Colors.LightRed, |
|
145 | 172 | |
|
146 | 173 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
147 | 174 | } ) |
|
148 | 175 | |
|
149 | 176 | # Build table of color schemes (needed by the parser) |
|
150 | ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], | |
|
177 | ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors], | |
|
151 | 178 | _scheme_default) |
|
152 | 179 | |
|
153 | 180 | class Parser(Colorable): |
|
154 | 181 | """ Format colored Python source. |
|
155 | 182 | """ |
|
156 | 183 | |
|
157 | 184 | def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None): |
|
158 | 185 | """ Create a parser with a specified color table and output channel. |
|
159 | 186 | |
|
160 | 187 | Call format() to process code. |
|
161 | 188 | """ |
|
162 | 189 | |
|
163 | 190 | super(Parser, self).__init__(parent=parent) |
|
164 | 191 | |
|
165 | 192 | self.color_table = color_table and color_table or ANSICodeColors |
|
166 | 193 | self.out = out |
|
167 | 194 | |
|
168 | 195 | def format(self, raw, out = None, scheme = ''): |
|
169 | 196 | return self.format2(raw, out, scheme)[0] |
|
170 | 197 | |
|
171 | 198 | def format2(self, raw, out = None, scheme = ''): |
|
172 | 199 | """ Parse and send the colored source. |
|
173 | 200 | |
|
174 | 201 | If out and scheme are not specified, the defaults (given to |
|
175 | 202 | constructor) are used. |
|
176 | 203 | |
|
177 | 204 | out should be a file-type object. Optionally, out can be given as the |
|
178 | 205 | string 'str' and the parser will automatically return the output in a |
|
179 | 206 | string.""" |
|
180 | 207 | |
|
181 | 208 | string_output = 0 |
|
182 | 209 | if out == 'str' or self.out == 'str' or \ |
|
183 | 210 | isinstance(self.out,StringIO): |
|
184 | 211 | # XXX - I don't really like this state handling logic, but at this |
|
185 | 212 | # point I don't want to make major changes, so adding the |
|
186 | 213 | # isinstance() check is the simplest I can do to ensure correct |
|
187 | 214 | # behavior. |
|
188 | 215 | out_old = self.out |
|
189 | 216 | self.out = StringIO() |
|
190 | 217 | string_output = 1 |
|
191 | 218 | elif out is not None: |
|
192 | 219 | self.out = out |
|
193 | 220 | |
|
194 | 221 | # Fast return of the unmodified input for NoColor scheme |
|
195 | 222 | if scheme == 'NoColor': |
|
196 | 223 | error = False |
|
197 | 224 | self.out.write(raw) |
|
198 | 225 | if string_output: |
|
199 | 226 | return raw,error |
|
200 | 227 | else: |
|
201 | 228 | return None,error |
|
202 | 229 | |
|
203 | 230 | # local shorthands |
|
204 | 231 | colors = self.color_table[scheme].colors |
|
205 | 232 | self.colors = colors # put in object so __call__ sees it |
|
206 | 233 | |
|
207 | 234 | # Remove trailing whitespace and normalize tabs |
|
208 | 235 | self.raw = raw.expandtabs().rstrip() |
|
209 | 236 | |
|
210 | 237 | # store line offsets in self.lines |
|
211 | 238 | self.lines = [0, 0] |
|
212 | 239 | pos = 0 |
|
213 | 240 | raw_find = self.raw.find |
|
214 | 241 | lines_append = self.lines.append |
|
215 | 242 | while 1: |
|
216 | 243 | pos = raw_find('\n', pos) + 1 |
|
217 | 244 | if not pos: break |
|
218 | 245 | lines_append(pos) |
|
219 | 246 | lines_append(len(self.raw)) |
|
220 | 247 | |
|
221 | 248 | # parse the source and write it |
|
222 | 249 | self.pos = 0 |
|
223 | 250 | text = StringIO(self.raw) |
|
224 | 251 | |
|
225 | 252 | error = False |
|
226 | 253 | try: |
|
227 | 254 | for atoken in generate_tokens(text.readline): |
|
228 | 255 | self(*atoken) |
|
229 | 256 | except tokenize.TokenError as ex: |
|
230 | 257 | msg = ex.args[0] |
|
231 | 258 | line = ex.args[1][0] |
|
232 | 259 | self.out.write("%s\n\n*** ERROR: %s%s%s\n" % |
|
233 | 260 | (colors[token.ERRORTOKEN], |
|
234 | 261 | msg, self.raw[self.lines[line]:], |
|
235 | 262 | colors.normal) |
|
236 | 263 | ) |
|
237 | 264 | error = True |
|
238 | 265 | self.out.write(colors.normal+'\n') |
|
239 | 266 | if string_output: |
|
240 | 267 | output = self.out.getvalue() |
|
241 | 268 | self.out = out_old |
|
242 | 269 | return (output, error) |
|
243 | 270 | return (None, error) |
|
244 | 271 | |
|
245 | 272 | def __call__(self, toktype, toktext, start_pos, end_pos, line): |
|
246 | 273 | """ Token handler, with syntax highlighting.""" |
|
247 | 274 | (srow,scol) = start_pos |
|
248 | 275 | (erow,ecol) = end_pos |
|
249 | 276 | colors = self.colors |
|
250 | 277 | owrite = self.out.write |
|
251 | 278 | |
|
252 | 279 | # line separator, so this works across platforms |
|
253 | 280 | linesep = os.linesep |
|
254 | 281 | |
|
255 | 282 | # calculate new positions |
|
256 | 283 | oldpos = self.pos |
|
257 | 284 | newpos = self.lines[srow] + scol |
|
258 | 285 | self.pos = newpos + len(toktext) |
|
259 | 286 | |
|
260 | 287 | # send the original whitespace, if needed |
|
261 | 288 | if newpos > oldpos: |
|
262 | 289 | owrite(self.raw[oldpos:newpos]) |
|
263 | 290 | |
|
264 | 291 | # skip indenting tokens |
|
265 | 292 | if toktype in [token.INDENT, token.DEDENT]: |
|
266 | 293 | self.pos = newpos |
|
267 | 294 | return |
|
268 | 295 | |
|
269 | 296 | # map token type to a color group |
|
270 | 297 | if token.LPAR <= toktype <= token.OP: |
|
271 | 298 | toktype = token.OP |
|
272 | 299 | elif toktype == token.NAME and keyword.iskeyword(toktext): |
|
273 | 300 | toktype = _KEYWORD |
|
274 | 301 | color = colors.get(toktype, colors[_TEXT]) |
|
275 | 302 | |
|
276 | 303 | #print '<%s>' % toktext, # dbg |
|
277 | 304 | |
|
278 | 305 | # Triple quoted strings must be handled carefully so that backtracking |
|
279 | 306 | # in pagers works correctly. We need color terminators on _each_ line. |
|
280 | 307 | if linesep in toktext: |
|
281 | 308 | toktext = toktext.replace(linesep, '%s%s%s' % |
|
282 | 309 | (colors.normal,linesep,color)) |
|
283 | 310 | |
|
284 | 311 | # send text |
|
285 | 312 | owrite('%s%s%s' % (color,toktext,colors.normal)) |
|
286 | 313 | |
|
287 | 314 | def main(argv=None): |
|
288 | 315 | """Run as a command-line script: colorize a python file or stdin using ANSI |
|
289 | 316 | color escapes and print to stdout. |
|
290 | 317 | |
|
291 | 318 | Inputs: |
|
292 | 319 | |
|
293 | 320 | - argv(None): a list of strings like sys.argv[1:] giving the command-line |
|
294 | 321 | arguments. If None, use sys.argv[1:]. |
|
295 | 322 | """ |
|
296 | 323 | |
|
297 | 324 | usage_msg = """%prog [options] [filename] |
|
298 | 325 | |
|
299 | 326 | Colorize a python file or stdin using ANSI color escapes and print to stdout. |
|
300 | 327 | If no filename is given, or if filename is -, read standard input.""" |
|
301 | 328 | |
|
302 | 329 | import optparse |
|
303 | 330 | parser = optparse.OptionParser(usage=usage_msg) |
|
304 | 331 | newopt = parser.add_option |
|
305 | 332 | newopt('-s','--scheme',metavar='NAME',dest='scheme_name',action='store', |
|
306 | 333 | choices=['Linux','LightBG','NoColor'],default=_scheme_default, |
|
307 | 334 | help="give the color scheme to use. Currently only 'Linux'\ |
|
308 | 335 | (default) and 'LightBG' and 'NoColor' are implemented (give without\ |
|
309 | 336 | quotes)") |
|
310 | 337 | |
|
311 | 338 | opts,args = parser.parse_args(argv) |
|
312 | 339 | |
|
313 | 340 | if len(args) > 1: |
|
314 | 341 | parser.error("you must give at most one filename.") |
|
315 | 342 | |
|
316 | 343 | if len(args) == 0: |
|
317 | 344 | fname = '-' # no filename given; setup to read from stdin |
|
318 | 345 | else: |
|
319 | 346 | fname = args[0] |
|
320 | 347 | |
|
321 | 348 | if fname == '-': |
|
322 | 349 | stream = sys.stdin |
|
323 | 350 | else: |
|
324 | 351 | try: |
|
325 | 352 | stream = open(fname) |
|
326 | 353 | except IOError as msg: |
|
327 | 354 | print(msg, file=sys.stderr) |
|
328 | 355 | sys.exit(1) |
|
329 | 356 | |
|
330 | 357 | parser = Parser() |
|
331 | 358 | |
|
332 | 359 | # we need nested try blocks because pre-2.5 python doesn't support unified |
|
333 | 360 | # try-except-finally |
|
334 | 361 | try: |
|
335 | 362 | try: |
|
336 | 363 | # write colorized version to stdout |
|
337 | 364 | parser.format(stream.read(),scheme=opts.scheme_name) |
|
338 | 365 | except IOError as msg: |
|
339 | 366 | # if user reads through a pager and quits, don't print traceback |
|
340 | 367 | if msg.args != (32,'Broken pipe'): |
|
341 | 368 | raise |
|
342 | 369 | finally: |
|
343 | 370 | if stream is not sys.stdin: |
|
344 | 371 | stream.close() # in case a non-handled exception happened above |
|
345 | 372 | |
|
346 | 373 | if __name__ == "__main__": |
|
347 | 374 | main() |
@@ -1,26 +1,26 b'' | |||
|
1 | 1 | #***************************************************************************** |
|
2 | 2 | # Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org> |
|
3 | 3 | # |
|
4 | 4 | # Distributed under the terms of the BSD License. The full license is in |
|
5 | 5 | # the file COPYING, distributed as part of this software. |
|
6 | 6 | #***************************************************************************** |
|
7 | 7 | from __future__ import absolute_import |
|
8 | 8 | |
|
9 | 9 | """ |
|
10 | 10 | Color managing related utilities |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | import pygments |
|
14 | 14 | |
|
15 | 15 | from traitlets.config import Configurable |
|
16 | 16 | from traitlets import Unicode |
|
17 | 17 | |
|
18 | 18 | |
|
19 | available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux'] | |
|
19 | available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral'] | |
|
20 | 20 | |
|
21 | 21 | class Colorable(Configurable): |
|
22 | 22 | """ |
|
23 | 23 | A subclass of configurable for all the classes that have a `default_scheme` |
|
24 | 24 | """ |
|
25 | 25 | default_style=Unicode('lightbg').tag(config=True) |
|
26 | 26 |
@@ -1,78 +1,78 b'' | |||
|
1 | 1 | # coding: utf-8 |
|
2 | 2 | """Test suite for our color utilities. |
|
3 | 3 | |
|
4 | 4 | Authors |
|
5 | 5 | ------- |
|
6 | 6 | |
|
7 | 7 | * Min RK |
|
8 | 8 | """ |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | # Copyright (C) 2011 The IPython Development Team |
|
11 | 11 | # |
|
12 | 12 | # Distributed under the terms of the BSD License. The full license is in |
|
13 | 13 | # the file COPYING.txt, distributed as part of this software. |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | # Imports |
|
18 | 18 | #----------------------------------------------------------------------------- |
|
19 | 19 | |
|
20 | 20 | # third party |
|
21 | 21 | import nose.tools as nt |
|
22 | 22 | |
|
23 | 23 | # our own |
|
24 | 24 | from IPython.utils.PyColorize import Parser |
|
25 | 25 | import io |
|
26 | 26 | |
|
27 | 27 | #----------------------------------------------------------------------------- |
|
28 | 28 | # Test functions |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | |
|
31 | 31 | sample = u""" |
|
32 | 32 | def function(arg, *args, kwarg=True, **kwargs): |
|
33 | 33 | ''' |
|
34 | 34 | this is docs |
|
35 | 35 | ''' |
|
36 | 36 | pass is True |
|
37 | 37 | False == None |
|
38 | 38 | |
|
39 | 39 | with io.open(ru'unicode'): |
|
40 | 40 | raise ValueError("\n escape \r sequence") |
|
41 | 41 | |
|
42 | 42 | print("wěird ünicoðe") |
|
43 | 43 | |
|
44 | 44 | class Bar(Super): |
|
45 | 45 | |
|
46 | 46 | def __init__(self): |
|
47 | 47 | super(Bar, self).__init__(1**2, 3^4, 5 or 6) |
|
48 | 48 | """ |
|
49 | 49 | |
|
50 | 50 | def test_loop_colors(): |
|
51 | 51 | |
|
52 | for scheme in ('Linux', 'NoColor','LightBG'): | |
|
52 | for scheme in ('Linux', 'NoColor','LightBG', 'Neutral'): | |
|
53 | 53 | |
|
54 | 54 | def test_unicode_colorize(): |
|
55 | 55 | p = Parser() |
|
56 | 56 | f1 = p.format('1/0', 'str', scheme=scheme) |
|
57 | 57 | f2 = p.format(u'1/0', 'str', scheme=scheme) |
|
58 | 58 | nt.assert_equal(f1, f2) |
|
59 | 59 | |
|
60 | 60 | def test_parse_sample(): |
|
61 | 61 | """and test writing to a buffer""" |
|
62 | 62 | buf = io.StringIO() |
|
63 | 63 | p = Parser() |
|
64 | 64 | p.format(sample, buf, scheme=scheme) |
|
65 | 65 | buf.seek(0) |
|
66 | 66 | f1 = buf.read() |
|
67 | 67 | |
|
68 | 68 | nt.assert_not_in('ERROR', f1) |
|
69 | 69 | |
|
70 | 70 | def test_parse_error(): |
|
71 | 71 | p = Parser() |
|
72 | 72 | f1 = p.format(')', 'str', scheme=scheme) |
|
73 | 73 | if scheme != 'NoColor': |
|
74 | 74 | nt.assert_in('ERROR', f1) |
|
75 | 75 | |
|
76 | 76 | yield test_unicode_colorize |
|
77 | 77 | yield test_parse_sample |
|
78 | 78 | yield test_parse_error |
General Comments 0
You need to be logged in to leave comments.
Login now