Show More
@@ -1,510 +1,509 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 | |
|
28 | 28 | import bdb |
|
29 | 29 | import linecache |
|
30 | 30 | import sys |
|
31 | 31 | |
|
32 | 32 | from IPython.utils import PyColorize |
|
33 | 33 | from IPython.core import ipapi |
|
34 | from IPython.utils import coloransi | |
|
35 | import IPython.utils.io | |
|
34 | from IPython.utils import coloransi, io | |
|
36 | 35 | from IPython.core.excolors import exception_colors |
|
37 | 36 | |
|
38 | 37 | # See if we can use pydb. |
|
39 | 38 | has_pydb = False |
|
40 | 39 | prompt = 'ipdb> ' |
|
41 | 40 | #We have to check this directly from sys.argv, config struct not yet available |
|
42 | 41 | if '-pydb' in sys.argv: |
|
43 | 42 | try: |
|
44 | 43 | import pydb |
|
45 | 44 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': |
|
46 | 45 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we |
|
47 | 46 | # better protect against it. |
|
48 | 47 | has_pydb = True |
|
49 | 48 | except ImportError: |
|
50 | 49 | print "Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available" |
|
51 | 50 | |
|
52 | 51 | if has_pydb: |
|
53 | 52 | from pydb import Pdb as OldPdb |
|
54 | 53 | #print "Using pydb for %run -d and post-mortem" #dbg |
|
55 | 54 | prompt = 'ipydb> ' |
|
56 | 55 | else: |
|
57 | 56 | from pdb import Pdb as OldPdb |
|
58 | 57 | |
|
59 | 58 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
60 | 59 | # it does so with some limitations. The rest of this support is implemented in |
|
61 | 60 | # the Tracer constructor. |
|
62 | 61 | def BdbQuit_excepthook(et,ev,tb): |
|
63 | 62 | if et==bdb.BdbQuit: |
|
64 | 63 | print 'Exiting Debugger.' |
|
65 | 64 | else: |
|
66 | 65 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
67 | 66 | |
|
68 | 67 | def BdbQuit_IPython_excepthook(self,et,ev,tb): |
|
69 | 68 | print 'Exiting Debugger.' |
|
70 | 69 | |
|
71 | 70 | |
|
72 | 71 | class Tracer(object): |
|
73 | 72 | """Class for local debugging, similar to pdb.set_trace. |
|
74 | 73 | |
|
75 | 74 | Instances of this class, when called, behave like pdb.set_trace, but |
|
76 | 75 | providing IPython's enhanced capabilities. |
|
77 | 76 | |
|
78 | 77 | This is implemented as a class which must be initialized in your own code |
|
79 | 78 | and not as a standalone function because we need to detect at runtime |
|
80 | 79 | whether IPython is already active or not. That detection is done in the |
|
81 | 80 | constructor, ensuring that this code plays nicely with a running IPython, |
|
82 | 81 | while functioning acceptably (though with limitations) if outside of it. |
|
83 | 82 | """ |
|
84 | 83 | |
|
85 | 84 | def __init__(self,colors=None): |
|
86 | 85 | """Create a local debugger instance. |
|
87 | 86 | |
|
88 | 87 | :Parameters: |
|
89 | 88 | |
|
90 | 89 | - `colors` (None): a string containing the name of the color scheme to |
|
91 | 90 | use, it must be one of IPython's valid color schemes. If not given, the |
|
92 | 91 | function will default to the current IPython scheme when running inside |
|
93 | 92 | IPython, and to 'NoColor' otherwise. |
|
94 | 93 | |
|
95 | 94 | Usage example: |
|
96 | 95 | |
|
97 | 96 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
98 | 97 | |
|
99 | 98 | ... later in your code |
|
100 | 99 | debug_here() # -> will open up the debugger at that point. |
|
101 | 100 | |
|
102 | 101 | Once the debugger activates, you can use all of its regular commands to |
|
103 | 102 | step through code, set breakpoints, etc. See the pdb documentation |
|
104 | 103 | from the Python standard library for usage details. |
|
105 | 104 | """ |
|
106 | 105 | |
|
107 | 106 | try: |
|
108 | 107 | ip = ipapi.get() |
|
109 | 108 | except: |
|
110 | 109 | # Outside of ipython, we set our own exception hook manually |
|
111 | 110 | BdbQuit_excepthook.excepthook_ori = sys.excepthook |
|
112 | 111 | sys.excepthook = BdbQuit_excepthook |
|
113 | 112 | def_colors = 'NoColor' |
|
114 | 113 | try: |
|
115 | 114 | # Limited tab completion support |
|
116 | 115 | import readline |
|
117 | 116 | readline.parse_and_bind('tab: complete') |
|
118 | 117 | except ImportError: |
|
119 | 118 | pass |
|
120 | 119 | else: |
|
121 | 120 | # In ipython, we use its custom exception handler mechanism |
|
122 | 121 | def_colors = ip.colors |
|
123 | 122 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) |
|
124 | 123 | |
|
125 | 124 | if colors is None: |
|
126 | 125 | colors = def_colors |
|
127 | 126 | self.debugger = Pdb(colors) |
|
128 | 127 | |
|
129 | 128 | def __call__(self): |
|
130 | 129 | """Starts an interactive debugger at the point where called. |
|
131 | 130 | |
|
132 | 131 | This is similar to the pdb.set_trace() function from the std lib, but |
|
133 | 132 | using IPython's enhanced debugger.""" |
|
134 | 133 | |
|
135 | 134 | self.debugger.set_trace(sys._getframe().f_back) |
|
136 | 135 | |
|
137 | 136 | |
|
138 | 137 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
139 | 138 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
140 | 139 | for the do_... commands that hook into the help system. |
|
141 | 140 | Adapted from from a comp.lang.python posting |
|
142 | 141 | by Duncan Booth.""" |
|
143 | 142 | def wrapper(*args, **kw): |
|
144 | 143 | return new_fn(*args, **kw) |
|
145 | 144 | if old_fn.__doc__: |
|
146 | 145 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
147 | 146 | return wrapper |
|
148 | 147 | |
|
149 | 148 | |
|
150 | 149 | def _file_lines(fname): |
|
151 | 150 | """Return the contents of a named file as a list of lines. |
|
152 | 151 | |
|
153 | 152 | This function never raises an IOError exception: if the file can't be |
|
154 | 153 | read, it simply returns an empty list.""" |
|
155 | 154 | |
|
156 | 155 | try: |
|
157 | 156 | outfile = open(fname) |
|
158 | 157 | except IOError: |
|
159 | 158 | return [] |
|
160 | 159 | else: |
|
161 | 160 | out = outfile.readlines() |
|
162 | 161 | outfile.close() |
|
163 | 162 | return out |
|
164 | 163 | |
|
165 | 164 | |
|
166 | 165 | class Pdb(OldPdb): |
|
167 | 166 | """Modified Pdb class, does not load readline.""" |
|
168 | 167 | |
|
169 | 168 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
170 | 169 | stdin=None, stdout=None): |
|
171 | 170 | |
|
172 | 171 | # Parent constructor: |
|
173 | 172 | if has_pydb and completekey is None: |
|
174 |
OldPdb.__init__(self,stdin=stdin,stdout= |
|
|
173 | OldPdb.__init__(self,stdin=stdin,stdout=io.stdout) | |
|
175 | 174 | else: |
|
176 | 175 | OldPdb.__init__(self,completekey,stdin,stdout) |
|
177 | 176 | |
|
178 | 177 | self.prompt = prompt # The default prompt is '(Pdb)' |
|
179 | 178 | |
|
180 | 179 | # IPython changes... |
|
181 | 180 | self.is_pydb = has_pydb |
|
182 | 181 | |
|
183 | 182 | self.shell = ipapi.get() |
|
184 | 183 | |
|
185 | 184 | if self.is_pydb: |
|
186 | 185 | |
|
187 | 186 | # interactiveshell.py's ipalias seems to want pdb's checkline |
|
188 | 187 | # which located in pydb.fn |
|
189 | 188 | import pydb.fns |
|
190 | 189 | self.checkline = lambda filename, lineno: \ |
|
191 | 190 | pydb.fns.checkline(self, filename, lineno) |
|
192 | 191 | |
|
193 | 192 | self.curframe = None |
|
194 | 193 | self.do_restart = self.new_do_restart |
|
195 | 194 | |
|
196 | 195 | self.old_all_completions = self.shell.Completer.all_completions |
|
197 | 196 | self.shell.Completer.all_completions=self.all_completions |
|
198 | 197 | |
|
199 | 198 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, |
|
200 | 199 | OldPdb.do_list) |
|
201 | 200 | self.do_l = self.do_list |
|
202 | 201 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, |
|
203 | 202 | OldPdb.do_frame) |
|
204 | 203 | |
|
205 | 204 | self.aliases = {} |
|
206 | 205 | |
|
207 | 206 | # Create color table: we copy the default one from the traceback |
|
208 | 207 | # module and add a few attributes needed for debugging |
|
209 | 208 | self.color_scheme_table = exception_colors() |
|
210 | 209 | |
|
211 | 210 | # shorthands |
|
212 | 211 | C = coloransi.TermColors |
|
213 | 212 | cst = self.color_scheme_table |
|
214 | 213 | |
|
215 | 214 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
216 | 215 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
217 | 216 | |
|
218 | 217 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
219 | 218 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
220 | 219 | |
|
221 | 220 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
222 | 221 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
223 | 222 | |
|
224 | 223 | self.set_colors(color_scheme) |
|
225 | 224 | |
|
226 | 225 | # Add a python parser so we can syntax highlight source while |
|
227 | 226 | # debugging. |
|
228 | 227 | self.parser = PyColorize.Parser() |
|
229 | 228 | |
|
230 | 229 | def set_colors(self, scheme): |
|
231 | 230 | """Shorthand access to the color table scheme selector method.""" |
|
232 | 231 | self.color_scheme_table.set_active_scheme(scheme) |
|
233 | 232 | |
|
234 | 233 | def interaction(self, frame, traceback): |
|
235 | 234 | self.shell.set_completer_frame(frame) |
|
236 | 235 | OldPdb.interaction(self, frame, traceback) |
|
237 | 236 | |
|
238 | 237 | def new_do_up(self, arg): |
|
239 | 238 | OldPdb.do_up(self, arg) |
|
240 | 239 | self.shell.set_completer_frame(self.curframe) |
|
241 | 240 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
242 | 241 | |
|
243 | 242 | def new_do_down(self, arg): |
|
244 | 243 | OldPdb.do_down(self, arg) |
|
245 | 244 | self.shell.set_completer_frame(self.curframe) |
|
246 | 245 | |
|
247 | 246 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
248 | 247 | |
|
249 | 248 | def new_do_frame(self, arg): |
|
250 | 249 | OldPdb.do_frame(self, arg) |
|
251 | 250 | self.shell.set_completer_frame(self.curframe) |
|
252 | 251 | |
|
253 | 252 | def new_do_quit(self, arg): |
|
254 | 253 | |
|
255 | 254 | if hasattr(self, 'old_all_completions'): |
|
256 | 255 | self.shell.Completer.all_completions=self.old_all_completions |
|
257 | 256 | |
|
258 | 257 | |
|
259 | 258 | return OldPdb.do_quit(self, arg) |
|
260 | 259 | |
|
261 | 260 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
262 | 261 | |
|
263 | 262 | def new_do_restart(self, arg): |
|
264 | 263 | """Restart command. In the context of ipython this is exactly the same |
|
265 | 264 | thing as 'quit'.""" |
|
266 | 265 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
267 | 266 | return self.do_quit(arg) |
|
268 | 267 | |
|
269 | 268 | def postloop(self): |
|
270 | 269 | self.shell.set_completer_frame(None) |
|
271 | 270 | |
|
272 | 271 | def print_stack_trace(self): |
|
273 | 272 | try: |
|
274 | 273 | for frame_lineno in self.stack: |
|
275 | 274 | self.print_stack_entry(frame_lineno, context = 5) |
|
276 | 275 | except KeyboardInterrupt: |
|
277 | 276 | pass |
|
278 | 277 | |
|
279 | 278 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
280 | 279 | context = 3): |
|
281 | 280 | #frame, lineno = frame_lineno |
|
282 |
print >> |
|
|
281 | print >>io.stdout, self.format_stack_entry(frame_lineno, '', context) | |
|
283 | 282 | |
|
284 | 283 | # vds: >> |
|
285 | 284 | frame, lineno = frame_lineno |
|
286 | 285 | filename = frame.f_code.co_filename |
|
287 | 286 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
288 | 287 | # vds: << |
|
289 | 288 | |
|
290 | 289 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): |
|
291 | 290 | import linecache, repr |
|
292 | 291 | |
|
293 | 292 | ret = [] |
|
294 | 293 | |
|
295 | 294 | Colors = self.color_scheme_table.active_colors |
|
296 | 295 | ColorsNormal = Colors.Normal |
|
297 | 296 | tpl_link = '%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
298 | 297 | tpl_call = '%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
299 | 298 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
300 | 299 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
301 | 300 | ColorsNormal) |
|
302 | 301 | |
|
303 | 302 | frame, lineno = frame_lineno |
|
304 | 303 | |
|
305 | 304 | return_value = '' |
|
306 | 305 | if '__return__' in frame.f_locals: |
|
307 | 306 | rv = frame.f_locals['__return__'] |
|
308 | 307 | #return_value += '->' |
|
309 | 308 | return_value += repr.repr(rv) + '\n' |
|
310 | 309 | ret.append(return_value) |
|
311 | 310 | |
|
312 | 311 | #s = filename + '(' + `lineno` + ')' |
|
313 | 312 | filename = self.canonic(frame.f_code.co_filename) |
|
314 | 313 | link = tpl_link % filename |
|
315 | 314 | |
|
316 | 315 | if frame.f_code.co_name: |
|
317 | 316 | func = frame.f_code.co_name |
|
318 | 317 | else: |
|
319 | 318 | func = "<lambda>" |
|
320 | 319 | |
|
321 | 320 | call = '' |
|
322 | 321 | if func != '?': |
|
323 | 322 | if '__args__' in frame.f_locals: |
|
324 | 323 | args = repr.repr(frame.f_locals['__args__']) |
|
325 | 324 | else: |
|
326 | 325 | args = '()' |
|
327 | 326 | call = tpl_call % (func, args) |
|
328 | 327 | |
|
329 | 328 | # The level info should be generated in the same format pdb uses, to |
|
330 | 329 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
331 | 330 | if frame is self.curframe: |
|
332 | 331 | ret.append('> ') |
|
333 | 332 | else: |
|
334 | 333 | ret.append(' ') |
|
335 | 334 | ret.append('%s(%s)%s\n' % (link,lineno,call)) |
|
336 | 335 | |
|
337 | 336 | start = lineno - 1 - context//2 |
|
338 | 337 | lines = linecache.getlines(filename) |
|
339 | 338 | start = max(start, 0) |
|
340 | 339 | start = min(start, len(lines) - context) |
|
341 | 340 | lines = lines[start : start + context] |
|
342 | 341 | |
|
343 | 342 | for i,line in enumerate(lines): |
|
344 | 343 | show_arrow = (start + 1 + i == lineno) |
|
345 | 344 | linetpl = (frame is self.curframe or show_arrow) \ |
|
346 | 345 | and tpl_line_em \ |
|
347 | 346 | or tpl_line |
|
348 | 347 | ret.append(self.__format_line(linetpl, filename, |
|
349 | 348 | start + 1 + i, line, |
|
350 | 349 | arrow = show_arrow) ) |
|
351 | 350 | |
|
352 | 351 | return ''.join(ret) |
|
353 | 352 | |
|
354 | 353 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
355 | 354 | bp_mark = "" |
|
356 | 355 | bp_mark_color = "" |
|
357 | 356 | |
|
358 | 357 | scheme = self.color_scheme_table.active_scheme_name |
|
359 | 358 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
360 | 359 | if not err: line = new_line |
|
361 | 360 | |
|
362 | 361 | bp = None |
|
363 | 362 | if lineno in self.get_file_breaks(filename): |
|
364 | 363 | bps = self.get_breaks(filename, lineno) |
|
365 | 364 | bp = bps[-1] |
|
366 | 365 | |
|
367 | 366 | if bp: |
|
368 | 367 | Colors = self.color_scheme_table.active_colors |
|
369 | 368 | bp_mark = str(bp.number) |
|
370 | 369 | bp_mark_color = Colors.breakpoint_enabled |
|
371 | 370 | if not bp.enabled: |
|
372 | 371 | bp_mark_color = Colors.breakpoint_disabled |
|
373 | 372 | |
|
374 | 373 | numbers_width = 7 |
|
375 | 374 | if arrow: |
|
376 | 375 | # This is the line with the error |
|
377 | 376 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
378 | 377 | if pad >= 3: |
|
379 | 378 | marker = '-'*(pad-3) + '-> ' |
|
380 | 379 | elif pad == 2: |
|
381 | 380 | marker = '> ' |
|
382 | 381 | elif pad == 1: |
|
383 | 382 | marker = '>' |
|
384 | 383 | else: |
|
385 | 384 | marker = '' |
|
386 | 385 | num = '%s%s' % (marker, str(lineno)) |
|
387 | 386 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
388 | 387 | else: |
|
389 | 388 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
390 | 389 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
391 | 390 | |
|
392 | 391 | return line |
|
393 | 392 | |
|
394 | 393 | def list_command_pydb(self, arg): |
|
395 | 394 | """List command to use if we have a newer pydb installed""" |
|
396 | 395 | filename, first, last = OldPdb.parse_list_cmd(self, arg) |
|
397 | 396 | if filename is not None: |
|
398 | 397 | self.print_list_lines(filename, first, last) |
|
399 | 398 | |
|
400 | 399 | def print_list_lines(self, filename, first, last): |
|
401 | 400 | """The printing (as opposed to the parsing part of a 'list' |
|
402 | 401 | command.""" |
|
403 | 402 | try: |
|
404 | 403 | Colors = self.color_scheme_table.active_colors |
|
405 | 404 | ColorsNormal = Colors.Normal |
|
406 | 405 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
407 | 406 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
408 | 407 | src = [] |
|
409 | 408 | for lineno in range(first, last+1): |
|
410 | 409 | line = linecache.getline(filename, lineno) |
|
411 | 410 | if not line: |
|
412 | 411 | break |
|
413 | 412 | |
|
414 | 413 | if lineno == self.curframe.f_lineno: |
|
415 | 414 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
416 | 415 | else: |
|
417 | 416 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
418 | 417 | |
|
419 | 418 | src.append(line) |
|
420 | 419 | self.lineno = lineno |
|
421 | 420 | |
|
422 |
print >> |
|
|
421 | print >>io.stdout, ''.join(src) | |
|
423 | 422 | |
|
424 | 423 | except KeyboardInterrupt: |
|
425 | 424 | pass |
|
426 | 425 | |
|
427 | 426 | def do_list(self, arg): |
|
428 | 427 | self.lastcmd = 'list' |
|
429 | 428 | last = None |
|
430 | 429 | if arg: |
|
431 | 430 | try: |
|
432 | 431 | x = eval(arg, {}, {}) |
|
433 | 432 | if type(x) == type(()): |
|
434 | 433 | first, last = x |
|
435 | 434 | first = int(first) |
|
436 | 435 | last = int(last) |
|
437 | 436 | if last < first: |
|
438 | 437 | # Assume it's a count |
|
439 | 438 | last = first + last |
|
440 | 439 | else: |
|
441 | 440 | first = max(1, int(x) - 5) |
|
442 | 441 | except: |
|
443 | 442 | print '*** Error in argument:', `arg` |
|
444 | 443 | return |
|
445 | 444 | elif self.lineno is None: |
|
446 | 445 | first = max(1, self.curframe.f_lineno - 5) |
|
447 | 446 | else: |
|
448 | 447 | first = self.lineno + 1 |
|
449 | 448 | if last is None: |
|
450 | 449 | last = first + 10 |
|
451 | 450 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
452 | 451 | |
|
453 | 452 | # vds: >> |
|
454 | 453 | lineno = first |
|
455 | 454 | filename = self.curframe.f_code.co_filename |
|
456 | 455 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
457 | 456 | # vds: << |
|
458 | 457 | |
|
459 | 458 | do_l = do_list |
|
460 | 459 | |
|
461 | 460 | def do_pdef(self, arg): |
|
462 | 461 | """The debugger interface to magic_pdef""" |
|
463 | 462 | namespaces = [('Locals', self.curframe.f_locals), |
|
464 | 463 | ('Globals', self.curframe.f_globals)] |
|
465 | 464 | self.shell.magic_pdef(arg, namespaces=namespaces) |
|
466 | 465 | |
|
467 | 466 | def do_pdoc(self, arg): |
|
468 | 467 | """The debugger interface to magic_pdoc""" |
|
469 | 468 | namespaces = [('Locals', self.curframe.f_locals), |
|
470 | 469 | ('Globals', self.curframe.f_globals)] |
|
471 | 470 | self.shell.magic_pdoc(arg, namespaces=namespaces) |
|
472 | 471 | |
|
473 | 472 | def do_pinfo(self, arg): |
|
474 | 473 | """The debugger equivalant of ?obj""" |
|
475 | 474 | namespaces = [('Locals', self.curframe.f_locals), |
|
476 | 475 | ('Globals', self.curframe.f_globals)] |
|
477 | 476 | self.shell.magic_pinfo("pinfo %s" % arg, namespaces=namespaces) |
|
478 | 477 | |
|
479 | 478 | def checkline(self, filename, lineno): |
|
480 | 479 | """Check whether specified line seems to be executable. |
|
481 | 480 | |
|
482 | 481 | Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank |
|
483 | 482 | line or EOF). Warning: testing is not comprehensive. |
|
484 | 483 | """ |
|
485 | 484 | ####################################################################### |
|
486 | 485 | # XXX Hack! Use python-2.5 compatible code for this call, because with |
|
487 | 486 | # all of our changes, we've drifted from the pdb api in 2.6. For now, |
|
488 | 487 | # changing: |
|
489 | 488 | # |
|
490 | 489 | #line = linecache.getline(filename, lineno, self.curframe.f_globals) |
|
491 | 490 | # to: |
|
492 | 491 | # |
|
493 | 492 | line = linecache.getline(filename, lineno) |
|
494 | 493 | # |
|
495 | 494 | # does the trick. But in reality, we need to fix this by reconciling |
|
496 | 495 | # our updates with the new Pdb APIs in Python 2.6. |
|
497 | 496 | # |
|
498 | 497 | # End hack. The rest of this method is copied verbatim from 2.6 pdb.py |
|
499 | 498 | ####################################################################### |
|
500 | 499 | |
|
501 | 500 | if not line: |
|
502 | 501 | print >>self.stdout, 'End of file' |
|
503 | 502 | return 0 |
|
504 | 503 | line = line.strip() |
|
505 | 504 | # Don't allow setting breakpoint at a blank line |
|
506 | 505 | if (not line or (line[0] == '#') or |
|
507 | 506 | (line[:3] == '"""') or line[:3] == "'''"): |
|
508 | 507 | print >>self.stdout, '*** Blank or comment' |
|
509 | 508 | return 0 |
|
510 | 509 | return lineno |
@@ -1,330 +1,329 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Displayhook for IPython. |
|
3 | 3 | |
|
4 | 4 | This defines a callable class that IPython uses for `sys.displayhook`. |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Fernando Perez |
|
9 | 9 | * Brian Granger |
|
10 | 10 | * Robert Kern |
|
11 | 11 | """ |
|
12 | 12 | |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Copyright (C) 2008-2010 The IPython Development Team |
|
15 | 15 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
16 | 16 | # |
|
17 | 17 | # Distributed under the terms of the BSD License. The full license is in |
|
18 | 18 | # the file COPYING, distributed as part of this software. |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # Imports |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | import __builtin__ |
|
26 | 26 | |
|
27 | 27 | from IPython.config.configurable import Configurable |
|
28 | 28 | from IPython.core import prompts |
|
29 | import IPython.utils.generics | |
|
30 | import IPython.utils.io | |
|
29 | from IPython.utils import io | |
|
31 | 30 | from IPython.utils.traitlets import Instance, List |
|
32 | 31 | from IPython.utils.warn import warn |
|
33 | 32 | |
|
34 | 33 | #----------------------------------------------------------------------------- |
|
35 | 34 | # Main displayhook class |
|
36 | 35 | #----------------------------------------------------------------------------- |
|
37 | 36 | |
|
38 | 37 | # TODO: The DisplayHook class should be split into two classes, one that |
|
39 | 38 | # manages the prompts and their synchronization and another that just does the |
|
40 | 39 | # displayhook logic and calls into the prompt manager. |
|
41 | 40 | |
|
42 | 41 | # TODO: Move the various attributes (cache_size, colors, input_sep, |
|
43 | 42 | # output_sep, output_sep2, ps1, ps2, ps_out, pad_left). Some of these are also |
|
44 | 43 | # attributes of InteractiveShell. They should be on ONE object only and the |
|
45 | 44 | # other objects should ask that one object for their values. |
|
46 | 45 | |
|
47 | 46 | class DisplayHook(Configurable): |
|
48 | 47 | """The custom IPython displayhook to replace sys.displayhook. |
|
49 | 48 | |
|
50 | 49 | This class does many things, but the basic idea is that it is a callable |
|
51 | 50 | that gets called anytime user code returns a value. |
|
52 | 51 | |
|
53 | 52 | Currently this class does more than just the displayhook logic and that |
|
54 | 53 | extra logic should eventually be moved out of here. |
|
55 | 54 | """ |
|
56 | 55 | |
|
57 | 56 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
58 | 57 | |
|
59 | 58 | def __init__(self, shell=None, cache_size=1000, |
|
60 | 59 | colors='NoColor', input_sep='\n', |
|
61 | 60 | output_sep='\n', output_sep2='', |
|
62 | 61 | ps1 = None, ps2 = None, ps_out = None, pad_left=True, |
|
63 | 62 | config=None): |
|
64 | 63 | super(DisplayHook, self).__init__(shell=shell, config=config) |
|
65 | 64 | |
|
66 | 65 | cache_size_min = 3 |
|
67 | 66 | if cache_size <= 0: |
|
68 | 67 | self.do_full_cache = 0 |
|
69 | 68 | cache_size = 0 |
|
70 | 69 | elif cache_size < cache_size_min: |
|
71 | 70 | self.do_full_cache = 0 |
|
72 | 71 | cache_size = 0 |
|
73 | 72 | warn('caching was disabled (min value for cache size is %s).' % |
|
74 | 73 | cache_size_min,level=3) |
|
75 | 74 | else: |
|
76 | 75 | self.do_full_cache = 1 |
|
77 | 76 | |
|
78 | 77 | self.cache_size = cache_size |
|
79 | 78 | self.input_sep = input_sep |
|
80 | 79 | |
|
81 | 80 | # we need a reference to the user-level namespace |
|
82 | 81 | self.shell = shell |
|
83 | 82 | |
|
84 | 83 | # Set input prompt strings and colors |
|
85 | 84 | if cache_size == 0: |
|
86 | 85 | if ps1.find('%n') > -1 or ps1.find(r'\#') > -1 \ |
|
87 | 86 | or ps1.find(r'\N') > -1: |
|
88 | 87 | ps1 = '>>> ' |
|
89 | 88 | if ps2.find('%n') > -1 or ps2.find(r'\#') > -1 \ |
|
90 | 89 | or ps2.find(r'\N') > -1: |
|
91 | 90 | ps2 = '... ' |
|
92 | 91 | self.ps1_str = self._set_prompt_str(ps1,'In [\\#]: ','>>> ') |
|
93 | 92 | self.ps2_str = self._set_prompt_str(ps2,' .\\D.: ','... ') |
|
94 | 93 | self.ps_out_str = self._set_prompt_str(ps_out,'Out[\\#]: ','') |
|
95 | 94 | |
|
96 | 95 | self.color_table = prompts.PromptColors |
|
97 | 96 | self.prompt1 = prompts.Prompt1(self,sep=input_sep,prompt=self.ps1_str, |
|
98 | 97 | pad_left=pad_left) |
|
99 | 98 | self.prompt2 = prompts.Prompt2(self,prompt=self.ps2_str,pad_left=pad_left) |
|
100 | 99 | self.prompt_out = prompts.PromptOut(self,sep='',prompt=self.ps_out_str, |
|
101 | 100 | pad_left=pad_left) |
|
102 | 101 | self.set_colors(colors) |
|
103 | 102 | |
|
104 | 103 | # Store the last prompt string each time, we need it for aligning |
|
105 | 104 | # continuation and auto-rewrite prompts |
|
106 | 105 | self.last_prompt = '' |
|
107 | 106 | self.output_sep = output_sep |
|
108 | 107 | self.output_sep2 = output_sep2 |
|
109 | 108 | self._,self.__,self.___ = '','','' |
|
110 | 109 | |
|
111 | 110 | # these are deliberately global: |
|
112 | 111 | to_user_ns = {'_':self._,'__':self.__,'___':self.___} |
|
113 | 112 | self.shell.user_ns.update(to_user_ns) |
|
114 | 113 | |
|
115 | 114 | @property |
|
116 | 115 | def prompt_count(self): |
|
117 | 116 | return self.shell.execution_count |
|
118 | 117 | |
|
119 | 118 | def _set_prompt_str(self,p_str,cache_def,no_cache_def): |
|
120 | 119 | if p_str is None: |
|
121 | 120 | if self.do_full_cache: |
|
122 | 121 | return cache_def |
|
123 | 122 | else: |
|
124 | 123 | return no_cache_def |
|
125 | 124 | else: |
|
126 | 125 | return p_str |
|
127 | 126 | |
|
128 | 127 | def set_colors(self, colors): |
|
129 | 128 | """Set the active color scheme and configure colors for the three |
|
130 | 129 | prompt subsystems.""" |
|
131 | 130 | |
|
132 | 131 | # FIXME: This modifying of the global prompts.prompt_specials needs |
|
133 | 132 | # to be fixed. We need to refactor all of the prompts stuff to use |
|
134 | 133 | # proper configuration and traits notifications. |
|
135 | 134 | if colors.lower()=='nocolor': |
|
136 | 135 | prompts.prompt_specials = prompts.prompt_specials_nocolor |
|
137 | 136 | else: |
|
138 | 137 | prompts.prompt_specials = prompts.prompt_specials_color |
|
139 | 138 | |
|
140 | 139 | self.color_table.set_active_scheme(colors) |
|
141 | 140 | self.prompt1.set_colors() |
|
142 | 141 | self.prompt2.set_colors() |
|
143 | 142 | self.prompt_out.set_colors() |
|
144 | 143 | |
|
145 | 144 | #------------------------------------------------------------------------- |
|
146 | 145 | # Methods used in __call__. Override these methods to modify the behavior |
|
147 | 146 | # of the displayhook. |
|
148 | 147 | #------------------------------------------------------------------------- |
|
149 | 148 | |
|
150 | 149 | def check_for_underscore(self): |
|
151 | 150 | """Check if the user has set the '_' variable by hand.""" |
|
152 | 151 | # If something injected a '_' variable in __builtin__, delete |
|
153 | 152 | # ipython's automatic one so we don't clobber that. gettext() in |
|
154 | 153 | # particular uses _, so we need to stay away from it. |
|
155 | 154 | if '_' in __builtin__.__dict__: |
|
156 | 155 | try: |
|
157 | 156 | del self.shell.user_ns['_'] |
|
158 | 157 | except KeyError: |
|
159 | 158 | pass |
|
160 | 159 | |
|
161 | 160 | def quiet(self): |
|
162 | 161 | """Should we silence the display hook because of ';'?""" |
|
163 | 162 | # do not print output if input ends in ';' |
|
164 | 163 | try: |
|
165 | 164 | cell = self.shell.history_manager.input_hist_parsed[self.prompt_count] |
|
166 | 165 | if cell.rstrip().endswith(';'): |
|
167 | 166 | return True |
|
168 | 167 | except IndexError: |
|
169 | 168 | # some uses of ipshellembed may fail here |
|
170 | 169 | pass |
|
171 | 170 | return False |
|
172 | 171 | |
|
173 | 172 | def start_displayhook(self): |
|
174 | 173 | """Start the displayhook, initializing resources.""" |
|
175 | 174 | pass |
|
176 | 175 | |
|
177 | 176 | def write_output_prompt(self): |
|
178 | 177 | """Write the output prompt. |
|
179 | 178 | |
|
180 | 179 | The default implementation simply writes the prompt to |
|
181 |
``io. |
|
|
180 | ``io.stdout``. | |
|
182 | 181 | """ |
|
183 | 182 | # Use write, not print which adds an extra space. |
|
184 |
|
|
|
183 | io.stdout.write(self.output_sep) | |
|
185 | 184 | outprompt = str(self.prompt_out) |
|
186 | 185 | if self.do_full_cache: |
|
187 |
|
|
|
186 | io.stdout.write(outprompt) | |
|
188 | 187 | |
|
189 | 188 | def compute_format_data(self, result): |
|
190 | 189 | """Compute format data of the object to be displayed. |
|
191 | 190 | |
|
192 | 191 | The format data is a generalization of the :func:`repr` of an object. |
|
193 | 192 | In the default implementation the format data is a :class:`dict` of |
|
194 | 193 | key value pair where the keys are valid MIME types and the values |
|
195 | 194 | are JSON'able data structure containing the raw data for that MIME |
|
196 | 195 | type. It is up to frontends to determine pick a MIME to to use and |
|
197 | 196 | display that data in an appropriate manner. |
|
198 | 197 | |
|
199 | 198 | This method only computes the format data for the object and should |
|
200 | 199 | NOT actually print or write that to a stream. |
|
201 | 200 | |
|
202 | 201 | Parameters |
|
203 | 202 | ---------- |
|
204 | 203 | result : object |
|
205 | 204 | The Python object passed to the display hook, whose format will be |
|
206 | 205 | computed. |
|
207 | 206 | |
|
208 | 207 | Returns |
|
209 | 208 | ------- |
|
210 | 209 | format_data : dict |
|
211 | 210 | A :class:`dict` whose keys are valid MIME types and values are |
|
212 | 211 | JSON'able raw data for that MIME type. It is recommended that |
|
213 | 212 | all return values of this should always include the "text/plain" |
|
214 | 213 | MIME type representation of the object. |
|
215 | 214 | """ |
|
216 | 215 | return self.shell.display_formatter.format(result) |
|
217 | 216 | |
|
218 | 217 | def write_format_data(self, format_dict): |
|
219 | 218 | """Write the format data dict to the frontend. |
|
220 | 219 | |
|
221 | 220 | This default version of this method simply writes the plain text |
|
222 |
representation of the object to ``io. |
|
|
221 | representation of the object to ``io.stdout``. Subclasses should | |
|
223 | 222 | override this method to send the entire `format_dict` to the |
|
224 | 223 | frontends. |
|
225 | 224 | |
|
226 | 225 | Parameters |
|
227 | 226 | ---------- |
|
228 | 227 | format_dict : dict |
|
229 | 228 | The format dict for the object passed to `sys.displayhook`. |
|
230 | 229 | """ |
|
231 | 230 | # We want to print because we want to always make sure we have a |
|
232 | 231 | # newline, even if all the prompt separators are ''. This is the |
|
233 | 232 | # standard IPython behavior. |
|
234 | 233 | result_repr = format_dict['text/plain'] |
|
235 | 234 | if '\n' in result_repr: |
|
236 | 235 | # So that multi-line strings line up with the left column of |
|
237 | 236 | # the screen, instead of having the output prompt mess up |
|
238 | 237 | # their first line. |
|
239 | 238 | # We use the ps_out_str template instead of the expanded prompt |
|
240 | 239 | # because the expansion may add ANSI escapes that will interfere |
|
241 | 240 | # with our ability to determine whether or not we should add |
|
242 | 241 | # a newline. |
|
243 | 242 | if self.ps_out_str and not self.ps_out_str.endswith('\n'): |
|
244 | 243 | # But avoid extraneous empty lines. |
|
245 | 244 | result_repr = '\n' + result_repr |
|
246 | 245 | |
|
247 |
print >> |
|
|
246 | print >>io.stdout, result_repr | |
|
248 | 247 | |
|
249 | 248 | def update_user_ns(self, result): |
|
250 | 249 | """Update user_ns with various things like _, __, _1, etc.""" |
|
251 | 250 | |
|
252 | 251 | # Avoid recursive reference when displaying _oh/Out |
|
253 | 252 | if result is not self.shell.user_ns['_oh']: |
|
254 | 253 | if len(self.shell.user_ns['_oh']) >= self.cache_size and self.do_full_cache: |
|
255 | 254 | warn('Output cache limit (currently '+ |
|
256 | 255 | `self.cache_size`+' entries) hit.\n' |
|
257 | 256 | 'Flushing cache and resetting history counter...\n' |
|
258 | 257 | 'The only history variables available will be _,__,___ and _1\n' |
|
259 | 258 | 'with the current result.') |
|
260 | 259 | |
|
261 | 260 | self.flush() |
|
262 | 261 | # Don't overwrite '_' and friends if '_' is in __builtin__ (otherwise |
|
263 | 262 | # we cause buggy behavior for things like gettext). |
|
264 | 263 | |
|
265 | 264 | if '_' not in __builtin__.__dict__: |
|
266 | 265 | self.___ = self.__ |
|
267 | 266 | self.__ = self._ |
|
268 | 267 | self._ = result |
|
269 | 268 | self.shell.user_ns.update({'_':self._, |
|
270 | 269 | '__':self.__, |
|
271 | 270 | '___':self.___}) |
|
272 | 271 | |
|
273 | 272 | # hackish access to top-level namespace to create _1,_2... dynamically |
|
274 | 273 | to_main = {} |
|
275 | 274 | if self.do_full_cache: |
|
276 | 275 | new_result = '_'+`self.prompt_count` |
|
277 | 276 | to_main[new_result] = result |
|
278 | 277 | self.shell.user_ns.update(to_main) |
|
279 | 278 | self.shell.user_ns['_oh'][self.prompt_count] = result |
|
280 | 279 | |
|
281 | 280 | def log_output(self, format_dict): |
|
282 | 281 | """Log the output.""" |
|
283 | 282 | if self.shell.logger.log_output: |
|
284 | 283 | self.shell.logger.log_write(format_dict['text/plain'], 'output') |
|
285 | 284 | self.shell.history_manager.output_hist_reprs[self.prompt_count] = \ |
|
286 | 285 | format_dict['text/plain'] |
|
287 | 286 | |
|
288 | 287 | def finish_displayhook(self): |
|
289 | 288 | """Finish up all displayhook activities.""" |
|
290 |
|
|
|
291 |
|
|
|
289 | io.stdout.write(self.output_sep2) | |
|
290 | io.stdout.flush() | |
|
292 | 291 | |
|
293 | 292 | def __call__(self, result=None): |
|
294 | 293 | """Printing with history cache management. |
|
295 | 294 | |
|
296 | 295 | This is invoked everytime the interpreter needs to print, and is |
|
297 | 296 | activated by setting the variable sys.displayhook to it. |
|
298 | 297 | """ |
|
299 | 298 | self.check_for_underscore() |
|
300 | 299 | if result is not None and not self.quiet(): |
|
301 | 300 | self.start_displayhook() |
|
302 | 301 | self.write_output_prompt() |
|
303 | 302 | format_dict = self.compute_format_data(result) |
|
304 | 303 | self.write_format_data(format_dict) |
|
305 | 304 | self.update_user_ns(result) |
|
306 | 305 | self.log_output(format_dict) |
|
307 | 306 | self.finish_displayhook() |
|
308 | 307 | |
|
309 | 308 | def flush(self): |
|
310 | 309 | if not self.do_full_cache: |
|
311 | 310 | raise ValueError,"You shouldn't have reached the cache flush "\ |
|
312 | 311 | "if full caching is not enabled!" |
|
313 | 312 | # delete auto-generated vars from global namespace |
|
314 | 313 | |
|
315 | 314 | for n in range(1,self.prompt_count + 1): |
|
316 | 315 | key = '_'+`n` |
|
317 | 316 | try: |
|
318 | 317 | del self.shell.user_ns[key] |
|
319 | 318 | except: pass |
|
320 | 319 | self.shell.user_ns['_oh'].clear() |
|
321 | 320 | |
|
322 | 321 | # Release our own references to objects: |
|
323 | 322 | self._, self.__, self.___ = '', '', '' |
|
324 | 323 | |
|
325 | 324 | if '_' not in __builtin__.__dict__: |
|
326 | 325 | self.shell.user_ns.update({'_':None,'__':None, '___':None}) |
|
327 | 326 | import gc |
|
328 | 327 | # TODO: Is this really needed? |
|
329 | 328 | gc.collect() |
|
330 | 329 |
@@ -1,145 +1,145 b'' | |||
|
1 | 1 | """An interface for publishing rich data to frontends. |
|
2 | 2 | |
|
3 | 3 | There are two components of the display system: |
|
4 | 4 | |
|
5 | 5 | * Display formatters, which take a Python object and compute the |
|
6 | 6 | representation of the object in various formats (text, HTML, SVg, etc.). |
|
7 | 7 | * The display publisher that is used to send the representation data to the |
|
8 | 8 | various frontends. |
|
9 | 9 | |
|
10 | 10 | This module defines the logic display publishing. The display publisher uses |
|
11 | 11 | the ``display_data`` message type that is defined in the IPython messaging |
|
12 | 12 | spec. |
|
13 | 13 | |
|
14 | 14 | Authors: |
|
15 | 15 | |
|
16 | 16 | * Brian Granger |
|
17 | 17 | """ |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Copyright (C) 2008-2010 The IPython Development Team |
|
21 | 21 | # |
|
22 | 22 | # Distributed under the terms of the BSD License. The full license is in |
|
23 | 23 | # the file COPYING, distributed as part of this software. |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | # Imports |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | |
|
30 | 30 | from __future__ import print_function |
|
31 | 31 | |
|
32 | 32 | from IPython.config.configurable import Configurable |
|
33 | 33 | |
|
34 | 34 | #----------------------------------------------------------------------------- |
|
35 | 35 | # Main payload class |
|
36 | 36 | #----------------------------------------------------------------------------- |
|
37 | 37 | |
|
38 | 38 | class DisplayPublisher(Configurable): |
|
39 | 39 | """A traited class that publishes display data to frontends. |
|
40 | 40 | |
|
41 | 41 | Instances of this class are created by the main IPython object and should |
|
42 | 42 | be accessed there. |
|
43 | 43 | """ |
|
44 | 44 | |
|
45 | 45 | def _validate_data(self, source, data, metadata=None): |
|
46 | 46 | """Validate the display data. |
|
47 | 47 | |
|
48 | 48 | Parameters |
|
49 | 49 | ---------- |
|
50 | 50 | source : str |
|
51 | 51 | The fully dotted name of the callable that created the data, like |
|
52 | 52 | :func:`foo.bar.my_formatter`. |
|
53 | 53 | data : dict |
|
54 | 54 | The formata data dictionary. |
|
55 | 55 | metadata : dict |
|
56 | 56 | Any metadata for the data. |
|
57 | 57 | """ |
|
58 | 58 | |
|
59 | 59 | if not isinstance(source, str): |
|
60 | 60 | raise TypeError('source must be a str, got: %r' % source) |
|
61 | 61 | if not isinstance(data, dict): |
|
62 | 62 | raise TypeError('data must be a dict, got: %r' % data) |
|
63 | 63 | if metadata is not None: |
|
64 | 64 | if not isinstance(metadata, dict): |
|
65 | 65 | raise TypeError('metadata must be a dict, got: %r' % data) |
|
66 | 66 | |
|
67 | 67 | def publish(self, source, data, metadata=None): |
|
68 | 68 | """Publish data and metadata to all frontends. |
|
69 | 69 | |
|
70 | 70 | See the ``display_data`` message in the messaging documentation for |
|
71 | 71 | more details about this message type. |
|
72 | 72 | |
|
73 | 73 | The following MIME types are currently implemented: |
|
74 | 74 | |
|
75 | 75 | * text/plain |
|
76 | 76 | * text/html |
|
77 | 77 | * text/latex |
|
78 | 78 | * application/json |
|
79 | 79 | * image/png |
|
80 | 80 | * immage/svg+xml |
|
81 | 81 | |
|
82 | 82 | Parameters |
|
83 | 83 | ---------- |
|
84 | 84 | source : str |
|
85 | 85 | A string that give the function or method that created the data, |
|
86 | 86 | such as 'IPython.core.page'. |
|
87 | 87 | data : dict |
|
88 | 88 | A dictionary having keys that are valid MIME types (like |
|
89 | 89 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
90 | 90 | that MIME type. The data itself must be a JSON'able data |
|
91 | 91 | structure. Minimally all data should have the 'text/plain' data, |
|
92 | 92 | which can be displayed by all frontends. If more than the plain |
|
93 | 93 | text is given, it is up to the frontend to decide which |
|
94 | 94 | representation to use. |
|
95 | 95 | metadata : dict |
|
96 | 96 | A dictionary for metadata related to the data. This can contain |
|
97 | 97 | arbitrary key, value pairs that frontends can use to interpret |
|
98 | 98 | the data. |
|
99 | 99 | """ |
|
100 | 100 | from IPython.utils import io |
|
101 |
# The default is to simply write the plain text data using io. |
|
|
101 | # The default is to simply write the plain text data using io.stdout. | |
|
102 | 102 | if data.has_key('text/plain'): |
|
103 |
print(data['text/plain'], file=io. |
|
|
103 | print(data['text/plain'], file=io.stdout) | |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | def publish_display_data(self, source, data, metadata=None): |
|
107 | 107 | """Publish data and metadata to all frontends. |
|
108 | 108 | |
|
109 | 109 | See the ``display_data`` message in the messaging documentation for |
|
110 | 110 | more details about this message type. |
|
111 | 111 | |
|
112 | 112 | The following MIME types are currently implemented: |
|
113 | 113 | |
|
114 | 114 | * text/plain |
|
115 | 115 | * text/html |
|
116 | 116 | * text/latex |
|
117 | 117 | * application/json |
|
118 | 118 | * image/png |
|
119 | 119 | * immage/svg+xml |
|
120 | 120 | |
|
121 | 121 | Parameters |
|
122 | 122 | ---------- |
|
123 | 123 | source : str |
|
124 | 124 | A string that give the function or method that created the data, |
|
125 | 125 | such as 'IPython.core.page'. |
|
126 | 126 | data : dict |
|
127 | 127 | A dictionary having keys that are valid MIME types (like |
|
128 | 128 | 'text/plain' or 'image/svg+xml') and values that are the data for |
|
129 | 129 | that MIME type. The data itself must be a JSON'able data |
|
130 | 130 | structure. Minimally all data should have the 'text/plain' data, |
|
131 | 131 | which can be displayed by all frontends. If more than the plain |
|
132 | 132 | text is given, it is up to the frontend to decide which |
|
133 | 133 | representation to use. |
|
134 | 134 | metadata : dict |
|
135 | 135 | A dictionary for metadata related to the data. This can contain |
|
136 | 136 | arbitrary key, value pairs that frontends can use to interpret |
|
137 | 137 | the data. |
|
138 | 138 | """ |
|
139 | 139 | from IPython.core.interactiveshell import InteractiveShell |
|
140 | 140 | InteractiveShell.instance().display_pub.publish( |
|
141 | 141 | source, |
|
142 | 142 | data, |
|
143 | 143 | metadata |
|
144 | 144 | ) |
|
145 | 145 |
@@ -1,803 +1,802 b'' | |||
|
1 | 1 | """ History related magics and functionality """ |
|
2 | 2 | #----------------------------------------------------------------------------- |
|
3 | 3 | # Copyright (C) 2010 The IPython Development Team. |
|
4 | 4 | # |
|
5 | 5 | # Distributed under the terms of the BSD License. |
|
6 | 6 | # |
|
7 | 7 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | 8 | #----------------------------------------------------------------------------- |
|
9 | 9 | |
|
10 | 10 | #----------------------------------------------------------------------------- |
|
11 | 11 | # Imports |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | from __future__ import print_function |
|
14 | 14 | |
|
15 | 15 | # Stdlib imports |
|
16 | 16 | import atexit |
|
17 | 17 | import datetime |
|
18 | 18 | import os |
|
19 | 19 | import re |
|
20 | 20 | import sqlite3 |
|
21 | 21 | import threading |
|
22 | 22 | |
|
23 | 23 | # Our own packages |
|
24 | 24 | from IPython.config.configurable import Configurable |
|
25 | import IPython.utils.io | |
|
26 | 25 | |
|
27 | 26 | from IPython.testing import decorators as testdec |
|
28 |
from IPython.utils |
|
|
27 | from IPython.utils import io | |
|
29 | 28 | from IPython.utils.traitlets import Bool, Dict, Instance, Int, List, Unicode |
|
30 | 29 | from IPython.utils.warn import warn |
|
31 | 30 | |
|
32 | 31 | #----------------------------------------------------------------------------- |
|
33 | 32 | # Classes and functions |
|
34 | 33 | #----------------------------------------------------------------------------- |
|
35 | 34 | |
|
36 | 35 | class HistoryManager(Configurable): |
|
37 | 36 | """A class to organize all history-related functionality in one place. |
|
38 | 37 | """ |
|
39 | 38 | # Public interface |
|
40 | 39 | |
|
41 | 40 | # An instance of the IPython shell we are attached to |
|
42 | 41 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
43 | 42 | # Lists to hold processed and raw history. These start with a blank entry |
|
44 | 43 | # so that we can index them starting from 1 |
|
45 | 44 | input_hist_parsed = List([""]) |
|
46 | 45 | input_hist_raw = List([""]) |
|
47 | 46 | # A list of directories visited during session |
|
48 | 47 | dir_hist = List() |
|
49 | 48 | def _dir_hist_default(self): |
|
50 | 49 | try: |
|
51 | 50 | return [os.getcwd()] |
|
52 | 51 | except OSError: |
|
53 | 52 | return [] |
|
54 | 53 | |
|
55 | 54 | # A dict of output history, keyed with ints from the shell's |
|
56 | 55 | # execution count. |
|
57 | 56 | output_hist = Dict() |
|
58 | 57 | # The text/plain repr of outputs. |
|
59 | 58 | output_hist_reprs = Dict() |
|
60 | 59 | |
|
61 | 60 | # String holding the path to the history file |
|
62 | 61 | hist_file = Unicode(config=True) |
|
63 | 62 | |
|
64 | 63 | # The SQLite database |
|
65 | 64 | db = Instance(sqlite3.Connection) |
|
66 | 65 | # The number of the current session in the history database |
|
67 | 66 | session_number = Int() |
|
68 | 67 | # Should we log output to the database? (default no) |
|
69 | 68 | db_log_output = Bool(False, config=True) |
|
70 | 69 | # Write to database every x commands (higher values save disk access & power) |
|
71 | 70 | # Values of 1 or less effectively disable caching. |
|
72 | 71 | db_cache_size = Int(0, config=True) |
|
73 | 72 | # The input and output caches |
|
74 | 73 | db_input_cache = List() |
|
75 | 74 | db_output_cache = List() |
|
76 | 75 | |
|
77 | 76 | # History saving in separate thread |
|
78 | 77 | save_thread = Instance('IPython.core.history.HistorySavingThread') |
|
79 | 78 | # N.B. Event is a function returning an instance of _Event. |
|
80 | 79 | save_flag = Instance(threading._Event) |
|
81 | 80 | |
|
82 | 81 | # Private interface |
|
83 | 82 | # Variables used to store the three last inputs from the user. On each new |
|
84 | 83 | # history update, we populate the user's namespace with these, shifted as |
|
85 | 84 | # necessary. |
|
86 | 85 | _i00 = Unicode(u'') |
|
87 | 86 | _i = Unicode(u'') |
|
88 | 87 | _ii = Unicode(u'') |
|
89 | 88 | _iii = Unicode(u'') |
|
90 | 89 | |
|
91 | 90 | # A regex matching all forms of the exit command, so that we don't store |
|
92 | 91 | # them in the history (it's annoying to rewind the first entry and land on |
|
93 | 92 | # an exit call). |
|
94 | 93 | _exit_re = re.compile(r"(exit|quit)(\s*\(.*\))?$") |
|
95 | 94 | |
|
96 | 95 | def __init__(self, shell, config=None, **traits): |
|
97 | 96 | """Create a new history manager associated with a shell instance. |
|
98 | 97 | """ |
|
99 | 98 | # We need a pointer back to the shell for various tasks. |
|
100 | 99 | super(HistoryManager, self).__init__(shell=shell, config=config, |
|
101 | 100 | **traits) |
|
102 | 101 | |
|
103 | 102 | if self.hist_file == u'': |
|
104 | 103 | # No one has set the hist_file, yet. |
|
105 | 104 | if shell.profile: |
|
106 | 105 | histfname = 'history-%s' % shell.profile |
|
107 | 106 | else: |
|
108 | 107 | histfname = 'history' |
|
109 | 108 | self.hist_file = os.path.join(shell.ipython_dir, histfname + '.sqlite') |
|
110 | 109 | |
|
111 | 110 | try: |
|
112 | 111 | self.init_db() |
|
113 | 112 | except sqlite3.DatabaseError: |
|
114 | 113 | if os.path.isfile(self.hist_file): |
|
115 | 114 | # Try to move the file out of the way. |
|
116 | 115 | newpath = os.path.join(self.shell.ipython_dir, "hist-corrupt.sqlite") |
|
117 | 116 | os.rename(self.hist_file, newpath) |
|
118 | 117 | print("ERROR! History file wasn't a valid SQLite database.", |
|
119 | 118 | "It was moved to %s" % newpath, "and a new file created.") |
|
120 | 119 | self.init_db() |
|
121 | 120 | else: |
|
122 | 121 | # The hist_file is probably :memory: or something else. |
|
123 | 122 | raise |
|
124 | 123 | |
|
125 | 124 | self.save_flag = threading.Event() |
|
126 | 125 | self.db_input_cache_lock = threading.Lock() |
|
127 | 126 | self.db_output_cache_lock = threading.Lock() |
|
128 | 127 | self.save_thread = HistorySavingThread(self) |
|
129 | 128 | self.save_thread.start() |
|
130 | 129 | |
|
131 | 130 | self.new_session() |
|
132 | 131 | |
|
133 | 132 | |
|
134 | 133 | def init_db(self): |
|
135 | 134 | """Connect to the database, and create tables if necessary.""" |
|
136 | 135 | self.db = sqlite3.connect(self.hist_file) |
|
137 | 136 | self.db.execute("""CREATE TABLE IF NOT EXISTS sessions (session integer |
|
138 | 137 | primary key autoincrement, start timestamp, |
|
139 | 138 | end timestamp, num_cmds integer, remark text)""") |
|
140 | 139 | self.db.execute("""CREATE TABLE IF NOT EXISTS history |
|
141 | 140 | (session integer, line integer, source text, source_raw text, |
|
142 | 141 | PRIMARY KEY (session, line))""") |
|
143 | 142 | # Output history is optional, but ensure the table's there so it can be |
|
144 | 143 | # enabled later. |
|
145 | 144 | self.db.execute("""CREATE TABLE IF NOT EXISTS output_history |
|
146 | 145 | (session integer, line integer, output text, |
|
147 | 146 | PRIMARY KEY (session, line))""") |
|
148 | 147 | self.db.commit() |
|
149 | 148 | |
|
150 | 149 | def new_session(self, conn=None): |
|
151 | 150 | """Get a new session number.""" |
|
152 | 151 | if conn is None: |
|
153 | 152 | conn = self.db |
|
154 | 153 | |
|
155 | 154 | with conn: |
|
156 | 155 | cur = conn.execute("""INSERT INTO sessions VALUES (NULL, ?, NULL, |
|
157 | 156 | NULL, "") """, (datetime.datetime.now(),)) |
|
158 | 157 | self.session_number = cur.lastrowid |
|
159 | 158 | |
|
160 | 159 | def end_session(self): |
|
161 | 160 | """Close the database session, filling in the end time and line count.""" |
|
162 | 161 | self.writeout_cache() |
|
163 | 162 | with self.db: |
|
164 | 163 | self.db.execute("""UPDATE sessions SET end=?, num_cmds=? WHERE |
|
165 | 164 | session==?""", (datetime.datetime.now(), |
|
166 | 165 | len(self.input_hist_parsed)-1, self.session_number)) |
|
167 | 166 | self.session_number = 0 |
|
168 | 167 | |
|
169 | 168 | def name_session(self, name): |
|
170 | 169 | """Give the current session a name in the history database.""" |
|
171 | 170 | with self.db: |
|
172 | 171 | self.db.execute("UPDATE sessions SET remark=? WHERE session==?", |
|
173 | 172 | (name, self.session_number)) |
|
174 | 173 | |
|
175 | 174 | def reset(self, new_session=True): |
|
176 | 175 | """Clear the session history, releasing all object references, and |
|
177 | 176 | optionally open a new session.""" |
|
178 | 177 | self.output_hist.clear() |
|
179 | 178 | # The directory history can't be completely empty |
|
180 | 179 | self.dir_hist[:] = [os.getcwd()] |
|
181 | 180 | |
|
182 | 181 | if new_session: |
|
183 | 182 | if self.session_number: |
|
184 | 183 | self.end_session() |
|
185 | 184 | self.input_hist_parsed[:] = [""] |
|
186 | 185 | self.input_hist_raw[:] = [""] |
|
187 | 186 | self.new_session() |
|
188 | 187 | |
|
189 | 188 | ## ------------------------------- |
|
190 | 189 | ## Methods for retrieving history: |
|
191 | 190 | ## ------------------------------- |
|
192 | 191 | def _run_sql(self, sql, params, raw=True, output=False): |
|
193 | 192 | """Prepares and runs an SQL query for the history database. |
|
194 | 193 | |
|
195 | 194 | Parameters |
|
196 | 195 | ---------- |
|
197 | 196 | sql : str |
|
198 | 197 | Any filtering expressions to go after SELECT ... FROM ... |
|
199 | 198 | params : tuple |
|
200 | 199 | Parameters passed to the SQL query (to replace "?") |
|
201 | 200 | raw, output : bool |
|
202 | 201 | See :meth:`get_range` |
|
203 | 202 | |
|
204 | 203 | Returns |
|
205 | 204 | ------- |
|
206 | 205 | Tuples as :meth:`get_range` |
|
207 | 206 | """ |
|
208 | 207 | toget = 'source_raw' if raw else 'source' |
|
209 | 208 | sqlfrom = "history" |
|
210 | 209 | if output: |
|
211 | 210 | sqlfrom = "history LEFT JOIN output_history USING (session, line)" |
|
212 | 211 | toget = "history.%s, output_history.output" % toget |
|
213 | 212 | cur = self.db.execute("SELECT session, line, %s FROM %s " %\ |
|
214 | 213 | (toget, sqlfrom) + sql, params) |
|
215 | 214 | if output: # Regroup into 3-tuples, and parse JSON |
|
216 | 215 | return ((ses, lin, (inp, out)) for ses, lin, inp, out in cur) |
|
217 | 216 | return cur |
|
218 | 217 | |
|
219 | 218 | |
|
220 | 219 | def get_tail(self, n=10, raw=True, output=False, include_latest=False): |
|
221 | 220 | """Get the last n lines from the history database. |
|
222 | 221 | |
|
223 | 222 | Parameters |
|
224 | 223 | ---------- |
|
225 | 224 | n : int |
|
226 | 225 | The number of lines to get |
|
227 | 226 | raw, output : bool |
|
228 | 227 | See :meth:`get_range` |
|
229 | 228 | include_latest : bool |
|
230 | 229 | If False (default), n+1 lines are fetched, and the latest one |
|
231 | 230 | is discarded. This is intended to be used where the function |
|
232 | 231 | is called by a user command, which it should not return. |
|
233 | 232 | |
|
234 | 233 | Returns |
|
235 | 234 | ------- |
|
236 | 235 | Tuples as :meth:`get_range` |
|
237 | 236 | """ |
|
238 | 237 | self.writeout_cache() |
|
239 | 238 | if not include_latest: |
|
240 | 239 | n += 1 |
|
241 | 240 | cur = self._run_sql("ORDER BY session DESC, line DESC LIMIT ?", |
|
242 | 241 | (n,), raw=raw, output=output) |
|
243 | 242 | if not include_latest: |
|
244 | 243 | return reversed(list(cur)[1:]) |
|
245 | 244 | return reversed(list(cur)) |
|
246 | 245 | |
|
247 | 246 | def search(self, pattern="*", raw=True, search_raw=True, |
|
248 | 247 | output=False): |
|
249 | 248 | """Search the database using unix glob-style matching (wildcards |
|
250 | 249 | * and ?). |
|
251 | 250 | |
|
252 | 251 | Parameters |
|
253 | 252 | ---------- |
|
254 | 253 | pattern : str |
|
255 | 254 | The wildcarded pattern to match when searching |
|
256 | 255 | search_raw : bool |
|
257 | 256 | If True, search the raw input, otherwise, the parsed input |
|
258 | 257 | raw, output : bool |
|
259 | 258 | See :meth:`get_range` |
|
260 | 259 | |
|
261 | 260 | Returns |
|
262 | 261 | ------- |
|
263 | 262 | Tuples as :meth:`get_range` |
|
264 | 263 | """ |
|
265 | 264 | tosearch = "source_raw" if search_raw else "source" |
|
266 | 265 | if output: |
|
267 | 266 | tosearch = "history." + tosearch |
|
268 | 267 | self.writeout_cache() |
|
269 | 268 | return self._run_sql("WHERE %s GLOB ?" % tosearch, (pattern,), |
|
270 | 269 | raw=raw, output=output) |
|
271 | 270 | |
|
272 | 271 | def _get_range_session(self, start=1, stop=None, raw=True, output=False): |
|
273 | 272 | """Get input and output history from the current session. Called by |
|
274 | 273 | get_range, and takes similar parameters.""" |
|
275 | 274 | input_hist = self.input_hist_raw if raw else self.input_hist_parsed |
|
276 | 275 | |
|
277 | 276 | n = len(input_hist) |
|
278 | 277 | if start < 0: |
|
279 | 278 | start += n |
|
280 | 279 | if not stop: |
|
281 | 280 | stop = n |
|
282 | 281 | elif stop < 0: |
|
283 | 282 | stop += n |
|
284 | 283 | |
|
285 | 284 | for i in range(start, stop): |
|
286 | 285 | if output: |
|
287 | 286 | line = (input_hist[i], self.output_hist_reprs.get(i)) |
|
288 | 287 | else: |
|
289 | 288 | line = input_hist[i] |
|
290 | 289 | yield (0, i, line) |
|
291 | 290 | |
|
292 | 291 | def get_range(self, session=0, start=1, stop=None, raw=True,output=False): |
|
293 | 292 | """Retrieve input by session. |
|
294 | 293 | |
|
295 | 294 | Parameters |
|
296 | 295 | ---------- |
|
297 | 296 | session : int |
|
298 | 297 | Session number to retrieve. The current session is 0, and negative |
|
299 | 298 | numbers count back from current session, so -1 is previous session. |
|
300 | 299 | start : int |
|
301 | 300 | First line to retrieve. |
|
302 | 301 | stop : int |
|
303 | 302 | End of line range (excluded from output itself). If None, retrieve |
|
304 | 303 | to the end of the session. |
|
305 | 304 | raw : bool |
|
306 | 305 | If True, return untranslated input |
|
307 | 306 | output : bool |
|
308 | 307 | If True, attempt to include output. This will be 'real' Python |
|
309 | 308 | objects for the current session, or text reprs from previous |
|
310 | 309 | sessions if db_log_output was enabled at the time. Where no output |
|
311 | 310 | is found, None is used. |
|
312 | 311 | |
|
313 | 312 | Returns |
|
314 | 313 | ------- |
|
315 | 314 | An iterator over the desired lines. Each line is a 3-tuple, either |
|
316 | 315 | (session, line, input) if output is False, or |
|
317 | 316 | (session, line, (input, output)) if output is True. |
|
318 | 317 | """ |
|
319 | 318 | if session == 0 or session==self.session_number: # Current session |
|
320 | 319 | return self._get_range_session(start, stop, raw, output) |
|
321 | 320 | if session < 0: |
|
322 | 321 | session += self.session_number |
|
323 | 322 | |
|
324 | 323 | if stop: |
|
325 | 324 | lineclause = "line >= ? AND line < ?" |
|
326 | 325 | params = (session, start, stop) |
|
327 | 326 | else: |
|
328 | 327 | lineclause = "line>=?" |
|
329 | 328 | params = (session, start) |
|
330 | 329 | |
|
331 | 330 | return self._run_sql("WHERE session==? AND %s""" % lineclause, |
|
332 | 331 | params, raw=raw, output=output) |
|
333 | 332 | |
|
334 | 333 | def get_range_by_str(self, rangestr, raw=True, output=False): |
|
335 | 334 | """Get lines of history from a string of ranges, as used by magic |
|
336 | 335 | commands %hist, %save, %macro, etc. |
|
337 | 336 | |
|
338 | 337 | Parameters |
|
339 | 338 | ---------- |
|
340 | 339 | rangestr : str |
|
341 | 340 | A string specifying ranges, e.g. "5 ~2/1-4". See |
|
342 | 341 | :func:`magic_history` for full details. |
|
343 | 342 | raw, output : bool |
|
344 | 343 | As :meth:`get_range` |
|
345 | 344 | |
|
346 | 345 | Returns |
|
347 | 346 | ------- |
|
348 | 347 | Tuples as :meth:`get_range` |
|
349 | 348 | """ |
|
350 | 349 | for sess, s, e in extract_hist_ranges(rangestr): |
|
351 | 350 | for line in self.get_range(sess, s, e, raw=raw, output=output): |
|
352 | 351 | yield line |
|
353 | 352 | |
|
354 | 353 | ## ---------------------------- |
|
355 | 354 | ## Methods for storing history: |
|
356 | 355 | ## ---------------------------- |
|
357 | 356 | def store_inputs(self, line_num, source, source_raw=None): |
|
358 | 357 | """Store source and raw input in history and create input cache |
|
359 | 358 | variables _i*. |
|
360 | 359 | |
|
361 | 360 | Parameters |
|
362 | 361 | ---------- |
|
363 | 362 | line_num : int |
|
364 | 363 | The prompt number of this input. |
|
365 | 364 | |
|
366 | 365 | source : str |
|
367 | 366 | Python input. |
|
368 | 367 | |
|
369 | 368 | source_raw : str, optional |
|
370 | 369 | If given, this is the raw input without any IPython transformations |
|
371 | 370 | applied to it. If not given, ``source`` is used. |
|
372 | 371 | """ |
|
373 | 372 | if source_raw is None: |
|
374 | 373 | source_raw = source |
|
375 | 374 | source = source.rstrip('\n') |
|
376 | 375 | source_raw = source_raw.rstrip('\n') |
|
377 | 376 | |
|
378 | 377 | # do not store exit/quit commands |
|
379 | 378 | if self._exit_re.match(source_raw.strip()): |
|
380 | 379 | return |
|
381 | 380 | |
|
382 | 381 | self.input_hist_parsed.append(source) |
|
383 | 382 | self.input_hist_raw.append(source_raw) |
|
384 | 383 | |
|
385 | 384 | with self.db_input_cache_lock: |
|
386 | 385 | self.db_input_cache.append((line_num, source, source_raw)) |
|
387 | 386 | # Trigger to flush cache and write to DB. |
|
388 | 387 | if len(self.db_input_cache) >= self.db_cache_size: |
|
389 | 388 | self.save_flag.set() |
|
390 | 389 | |
|
391 | 390 | # update the auto _i variables |
|
392 | 391 | self._iii = self._ii |
|
393 | 392 | self._ii = self._i |
|
394 | 393 | self._i = self._i00 |
|
395 | 394 | self._i00 = source_raw |
|
396 | 395 | |
|
397 | 396 | # hackish access to user namespace to create _i1,_i2... dynamically |
|
398 | 397 | new_i = '_i%s' % line_num |
|
399 | 398 | to_main = {'_i': self._i, |
|
400 | 399 | '_ii': self._ii, |
|
401 | 400 | '_iii': self._iii, |
|
402 | 401 | new_i : self._i00 } |
|
403 | 402 | self.shell.user_ns.update(to_main) |
|
404 | 403 | |
|
405 | 404 | def store_output(self, line_num): |
|
406 | 405 | """If database output logging is enabled, this saves all the |
|
407 | 406 | outputs from the indicated prompt number to the database. It's |
|
408 | 407 | called by run_cell after code has been executed. |
|
409 | 408 | |
|
410 | 409 | Parameters |
|
411 | 410 | ---------- |
|
412 | 411 | line_num : int |
|
413 | 412 | The line number from which to save outputs |
|
414 | 413 | """ |
|
415 | 414 | if (not self.db_log_output) or (line_num not in self.output_hist_reprs): |
|
416 | 415 | return |
|
417 | 416 | output = self.output_hist_reprs[line_num] |
|
418 | 417 | |
|
419 | 418 | with self.db_output_cache_lock: |
|
420 | 419 | self.db_output_cache.append((line_num, output)) |
|
421 | 420 | if self.db_cache_size <= 1: |
|
422 | 421 | self.save_flag.set() |
|
423 | 422 | |
|
424 | 423 | def _writeout_input_cache(self, conn): |
|
425 | 424 | with conn: |
|
426 | 425 | for line in self.db_input_cache: |
|
427 | 426 | conn.execute("INSERT INTO history VALUES (?, ?, ?, ?)", |
|
428 | 427 | (self.session_number,)+line) |
|
429 | 428 | |
|
430 | 429 | def _writeout_output_cache(self, conn): |
|
431 | 430 | with conn: |
|
432 | 431 | for line in self.db_output_cache: |
|
433 | 432 | conn.execute("INSERT INTO output_history VALUES (?, ?, ?)", |
|
434 | 433 | (self.session_number,)+line) |
|
435 | 434 | |
|
436 | 435 | def writeout_cache(self, conn=None): |
|
437 | 436 | """Write any entries in the cache to the database.""" |
|
438 | 437 | if conn is None: |
|
439 | 438 | conn = self.db |
|
440 | 439 | |
|
441 | 440 | with self.db_input_cache_lock: |
|
442 | 441 | try: |
|
443 | 442 | self._writeout_input_cache(conn) |
|
444 | 443 | except sqlite3.IntegrityError: |
|
445 | 444 | self.new_session(conn) |
|
446 | 445 | print("ERROR! Session/line number was not unique in", |
|
447 | 446 | "database. History logging moved to new session", |
|
448 | 447 | self.session_number) |
|
449 | 448 | try: # Try writing to the new session. If this fails, don't recurse |
|
450 | 449 | self._writeout_input_cache(conn) |
|
451 | 450 | except sqlite3.IntegrityError: |
|
452 | 451 | pass |
|
453 | 452 | finally: |
|
454 | 453 | self.db_input_cache = [] |
|
455 | 454 | |
|
456 | 455 | with self.db_output_cache_lock: |
|
457 | 456 | try: |
|
458 | 457 | self._writeout_output_cache(conn) |
|
459 | 458 | except sqlite3.IntegrityError: |
|
460 | 459 | print("!! Session/line number for output was not unique", |
|
461 | 460 | "in database. Output will not be stored.") |
|
462 | 461 | finally: |
|
463 | 462 | self.db_output_cache = [] |
|
464 | 463 | |
|
465 | 464 | |
|
466 | 465 | class HistorySavingThread(threading.Thread): |
|
467 | 466 | """This thread takes care of writing history to the database, so that |
|
468 | 467 | the UI isn't held up while that happens. |
|
469 | 468 | |
|
470 | 469 | It waits for the HistoryManager's save_flag to be set, then writes out |
|
471 | 470 | the history cache. The main thread is responsible for setting the flag when |
|
472 | 471 | the cache size reaches a defined threshold.""" |
|
473 | 472 | daemon = True |
|
474 | 473 | stop_now = False |
|
475 | 474 | def __init__(self, history_manager): |
|
476 | 475 | super(HistorySavingThread, self).__init__() |
|
477 | 476 | self.history_manager = history_manager |
|
478 | 477 | atexit.register(self.stop) |
|
479 | 478 | |
|
480 | 479 | def run(self): |
|
481 | 480 | # We need a separate db connection per thread: |
|
482 | 481 | try: |
|
483 | 482 | self.db = sqlite3.connect(self.history_manager.hist_file) |
|
484 | 483 | while True: |
|
485 | 484 | self.history_manager.save_flag.wait() |
|
486 | 485 | if self.stop_now: |
|
487 | 486 | return |
|
488 | 487 | self.history_manager.save_flag.clear() |
|
489 | 488 | self.history_manager.writeout_cache(self.db) |
|
490 | 489 | except Exception as e: |
|
491 | 490 | print(("The history saving thread hit an unexpected error (%s)." |
|
492 | 491 | "History will not be written to the database.") % repr(e)) |
|
493 | 492 | |
|
494 | 493 | def stop(self): |
|
495 | 494 | """This can be called from the main thread to safely stop this thread. |
|
496 | 495 | |
|
497 | 496 | Note that it does not attempt to write out remaining history before |
|
498 | 497 | exiting. That should be done by calling the HistoryManager's |
|
499 | 498 | end_session method.""" |
|
500 | 499 | self.stop_now = True |
|
501 | 500 | self.history_manager.save_flag.set() |
|
502 | 501 | self.join() |
|
503 | 502 | |
|
504 | 503 | |
|
505 | 504 | # To match, e.g. ~5/8-~2/3 |
|
506 | 505 | range_re = re.compile(r""" |
|
507 | 506 | ((?P<startsess>~?\d+)/)? |
|
508 | 507 | (?P<start>\d+) # Only the start line num is compulsory |
|
509 | 508 | ((?P<sep>[\-:]) |
|
510 | 509 | ((?P<endsess>~?\d+)/)? |
|
511 | 510 | (?P<end>\d+))? |
|
512 | 511 | $""", re.VERBOSE) |
|
513 | 512 | |
|
514 | 513 | def extract_hist_ranges(ranges_str): |
|
515 | 514 | """Turn a string of history ranges into 3-tuples of (session, start, stop). |
|
516 | 515 | |
|
517 | 516 | Examples |
|
518 | 517 | -------- |
|
519 | 518 | list(extract_input_ranges("~8/5-~7/4 2")) |
|
520 | 519 | [(-8, 5, None), (-7, 1, 4), (0, 2, 3)] |
|
521 | 520 | """ |
|
522 | 521 | for range_str in ranges_str.split(): |
|
523 | 522 | rmatch = range_re.match(range_str) |
|
524 | 523 | if not rmatch: |
|
525 | 524 | continue |
|
526 | 525 | start = int(rmatch.group("start")) |
|
527 | 526 | end = rmatch.group("end") |
|
528 | 527 | end = int(end) if end else start+1 # If no end specified, get (a, a+1) |
|
529 | 528 | if rmatch.group("sep") == "-": # 1-3 == 1:4 --> [1, 2, 3] |
|
530 | 529 | end += 1 |
|
531 | 530 | startsess = rmatch.group("startsess") or "0" |
|
532 | 531 | endsess = rmatch.group("endsess") or startsess |
|
533 | 532 | startsess = int(startsess.replace("~","-")) |
|
534 | 533 | endsess = int(endsess.replace("~","-")) |
|
535 | 534 | assert endsess >= startsess |
|
536 | 535 | |
|
537 | 536 | if endsess == startsess: |
|
538 | 537 | yield (startsess, start, end) |
|
539 | 538 | continue |
|
540 | 539 | # Multiple sessions in one range: |
|
541 | 540 | yield (startsess, start, None) |
|
542 | 541 | for sess in range(startsess+1, endsess): |
|
543 | 542 | yield (sess, 1, None) |
|
544 | 543 | yield (endsess, 1, end) |
|
545 | 544 | |
|
546 | 545 | def _format_lineno(session, line): |
|
547 | 546 | """Helper function to format line numbers properly.""" |
|
548 | 547 | if session == 0: |
|
549 | 548 | return str(line) |
|
550 | 549 | return "%s#%s" % (session, line) |
|
551 | 550 | |
|
552 | 551 | @testdec.skip_doctest |
|
553 | 552 | def magic_history(self, parameter_s = ''): |
|
554 | 553 | """Print input history (_i<n> variables), with most recent last. |
|
555 | 554 | |
|
556 | 555 | %history -> print at most 40 inputs (some may be multi-line)\\ |
|
557 | 556 | %history n -> print at most n inputs\\ |
|
558 | 557 | %history n1 n2 -> print inputs between n1 and n2 (n2 not included)\\ |
|
559 | 558 | |
|
560 | 559 | By default, input history is printed without line numbers so it can be |
|
561 | 560 | directly pasted into an editor. Use -n to show them. |
|
562 | 561 | |
|
563 | 562 | Ranges of history can be indicated using the syntax: |
|
564 | 563 | 4 : Line 4, current session |
|
565 | 564 | 4-6 : Lines 4-6, current session |
|
566 | 565 | 243/1-5: Lines 1-5, session 243 |
|
567 | 566 | ~2/7 : Line 7, session 2 before current |
|
568 | 567 | ~8/1-~6/5 : From the first line of 8 sessions ago, to the fifth line |
|
569 | 568 | of 6 sessions ago. |
|
570 | 569 | Multiple ranges can be entered, separated by spaces |
|
571 | 570 | |
|
572 | 571 | The same syntax is used by %macro, %save, %edit, %rerun |
|
573 | 572 | |
|
574 | 573 | Options: |
|
575 | 574 | |
|
576 | 575 | -n: print line numbers for each input. |
|
577 | 576 | This feature is only available if numbered prompts are in use. |
|
578 | 577 | |
|
579 | 578 | -o: also print outputs for each input. |
|
580 | 579 | |
|
581 | 580 | -p: print classic '>>>' python prompts before each input. This is useful |
|
582 | 581 | for making documentation, and in conjunction with -o, for producing |
|
583 | 582 | doctest-ready output. |
|
584 | 583 | |
|
585 | 584 | -r: (default) print the 'raw' history, i.e. the actual commands you typed. |
|
586 | 585 | |
|
587 | 586 | -t: print the 'translated' history, as IPython understands it. IPython |
|
588 | 587 | filters your input and converts it all into valid Python source before |
|
589 | 588 | executing it (things like magics or aliases are turned into function |
|
590 | 589 | calls, for example). With this option, you'll see the native history |
|
591 | 590 | instead of the user-entered version: '%cd /' will be seen as |
|
592 | 591 | 'get_ipython().magic("%cd /")' instead of '%cd /'. |
|
593 | 592 | |
|
594 | 593 | -g: treat the arg as a pattern to grep for in (full) history. |
|
595 | 594 | This includes the saved history (almost all commands ever written). |
|
596 | 595 | Use '%hist -g' to show full saved history (may be very long). |
|
597 | 596 | |
|
598 | 597 | -l: get the last n lines from all sessions. Specify n as a single arg, or |
|
599 | 598 | the default is the last 10 lines. |
|
600 | 599 | |
|
601 | 600 | -f FILENAME: instead of printing the output to the screen, redirect it to |
|
602 | 601 | the given file. The file is always overwritten, though IPython asks for |
|
603 | 602 | confirmation first if it already exists. |
|
604 | 603 | |
|
605 | 604 | Examples |
|
606 | 605 | -------- |
|
607 | 606 | :: |
|
608 | 607 | |
|
609 | 608 | In [6]: %hist -n 4 6 |
|
610 | 609 | 4:a = 12 |
|
611 | 610 | 5:print a**2 |
|
612 | 611 | |
|
613 | 612 | """ |
|
614 | 613 | |
|
615 | 614 | if not self.shell.displayhook.do_full_cache: |
|
616 | 615 | print('This feature is only available if numbered prompts are in use.') |
|
617 | 616 | return |
|
618 | 617 | opts,args = self.parse_options(parameter_s,'noprtglf:',mode='string') |
|
619 | 618 | |
|
620 | 619 | # For brevity |
|
621 | 620 | history_manager = self.shell.history_manager |
|
622 | 621 | |
|
623 | 622 | def _format_lineno(session, line): |
|
624 | 623 | """Helper function to format line numbers properly.""" |
|
625 | 624 | if session in (0, history_manager.session_number): |
|
626 | 625 | return str(line) |
|
627 | 626 | return "%s/%s" % (session, line) |
|
628 | 627 | |
|
629 | 628 | # Check if output to specific file was requested. |
|
630 | 629 | try: |
|
631 | 630 | outfname = opts['f'] |
|
632 | 631 | except KeyError: |
|
633 |
outfile = |
|
|
632 | outfile = io.stdout # default | |
|
634 | 633 | # We don't want to close stdout at the end! |
|
635 | 634 | close_at_end = False |
|
636 | 635 | else: |
|
637 | 636 | if os.path.exists(outfname): |
|
638 | if not ask_yes_no("File %r exists. Overwrite?" % outfname): | |
|
637 | if not io.ask_yes_no("File %r exists. Overwrite?" % outfname): | |
|
639 | 638 | print('Aborting.') |
|
640 | 639 | return |
|
641 | 640 | |
|
642 | 641 | outfile = open(outfname,'w') |
|
643 | 642 | close_at_end = True |
|
644 | 643 | |
|
645 | 644 | print_nums = 'n' in opts |
|
646 | 645 | get_output = 'o' in opts |
|
647 | 646 | pyprompts = 'p' in opts |
|
648 | 647 | # Raw history is the default |
|
649 | 648 | raw = not('t' in opts) |
|
650 | 649 | |
|
651 | 650 | default_length = 40 |
|
652 | 651 | pattern = None |
|
653 | 652 | |
|
654 | 653 | if 'g' in opts: # Glob search |
|
655 | 654 | pattern = "*" + args + "*" if args else "*" |
|
656 | 655 | hist = history_manager.search(pattern, raw=raw, output=get_output) |
|
657 | 656 | elif 'l' in opts: # Get 'tail' |
|
658 | 657 | try: |
|
659 | 658 | n = int(args) |
|
660 | 659 | except ValueError, IndexError: |
|
661 | 660 | n = 10 |
|
662 | 661 | hist = history_manager.get_tail(n, raw=raw, output=get_output) |
|
663 | 662 | else: |
|
664 | 663 | if args: # Get history by ranges |
|
665 | 664 | hist = history_manager.get_range_by_str(args, raw, get_output) |
|
666 | 665 | else: # Just get history for the current session |
|
667 | 666 | hist = history_manager.get_range(raw=raw, output=get_output) |
|
668 | 667 | |
|
669 | 668 | # We could be displaying the entire history, so let's not try to pull it |
|
670 | 669 | # into a list in memory. Anything that needs more space will just misalign. |
|
671 | 670 | width = 4 |
|
672 | 671 | |
|
673 | 672 | for session, lineno, inline in hist: |
|
674 | 673 | # Print user history with tabs expanded to 4 spaces. The GUI clients |
|
675 | 674 | # use hard tabs for easier usability in auto-indented code, but we want |
|
676 | 675 | # to produce PEP-8 compliant history for safe pasting into an editor. |
|
677 | 676 | if get_output: |
|
678 | 677 | inline, output = inline |
|
679 | 678 | inline = inline.expandtabs(4).rstrip() |
|
680 | 679 | |
|
681 | 680 | multiline = "\n" in inline |
|
682 | 681 | line_sep = '\n' if multiline else ' ' |
|
683 | 682 | if print_nums: |
|
684 | 683 | print('%s:%s' % (_format_lineno(session, lineno).rjust(width), |
|
685 | 684 | line_sep), file=outfile, end='') |
|
686 | 685 | if pyprompts: |
|
687 | 686 | print(">>> ", end="", file=outfile) |
|
688 | 687 | if multiline: |
|
689 | 688 | inline = "\n... ".join(inline.splitlines()) + "\n..." |
|
690 | 689 | print(inline, file=outfile) |
|
691 | 690 | if get_output and output: |
|
692 | 691 | print(output, file=outfile) |
|
693 | 692 | |
|
694 | 693 | if close_at_end: |
|
695 | 694 | outfile.close() |
|
696 | 695 | |
|
697 | 696 | |
|
698 | 697 | def magic_rep(self, arg): |
|
699 | 698 | r""" Repeat a command, or get command to input line for editing |
|
700 | 699 | |
|
701 | 700 | - %rep (no arguments): |
|
702 | 701 | |
|
703 | 702 | Place a string version of last computation result (stored in the special '_' |
|
704 | 703 | variable) to the next input prompt. Allows you to create elaborate command |
|
705 | 704 | lines without using copy-paste:: |
|
706 | 705 | |
|
707 | 706 | In[1]: l = ["hei", "vaan"] |
|
708 | 707 | In[2]: "".join(l) |
|
709 | 708 | Out[2]: heivaan |
|
710 | 709 | In[3]: %rep |
|
711 | 710 | In[4]: heivaan_ <== cursor blinking |
|
712 | 711 | |
|
713 | 712 | %rep 45 |
|
714 | 713 | |
|
715 | 714 | Place history line 45 on the next input prompt. Use %hist to find |
|
716 | 715 | out the number. |
|
717 | 716 | |
|
718 | 717 | %rep 1-4 |
|
719 | 718 | |
|
720 | 719 | Combine the specified lines into one cell, and place it on the next |
|
721 | 720 | input prompt. See %history for the slice syntax. |
|
722 | 721 | |
|
723 | 722 | %rep foo+bar |
|
724 | 723 | |
|
725 | 724 | If foo+bar can be evaluated in the user namespace, the result is |
|
726 | 725 | placed at the next input prompt. Otherwise, the history is searched |
|
727 | 726 | for lines which contain that substring, and the most recent one is |
|
728 | 727 | placed at the next input prompt. |
|
729 | 728 | """ |
|
730 | 729 | if not arg: # Last output |
|
731 | 730 | self.set_next_input(str(self.shell.user_ns["_"])) |
|
732 | 731 | return |
|
733 | 732 | # Get history range |
|
734 | 733 | histlines = self.history_manager.get_range_by_str(arg) |
|
735 | 734 | cmd = "\n".join(x[2] for x in histlines) |
|
736 | 735 | if cmd: |
|
737 | 736 | self.set_next_input(cmd.rstrip()) |
|
738 | 737 | return |
|
739 | 738 | |
|
740 | 739 | try: # Variable in user namespace |
|
741 | 740 | cmd = str(eval(arg, self.shell.user_ns)) |
|
742 | 741 | except Exception: # Search for term in history |
|
743 | 742 | histlines = self.history_manager.search("*"+arg+"*") |
|
744 | 743 | for h in reversed([x[2] for x in histlines]): |
|
745 | 744 | if 'rep' in h: |
|
746 | 745 | continue |
|
747 | 746 | self.set_next_input(h.rstrip()) |
|
748 | 747 | return |
|
749 | 748 | else: |
|
750 | 749 | self.set_next_input(cmd.rstrip()) |
|
751 | 750 | print("Couldn't evaluate or find in history:", arg) |
|
752 | 751 | |
|
753 | 752 | def magic_rerun(self, parameter_s=''): |
|
754 | 753 | """Re-run previous input |
|
755 | 754 | |
|
756 | 755 | By default, you can specify ranges of input history to be repeated |
|
757 | 756 | (as with %history). With no arguments, it will repeat the last line. |
|
758 | 757 | |
|
759 | 758 | Options: |
|
760 | 759 | |
|
761 | 760 | -l <n> : Repeat the last n lines of input, not including the |
|
762 | 761 | current command. |
|
763 | 762 | |
|
764 | 763 | -g foo : Repeat the most recent line which contains foo |
|
765 | 764 | """ |
|
766 | 765 | opts, args = self.parse_options(parameter_s, 'l:g:', mode='string') |
|
767 | 766 | if "l" in opts: # Last n lines |
|
768 | 767 | n = int(opts['l']) |
|
769 | 768 | hist = self.history_manager.get_tail(n) |
|
770 | 769 | elif "g" in opts: # Search |
|
771 | 770 | p = "*"+opts['g']+"*" |
|
772 | 771 | hist = list(self.history_manager.search(p)) |
|
773 | 772 | for l in reversed(hist): |
|
774 | 773 | if "rerun" not in l[2]: |
|
775 | 774 | hist = [l] # The last match which isn't a %rerun |
|
776 | 775 | break |
|
777 | 776 | else: |
|
778 | 777 | hist = [] # No matches except %rerun |
|
779 | 778 | elif args: # Specify history ranges |
|
780 | 779 | hist = self.history_manager.get_range_by_str(args) |
|
781 | 780 | else: # Last line |
|
782 | 781 | hist = self.history_manager.get_tail(1) |
|
783 | 782 | hist = [x[2] for x in hist] |
|
784 | 783 | if not hist: |
|
785 | 784 | print("No lines in history match specification") |
|
786 | 785 | return |
|
787 | 786 | histlines = "\n".join(hist) |
|
788 | 787 | print("=== Executing: ===") |
|
789 | 788 | print(histlines) |
|
790 | 789 | print("=== Output: ===") |
|
791 | 790 | self.run_cell("\n".join(hist), store_history=False) |
|
792 | 791 | |
|
793 | 792 | |
|
794 | 793 | def init_ipython(ip): |
|
795 | 794 | ip.define_magic("rep", magic_rep) |
|
796 | 795 | ip.define_magic("recall", magic_rep) |
|
797 | 796 | ip.define_magic("rerun", magic_rerun) |
|
798 | 797 | ip.define_magic("hist",magic_history) # Alternative name |
|
799 | 798 | ip.define_magic("history",magic_history) |
|
800 | 799 | |
|
801 | 800 | # XXX - ipy_completers are in quarantine, need to be updated to new apis |
|
802 | 801 | #import ipy_completers |
|
803 | 802 | #ipy_completers.quick_completer('%hist' ,'-g -t -r -n') |
@@ -1,236 +1,235 b'' | |||
|
1 | 1 | """hooks for IPython. |
|
2 | 2 | |
|
3 | 3 | In Python, it is possible to overwrite any method of any object if you really |
|
4 | 4 | want to. But IPython exposes a few 'hooks', methods which are _designed_ to |
|
5 | 5 | be overwritten by users for customization purposes. This module defines the |
|
6 | 6 | default versions of all such hooks, which get used by IPython if not |
|
7 | 7 | overridden by the user. |
|
8 | 8 | |
|
9 | 9 | hooks are simple functions, but they should be declared with 'self' as their |
|
10 | 10 | first argument, because when activated they are registered into IPython as |
|
11 | 11 | instance methods. The self argument will be the IPython running instance |
|
12 | 12 | itself, so hooks have full access to the entire IPython object. |
|
13 | 13 | |
|
14 | 14 | If you wish to define a new hook and activate it, you need to put the |
|
15 | 15 | necessary code into a python file which can be either imported or execfile()'d |
|
16 | 16 | from within your ipythonrc configuration. |
|
17 | 17 | |
|
18 | 18 | For example, suppose that you have a module called 'myiphooks' in your |
|
19 | 19 | PYTHONPATH, which contains the following definition: |
|
20 | 20 | |
|
21 | 21 | import os |
|
22 | 22 | from IPython.core import ipapi |
|
23 | 23 | ip = ipapi.get() |
|
24 | 24 | |
|
25 | 25 | def calljed(self,filename, linenum): |
|
26 | 26 | "My editor hook calls the jed editor directly." |
|
27 | 27 | print "Calling my own editor, jed ..." |
|
28 | 28 | if os.system('jed +%d %s' % (linenum,filename)) != 0: |
|
29 | 29 | raise TryNext() |
|
30 | 30 | |
|
31 | 31 | ip.set_hook('editor', calljed) |
|
32 | 32 | |
|
33 | 33 | You can then enable the functionality by doing 'import myiphooks' |
|
34 | 34 | somewhere in your configuration files or ipython command line. |
|
35 | 35 | """ |
|
36 | 36 | |
|
37 | 37 | #***************************************************************************** |
|
38 | 38 | # Copyright (C) 2005 Fernando Perez. <fperez@colorado.edu> |
|
39 | 39 | # |
|
40 | 40 | # Distributed under the terms of the BSD License. The full license is in |
|
41 | 41 | # the file COPYING, distributed as part of this software. |
|
42 | 42 | #***************************************************************************** |
|
43 | 43 | |
|
44 | 44 | import os, bisect |
|
45 | 45 | import sys |
|
46 | 46 | |
|
47 | 47 | from IPython.core.error import TryNext |
|
48 | import IPython.utils.io | |
|
49 | 48 | |
|
50 | 49 | # List here all the default hooks. For now it's just the editor functions |
|
51 | 50 | # but over time we'll move here all the public API for user-accessible things. |
|
52 | 51 | |
|
53 | 52 | __all__ = ['editor', 'fix_error_editor', 'synchronize_with_editor', |
|
54 | 53 | 'input_prefilter', 'shutdown_hook', 'late_startup_hook', |
|
55 | 54 | 'generate_prompt', 'show_in_pager','pre_prompt_hook', |
|
56 | 55 | 'pre_run_code_hook', 'clipboard_get'] |
|
57 | 56 | |
|
58 | 57 | def editor(self,filename, linenum=None): |
|
59 | 58 | """Open the default editor at the given filename and linenumber. |
|
60 | 59 | |
|
61 | 60 | This is IPython's default editor hook, you can use it as an example to |
|
62 | 61 | write your own modified one. To set your own editor function as the |
|
63 | 62 | new editor hook, call ip.set_hook('editor',yourfunc).""" |
|
64 | 63 | |
|
65 | 64 | # IPython configures a default editor at startup by reading $EDITOR from |
|
66 | 65 | # the environment, and falling back on vi (unix) or notepad (win32). |
|
67 | 66 | editor = self.editor |
|
68 | 67 | |
|
69 | 68 | # marker for at which line to open the file (for existing objects) |
|
70 | 69 | if linenum is None or editor=='notepad': |
|
71 | 70 | linemark = '' |
|
72 | 71 | else: |
|
73 | 72 | linemark = '+%d' % int(linenum) |
|
74 | 73 | |
|
75 | 74 | # Enclose in quotes if necessary and legal |
|
76 | 75 | if ' ' in editor and os.path.isfile(editor) and editor[0] != '"': |
|
77 | 76 | editor = '"%s"' % editor |
|
78 | 77 | |
|
79 | 78 | # Call the actual editor |
|
80 | 79 | if os.system('%s %s %s' % (editor,linemark,filename)) != 0: |
|
81 | 80 | raise TryNext() |
|
82 | 81 | |
|
83 | 82 | import tempfile |
|
84 | 83 | def fix_error_editor(self,filename,linenum,column,msg): |
|
85 | 84 | """Open the editor at the given filename, linenumber, column and |
|
86 | 85 | show an error message. This is used for correcting syntax errors. |
|
87 | 86 | The current implementation only has special support for the VIM editor, |
|
88 | 87 | and falls back on the 'editor' hook if VIM is not used. |
|
89 | 88 | |
|
90 | 89 | Call ip.set_hook('fix_error_editor',youfunc) to use your own function, |
|
91 | 90 | """ |
|
92 | 91 | def vim_quickfix_file(): |
|
93 | 92 | t = tempfile.NamedTemporaryFile() |
|
94 | 93 | t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg)) |
|
95 | 94 | t.flush() |
|
96 | 95 | return t |
|
97 | 96 | if os.path.basename(self.editor) != 'vim': |
|
98 | 97 | self.hooks.editor(filename,linenum) |
|
99 | 98 | return |
|
100 | 99 | t = vim_quickfix_file() |
|
101 | 100 | try: |
|
102 | 101 | if os.system('vim --cmd "set errorformat=%f:%l:%c:%m" -q ' + t.name): |
|
103 | 102 | raise TryNext() |
|
104 | 103 | finally: |
|
105 | 104 | t.close() |
|
106 | 105 | |
|
107 | 106 | |
|
108 | 107 | def synchronize_with_editor(self, filename, linenum, column): |
|
109 | 108 | pass |
|
110 | 109 | |
|
111 | 110 | |
|
112 | 111 | class CommandChainDispatcher: |
|
113 | 112 | """ Dispatch calls to a chain of commands until some func can handle it |
|
114 | 113 | |
|
115 | 114 | Usage: instantiate, execute "add" to add commands (with optional |
|
116 | 115 | priority), execute normally via f() calling mechanism. |
|
117 | 116 | |
|
118 | 117 | """ |
|
119 | 118 | def __init__(self,commands=None): |
|
120 | 119 | if commands is None: |
|
121 | 120 | self.chain = [] |
|
122 | 121 | else: |
|
123 | 122 | self.chain = commands |
|
124 | 123 | |
|
125 | 124 | |
|
126 | 125 | def __call__(self,*args, **kw): |
|
127 | 126 | """ Command chain is called just like normal func. |
|
128 | 127 | |
|
129 | 128 | This will call all funcs in chain with the same args as were given to this |
|
130 | 129 | function, and return the result of first func that didn't raise |
|
131 | 130 | TryNext """ |
|
132 | 131 | |
|
133 | 132 | for prio,cmd in self.chain: |
|
134 | 133 | #print "prio",prio,"cmd",cmd #dbg |
|
135 | 134 | try: |
|
136 | 135 | return cmd(*args, **kw) |
|
137 | 136 | except TryNext, exc: |
|
138 | 137 | if exc.args or exc.kwargs: |
|
139 | 138 | args = exc.args |
|
140 | 139 | kw = exc.kwargs |
|
141 | 140 | # if no function will accept it, raise TryNext up to the caller |
|
142 | 141 | raise TryNext |
|
143 | 142 | |
|
144 | 143 | def __str__(self): |
|
145 | 144 | return str(self.chain) |
|
146 | 145 | |
|
147 | 146 | def add(self, func, priority=0): |
|
148 | 147 | """ Add a func to the cmd chain with given priority """ |
|
149 | 148 | bisect.insort(self.chain,(priority,func)) |
|
150 | 149 | |
|
151 | 150 | def __iter__(self): |
|
152 | 151 | """ Return all objects in chain. |
|
153 | 152 | |
|
154 | 153 | Handy if the objects are not callable. |
|
155 | 154 | """ |
|
156 | 155 | return iter(self.chain) |
|
157 | 156 | |
|
158 | 157 | |
|
159 | 158 | def input_prefilter(self,line): |
|
160 | 159 | """ Default input prefilter |
|
161 | 160 | |
|
162 | 161 | This returns the line as unchanged, so that the interpreter |
|
163 | 162 | knows that nothing was done and proceeds with "classic" prefiltering |
|
164 | 163 | (%magics, !shell commands etc.). |
|
165 | 164 | |
|
166 | 165 | Note that leading whitespace is not passed to this hook. Prefilter |
|
167 | 166 | can't alter indentation. |
|
168 | 167 | |
|
169 | 168 | """ |
|
170 | 169 | #print "attempt to rewrite",line #dbg |
|
171 | 170 | return line |
|
172 | 171 | |
|
173 | 172 | |
|
174 | 173 | def shutdown_hook(self): |
|
175 | 174 | """ default shutdown hook |
|
176 | 175 | |
|
177 | 176 | Typically, shotdown hooks should raise TryNext so all shutdown ops are done |
|
178 | 177 | """ |
|
179 | 178 | |
|
180 | 179 | #print "default shutdown hook ok" # dbg |
|
181 | 180 | return |
|
182 | 181 | |
|
183 | 182 | |
|
184 | 183 | def late_startup_hook(self): |
|
185 | 184 | """ Executed after ipython has been constructed and configured |
|
186 | 185 | |
|
187 | 186 | """ |
|
188 | 187 | #print "default startup hook ok" # dbg |
|
189 | 188 | |
|
190 | 189 | |
|
191 | 190 | def generate_prompt(self, is_continuation): |
|
192 | 191 | """ calculate and return a string with the prompt to display """ |
|
193 | 192 | if is_continuation: |
|
194 | 193 | return str(self.displayhook.prompt2) |
|
195 | 194 | return str(self.displayhook.prompt1) |
|
196 | 195 | |
|
197 | 196 | |
|
198 | 197 | def show_in_pager(self,s): |
|
199 | 198 | """ Run a string through pager """ |
|
200 | 199 | # raising TryNext here will use the default paging functionality |
|
201 | 200 | raise TryNext |
|
202 | 201 | |
|
203 | 202 | |
|
204 | 203 | def pre_prompt_hook(self): |
|
205 | 204 | """ Run before displaying the next prompt |
|
206 | 205 | |
|
207 | 206 | Use this e.g. to display output from asynchronous operations (in order |
|
208 | 207 | to not mess up text entry) |
|
209 | 208 | """ |
|
210 | 209 | |
|
211 | 210 | return None |
|
212 | 211 | |
|
213 | 212 | |
|
214 | 213 | def pre_run_code_hook(self): |
|
215 | 214 | """ Executed before running the (prefiltered) code in IPython """ |
|
216 | 215 | return None |
|
217 | 216 | |
|
218 | 217 | |
|
219 | 218 | def clipboard_get(self): |
|
220 | 219 | """ Get text from the clipboard. |
|
221 | 220 | """ |
|
222 | 221 | from IPython.lib.clipboard import ( |
|
223 | 222 | osx_clipboard_get, tkinter_clipboard_get, |
|
224 | 223 | win32_clipboard_get |
|
225 | 224 | ) |
|
226 | 225 | if sys.platform == 'win32': |
|
227 | 226 | chain = [win32_clipboard_get, tkinter_clipboard_get] |
|
228 | 227 | elif sys.platform == 'darwin': |
|
229 | 228 | chain = [osx_clipboard_get, tkinter_clipboard_get] |
|
230 | 229 | else: |
|
231 | 230 | chain = [tkinter_clipboard_get] |
|
232 | 231 | dispatcher = CommandChainDispatcher() |
|
233 | 232 | for func in chain: |
|
234 | 233 | dispatcher.add(func) |
|
235 | 234 | text = dispatcher() |
|
236 | 235 | return text |
@@ -1,2424 +1,2423 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 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | from __future__ import with_statement |
|
18 | 18 | from __future__ import absolute_import |
|
19 | 19 | |
|
20 | 20 | import __builtin__ |
|
21 | 21 | import __future__ |
|
22 | 22 | import abc |
|
23 | 23 | import ast |
|
24 | 24 | import atexit |
|
25 | 25 | import codeop |
|
26 | 26 | import inspect |
|
27 | 27 | import os |
|
28 | 28 | import re |
|
29 | 29 | import sys |
|
30 | 30 | import tempfile |
|
31 | 31 | import types |
|
32 | 32 | from contextlib import nested |
|
33 | 33 | |
|
34 | 34 | from IPython.config.configurable import Configurable |
|
35 | 35 | from IPython.core import debugger, oinspect |
|
36 | 36 | from IPython.core import history as ipcorehist |
|
37 | 37 | from IPython.core import page |
|
38 | 38 | from IPython.core import prefilter |
|
39 | 39 | from IPython.core import shadowns |
|
40 | 40 | from IPython.core import ultratb |
|
41 | 41 | from IPython.core.alias import AliasManager |
|
42 | 42 | from IPython.core.autocall import ExitAutocall |
|
43 | 43 | from IPython.core.builtin_trap import BuiltinTrap |
|
44 | 44 | from IPython.core.compilerop import CachingCompiler |
|
45 | 45 | from IPython.core.display_trap import DisplayTrap |
|
46 | 46 | from IPython.core.displayhook import DisplayHook |
|
47 | 47 | from IPython.core.displaypub import DisplayPublisher |
|
48 | 48 | from IPython.core.error import TryNext, UsageError |
|
49 | 49 | from IPython.core.extensions import ExtensionManager |
|
50 | 50 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
51 | 51 | from IPython.core.formatters import DisplayFormatter |
|
52 | 52 | from IPython.core.history import HistoryManager |
|
53 | 53 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
54 | 54 | from IPython.core.logger import Logger |
|
55 | 55 | from IPython.core.macro import Macro |
|
56 | 56 | from IPython.core.magic import Magic |
|
57 | 57 | from IPython.core.payload import PayloadManager |
|
58 | 58 | from IPython.core.plugin import PluginManager |
|
59 | 59 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
60 | 60 | from IPython.external.Itpl import ItplNS |
|
61 | 61 | from IPython.utils import PyColorize |
|
62 | 62 | from IPython.utils import io |
|
63 | 63 | from IPython.utils.doctestreload import doctest_reload |
|
64 | 64 | from IPython.utils.io import ask_yes_no, rprint |
|
65 | 65 | from IPython.utils.ipstruct import Struct |
|
66 | 66 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
67 | 67 | from IPython.utils.pickleshare import PickleShareDB |
|
68 | 68 | from IPython.utils.process import system, getoutput |
|
69 | 69 | from IPython.utils.strdispatch import StrDispatch |
|
70 | 70 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
71 | 71 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList |
|
72 | 72 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
73 | 73 | List, Unicode, Instance, Type) |
|
74 | 74 | from IPython.utils.warn import warn, error, fatal |
|
75 | 75 | import IPython.core.hooks |
|
76 | 76 | |
|
77 | 77 | #----------------------------------------------------------------------------- |
|
78 | 78 | # Globals |
|
79 | 79 | #----------------------------------------------------------------------------- |
|
80 | 80 | |
|
81 | 81 | # compiled regexps for autoindent management |
|
82 | 82 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
83 | 83 | |
|
84 | 84 | #----------------------------------------------------------------------------- |
|
85 | 85 | # Utilities |
|
86 | 86 | #----------------------------------------------------------------------------- |
|
87 | 87 | |
|
88 | 88 | # store the builtin raw_input globally, and use this always, in case user code |
|
89 | 89 | # overwrites it (like wx.py.PyShell does) |
|
90 | 90 | raw_input_original = raw_input |
|
91 | 91 | |
|
92 | 92 | def softspace(file, newvalue): |
|
93 | 93 | """Copied from code.py, to remove the dependency""" |
|
94 | 94 | |
|
95 | 95 | oldvalue = 0 |
|
96 | 96 | try: |
|
97 | 97 | oldvalue = file.softspace |
|
98 | 98 | except AttributeError: |
|
99 | 99 | pass |
|
100 | 100 | try: |
|
101 | 101 | file.softspace = newvalue |
|
102 | 102 | except (AttributeError, TypeError): |
|
103 | 103 | # "attribute-less object" or "read-only attributes" |
|
104 | 104 | pass |
|
105 | 105 | return oldvalue |
|
106 | 106 | |
|
107 | 107 | |
|
108 | 108 | def no_op(*a, **kw): pass |
|
109 | 109 | |
|
110 | 110 | class SpaceInInput(Exception): pass |
|
111 | 111 | |
|
112 | 112 | class Bunch: pass |
|
113 | 113 | |
|
114 | 114 | |
|
115 | 115 | def get_default_colors(): |
|
116 | 116 | if sys.platform=='darwin': |
|
117 | 117 | return "LightBG" |
|
118 | 118 | elif os.name=='nt': |
|
119 | 119 | return 'Linux' |
|
120 | 120 | else: |
|
121 | 121 | return 'Linux' |
|
122 | 122 | |
|
123 | 123 | |
|
124 | 124 | class SeparateStr(Str): |
|
125 | 125 | """A Str subclass to validate separate_in, separate_out, etc. |
|
126 | 126 | |
|
127 | 127 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
128 | 128 | """ |
|
129 | 129 | |
|
130 | 130 | def validate(self, obj, value): |
|
131 | 131 | if value == '0': value = '' |
|
132 | 132 | value = value.replace('\\n','\n') |
|
133 | 133 | return super(SeparateStr, self).validate(obj, value) |
|
134 | 134 | |
|
135 | 135 | class MultipleInstanceError(Exception): |
|
136 | 136 | pass |
|
137 | 137 | |
|
138 | 138 | class ReadlineNoRecord(object): |
|
139 | 139 | """Context manager to execute some code, then reload readline history |
|
140 | 140 | so that interactive input to the code doesn't appear when pressing up.""" |
|
141 | 141 | def __init__(self, shell): |
|
142 | 142 | self.shell = shell |
|
143 | 143 | self._nested_level = 0 |
|
144 | 144 | |
|
145 | 145 | def __enter__(self): |
|
146 | 146 | if self._nested_level == 0: |
|
147 | 147 | try: |
|
148 | 148 | self.orig_length = self.current_length() |
|
149 | 149 | self.readline_tail = self.get_readline_tail() |
|
150 | 150 | except (AttributeError, IndexError): # Can fail with pyreadline |
|
151 | 151 | self.orig_length, self.readline_tail = 999999, [] |
|
152 | 152 | self._nested_level += 1 |
|
153 | 153 | |
|
154 | 154 | def __exit__(self, type, value, traceback): |
|
155 | 155 | self._nested_level -= 1 |
|
156 | 156 | if self._nested_level == 0: |
|
157 | 157 | # Try clipping the end if it's got longer |
|
158 | 158 | try: |
|
159 | 159 | e = self.current_length() - self.orig_length |
|
160 | 160 | if e > 0: |
|
161 | 161 | for _ in range(e): |
|
162 | 162 | self.shell.readline.remove_history_item(self.orig_length) |
|
163 | 163 | |
|
164 | 164 | # If it still doesn't match, just reload readline history. |
|
165 | 165 | if self.current_length() != self.orig_length \ |
|
166 | 166 | or self.get_readline_tail() != self.readline_tail: |
|
167 | 167 | self.shell.refill_readline_hist() |
|
168 | 168 | except (AttributeError, IndexError): |
|
169 | 169 | pass |
|
170 | 170 | # Returning False will cause exceptions to propagate |
|
171 | 171 | return False |
|
172 | 172 | |
|
173 | 173 | def current_length(self): |
|
174 | 174 | return self.shell.readline.get_current_history_length() |
|
175 | 175 | |
|
176 | 176 | def get_readline_tail(self, n=10): |
|
177 | 177 | """Get the last n items in readline history.""" |
|
178 | 178 | end = self.shell.readline.get_current_history_length() + 1 |
|
179 | 179 | start = max(end-n, 1) |
|
180 | 180 | ghi = self.shell.readline.get_history_item |
|
181 | 181 | return [ghi(x) for x in range(start, end)] |
|
182 | 182 | |
|
183 | 183 | |
|
184 | 184 | #----------------------------------------------------------------------------- |
|
185 | 185 | # Main IPython class |
|
186 | 186 | #----------------------------------------------------------------------------- |
|
187 | 187 | |
|
188 | 188 | class InteractiveShell(Configurable, Magic): |
|
189 | 189 | """An enhanced, interactive shell for Python.""" |
|
190 | 190 | |
|
191 | 191 | _instance = None |
|
192 | 192 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
193 | 193 | # TODO: remove all autoindent logic and put into frontends. |
|
194 | 194 | # We can't do this yet because even runlines uses the autoindent. |
|
195 | 195 | autoindent = CBool(True, config=True) |
|
196 | 196 | automagic = CBool(True, config=True) |
|
197 | 197 | cache_size = Int(1000, config=True) |
|
198 | 198 | color_info = CBool(True, config=True) |
|
199 | 199 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
200 | 200 | default_value=get_default_colors(), config=True) |
|
201 | 201 | debug = CBool(False, config=True) |
|
202 | 202 | deep_reload = CBool(False, config=True) |
|
203 | 203 | display_formatter = Instance(DisplayFormatter) |
|
204 | 204 | displayhook_class = Type(DisplayHook) |
|
205 | 205 | display_pub_class = Type(DisplayPublisher) |
|
206 | 206 | |
|
207 | 207 | exit_now = CBool(False) |
|
208 | 208 | exiter = Instance(ExitAutocall) |
|
209 | 209 | def _exiter_default(self): |
|
210 | 210 | return ExitAutocall(self) |
|
211 | 211 | # Monotonically increasing execution counter |
|
212 | 212 | execution_count = Int(1) |
|
213 | 213 | filename = Unicode("<ipython console>") |
|
214 | 214 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
215 | 215 | |
|
216 | 216 | # Input splitter, to split entire cells of input into either individual |
|
217 | 217 | # interactive statements or whole blocks. |
|
218 | 218 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter', |
|
219 | 219 | (), {}) |
|
220 | 220 | logstart = CBool(False, config=True) |
|
221 | 221 | logfile = Unicode('', config=True) |
|
222 | 222 | logappend = Unicode('', config=True) |
|
223 | 223 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
224 | 224 | config=True) |
|
225 | 225 | pdb = CBool(False, config=True) |
|
226 | 226 | |
|
227 | 227 | profile = Unicode('', config=True) |
|
228 | 228 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
229 | 229 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
230 | 230 | prompt_out = Str('Out[\\#]: ', config=True) |
|
231 | 231 | prompts_pad_left = CBool(True, config=True) |
|
232 | 232 | quiet = CBool(False, config=True) |
|
233 | 233 | |
|
234 | 234 | history_length = Int(10000, config=True) |
|
235 | 235 | |
|
236 | 236 | # The readline stuff will eventually be moved to the terminal subclass |
|
237 | 237 | # but for now, we can't do that as readline is welded in everywhere. |
|
238 | 238 | readline_use = CBool(True, config=True) |
|
239 | 239 | readline_merge_completions = CBool(True, config=True) |
|
240 | 240 | readline_omit__names = Enum((0,1,2), default_value=2, config=True) |
|
241 | 241 | readline_remove_delims = Str('-/~', config=True) |
|
242 | 242 | readline_parse_and_bind = List([ |
|
243 | 243 | 'tab: complete', |
|
244 | 244 | '"\C-l": clear-screen', |
|
245 | 245 | 'set show-all-if-ambiguous on', |
|
246 | 246 | '"\C-o": tab-insert', |
|
247 | 247 | # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff |
|
248 | 248 | # crash IPython. |
|
249 | 249 | '"\M-o": "\d\d\d\d"', |
|
250 | 250 | '"\M-I": "\d\d\d\d"', |
|
251 | 251 | '"\C-r": reverse-search-history', |
|
252 | 252 | '"\C-s": forward-search-history', |
|
253 | 253 | '"\C-p": history-search-backward', |
|
254 | 254 | '"\C-n": history-search-forward', |
|
255 | 255 | '"\e[A": history-search-backward', |
|
256 | 256 | '"\e[B": history-search-forward', |
|
257 | 257 | '"\C-k": kill-line', |
|
258 | 258 | '"\C-u": unix-line-discard', |
|
259 | 259 | ], allow_none=False, config=True) |
|
260 | 260 | |
|
261 | 261 | # TODO: this part of prompt management should be moved to the frontends. |
|
262 | 262 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
263 | 263 | separate_in = SeparateStr('\n', config=True) |
|
264 | 264 | separate_out = SeparateStr('', config=True) |
|
265 | 265 | separate_out2 = SeparateStr('', config=True) |
|
266 | 266 | wildcards_case_sensitive = CBool(True, config=True) |
|
267 | 267 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
268 | 268 | default_value='Context', config=True) |
|
269 | 269 | |
|
270 | 270 | # Subcomponents of InteractiveShell |
|
271 | 271 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
272 | 272 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
273 | 273 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
274 | 274 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
275 | 275 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
276 | 276 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
277 | 277 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
278 | 278 | history_manager = Instance('IPython.core.history.HistoryManager') |
|
279 | 279 | |
|
280 | 280 | # Private interface |
|
281 | 281 | _post_execute = Instance(dict) |
|
282 | 282 | |
|
283 | 283 | def __init__(self, config=None, ipython_dir=None, |
|
284 | 284 | user_ns=None, user_global_ns=None, |
|
285 | 285 | custom_exceptions=((), None)): |
|
286 | 286 | |
|
287 | 287 | # This is where traits with a config_key argument are updated |
|
288 | 288 | # from the values on config. |
|
289 | 289 | super(InteractiveShell, self).__init__(config=config) |
|
290 | 290 | |
|
291 | 291 | # These are relatively independent and stateless |
|
292 | 292 | self.init_ipython_dir(ipython_dir) |
|
293 | 293 | self.init_instance_attrs() |
|
294 | 294 | self.init_environment() |
|
295 | 295 | |
|
296 | 296 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
297 | 297 | self.init_create_namespaces(user_ns, user_global_ns) |
|
298 | 298 | # This has to be done after init_create_namespaces because it uses |
|
299 | 299 | # something in self.user_ns, but before init_sys_modules, which |
|
300 | 300 | # is the first thing to modify sys. |
|
301 | 301 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
302 | 302 | # is created, we are saving the overridden ones here. Not sure if this |
|
303 | 303 | # is what we want to do. |
|
304 | 304 | self.save_sys_module_state() |
|
305 | 305 | self.init_sys_modules() |
|
306 | 306 | |
|
307 | 307 | # While we're trying to have each part of the code directly access what |
|
308 | 308 | # it needs without keeping redundant references to objects, we have too |
|
309 | 309 | # much legacy code that expects ip.db to exist. |
|
310 | 310 | self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db')) |
|
311 | 311 | |
|
312 | 312 | self.init_history() |
|
313 | 313 | self.init_encoding() |
|
314 | 314 | self.init_prefilter() |
|
315 | 315 | |
|
316 | 316 | Magic.__init__(self, self) |
|
317 | 317 | |
|
318 | 318 | self.init_syntax_highlighting() |
|
319 | 319 | self.init_hooks() |
|
320 | 320 | self.init_pushd_popd_magic() |
|
321 | 321 | # self.init_traceback_handlers use to be here, but we moved it below |
|
322 | 322 | # because it and init_io have to come after init_readline. |
|
323 | 323 | self.init_user_ns() |
|
324 | 324 | self.init_logger() |
|
325 | 325 | self.init_alias() |
|
326 | 326 | self.init_builtins() |
|
327 | 327 | |
|
328 | 328 | # pre_config_initialization |
|
329 | 329 | |
|
330 | 330 | # The next section should contain everything that was in ipmaker. |
|
331 | 331 | self.init_logstart() |
|
332 | 332 | |
|
333 | 333 | # The following was in post_config_initialization |
|
334 | 334 | self.init_inspector() |
|
335 | 335 | # init_readline() must come before init_io(), because init_io uses |
|
336 | 336 | # readline related things. |
|
337 | 337 | self.init_readline() |
|
338 | 338 | # init_completer must come after init_readline, because it needs to |
|
339 | 339 | # know whether readline is present or not system-wide to configure the |
|
340 | 340 | # completers, since the completion machinery can now operate |
|
341 | 341 | # independently of readline (e.g. over the network) |
|
342 | 342 | self.init_completer() |
|
343 | 343 | # TODO: init_io() needs to happen before init_traceback handlers |
|
344 | 344 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
345 | 345 | # This logic in in debugger.Pdb and should eventually be changed. |
|
346 | 346 | self.init_io() |
|
347 | 347 | self.init_traceback_handlers(custom_exceptions) |
|
348 | 348 | self.init_prompts() |
|
349 | 349 | self.init_display_formatter() |
|
350 | 350 | self.init_display_pub() |
|
351 | 351 | self.init_displayhook() |
|
352 | 352 | self.init_reload_doctest() |
|
353 | 353 | self.init_magics() |
|
354 | 354 | self.init_pdb() |
|
355 | 355 | self.init_extension_manager() |
|
356 | 356 | self.init_plugin_manager() |
|
357 | 357 | self.init_payload() |
|
358 | 358 | self.hooks.late_startup_hook() |
|
359 | 359 | atexit.register(self.atexit_operations) |
|
360 | 360 | |
|
361 | 361 | @classmethod |
|
362 | 362 | def instance(cls, *args, **kwargs): |
|
363 | 363 | """Returns a global InteractiveShell instance.""" |
|
364 | 364 | if cls._instance is None: |
|
365 | 365 | inst = cls(*args, **kwargs) |
|
366 | 366 | # Now make sure that the instance will also be returned by |
|
367 | 367 | # the subclasses instance attribute. |
|
368 | 368 | for subclass in cls.mro(): |
|
369 | 369 | if issubclass(cls, subclass) and \ |
|
370 | 370 | issubclass(subclass, InteractiveShell): |
|
371 | 371 | subclass._instance = inst |
|
372 | 372 | else: |
|
373 | 373 | break |
|
374 | 374 | if isinstance(cls._instance, cls): |
|
375 | 375 | return cls._instance |
|
376 | 376 | else: |
|
377 | 377 | raise MultipleInstanceError( |
|
378 | 378 | 'Multiple incompatible subclass instances of ' |
|
379 | 379 | 'InteractiveShell are being created.' |
|
380 | 380 | ) |
|
381 | 381 | |
|
382 | 382 | @classmethod |
|
383 | 383 | def initialized(cls): |
|
384 | 384 | return hasattr(cls, "_instance") |
|
385 | 385 | |
|
386 | 386 | def get_ipython(self): |
|
387 | 387 | """Return the currently running IPython instance.""" |
|
388 | 388 | return self |
|
389 | 389 | |
|
390 | 390 | #------------------------------------------------------------------------- |
|
391 | 391 | # Trait changed handlers |
|
392 | 392 | #------------------------------------------------------------------------- |
|
393 | 393 | |
|
394 | 394 | def _ipython_dir_changed(self, name, new): |
|
395 | 395 | if not os.path.isdir(new): |
|
396 | 396 | os.makedirs(new, mode = 0777) |
|
397 | 397 | |
|
398 | 398 | def set_autoindent(self,value=None): |
|
399 | 399 | """Set the autoindent flag, checking for readline support. |
|
400 | 400 | |
|
401 | 401 | If called with no arguments, it acts as a toggle.""" |
|
402 | 402 | |
|
403 | 403 | if not self.has_readline: |
|
404 | 404 | if os.name == 'posix': |
|
405 | 405 | warn("The auto-indent feature requires the readline library") |
|
406 | 406 | self.autoindent = 0 |
|
407 | 407 | return |
|
408 | 408 | if value is None: |
|
409 | 409 | self.autoindent = not self.autoindent |
|
410 | 410 | else: |
|
411 | 411 | self.autoindent = value |
|
412 | 412 | |
|
413 | 413 | #------------------------------------------------------------------------- |
|
414 | 414 | # init_* methods called by __init__ |
|
415 | 415 | #------------------------------------------------------------------------- |
|
416 | 416 | |
|
417 | 417 | def init_ipython_dir(self, ipython_dir): |
|
418 | 418 | if ipython_dir is not None: |
|
419 | 419 | self.ipython_dir = ipython_dir |
|
420 | 420 | self.config.Global.ipython_dir = self.ipython_dir |
|
421 | 421 | return |
|
422 | 422 | |
|
423 | 423 | if hasattr(self.config.Global, 'ipython_dir'): |
|
424 | 424 | self.ipython_dir = self.config.Global.ipython_dir |
|
425 | 425 | else: |
|
426 | 426 | self.ipython_dir = get_ipython_dir() |
|
427 | 427 | |
|
428 | 428 | # All children can just read this |
|
429 | 429 | self.config.Global.ipython_dir = self.ipython_dir |
|
430 | 430 | |
|
431 | 431 | def init_instance_attrs(self): |
|
432 | 432 | self.more = False |
|
433 | 433 | |
|
434 | 434 | # command compiler |
|
435 | 435 | self.compile = CachingCompiler() |
|
436 | 436 | |
|
437 | 437 | # Make an empty namespace, which extension writers can rely on both |
|
438 | 438 | # existing and NEVER being used by ipython itself. This gives them a |
|
439 | 439 | # convenient location for storing additional information and state |
|
440 | 440 | # their extensions may require, without fear of collisions with other |
|
441 | 441 | # ipython names that may develop later. |
|
442 | 442 | self.meta = Struct() |
|
443 | 443 | |
|
444 | 444 | # Temporary files used for various purposes. Deleted at exit. |
|
445 | 445 | self.tempfiles = [] |
|
446 | 446 | |
|
447 | 447 | # Keep track of readline usage (later set by init_readline) |
|
448 | 448 | self.has_readline = False |
|
449 | 449 | |
|
450 | 450 | # keep track of where we started running (mainly for crash post-mortem) |
|
451 | 451 | # This is not being used anywhere currently. |
|
452 | 452 | self.starting_dir = os.getcwd() |
|
453 | 453 | |
|
454 | 454 | # Indentation management |
|
455 | 455 | self.indent_current_nsp = 0 |
|
456 | 456 | |
|
457 | 457 | # Dict to track post-execution functions that have been registered |
|
458 | 458 | self._post_execute = {} |
|
459 | 459 | |
|
460 | 460 | def init_environment(self): |
|
461 | 461 | """Any changes we need to make to the user's environment.""" |
|
462 | 462 | pass |
|
463 | 463 | |
|
464 | 464 | def init_encoding(self): |
|
465 | 465 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
466 | 466 | # under Win32 have it set to None, and we need to have a known valid |
|
467 | 467 | # encoding to use in the raw_input() method |
|
468 | 468 | try: |
|
469 | 469 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
470 | 470 | except AttributeError: |
|
471 | 471 | self.stdin_encoding = 'ascii' |
|
472 | 472 | |
|
473 | 473 | def init_syntax_highlighting(self): |
|
474 | 474 | # Python source parser/formatter for syntax highlighting |
|
475 | 475 | pyformat = PyColorize.Parser().format |
|
476 | 476 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
477 | 477 | |
|
478 | 478 | def init_pushd_popd_magic(self): |
|
479 | 479 | # for pushd/popd management |
|
480 | 480 | try: |
|
481 | 481 | self.home_dir = get_home_dir() |
|
482 | 482 | except HomeDirError, msg: |
|
483 | 483 | fatal(msg) |
|
484 | 484 | |
|
485 | 485 | self.dir_stack = [] |
|
486 | 486 | |
|
487 | 487 | def init_logger(self): |
|
488 | 488 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
489 | 489 | logmode='rotate') |
|
490 | 490 | |
|
491 | 491 | def init_logstart(self): |
|
492 | 492 | """Initialize logging in case it was requested at the command line. |
|
493 | 493 | """ |
|
494 | 494 | if self.logappend: |
|
495 | 495 | self.magic_logstart(self.logappend + ' append') |
|
496 | 496 | elif self.logfile: |
|
497 | 497 | self.magic_logstart(self.logfile) |
|
498 | 498 | elif self.logstart: |
|
499 | 499 | self.magic_logstart() |
|
500 | 500 | |
|
501 | 501 | def init_builtins(self): |
|
502 | 502 | self.builtin_trap = BuiltinTrap(shell=self) |
|
503 | 503 | |
|
504 | 504 | def init_inspector(self): |
|
505 | 505 | # Object inspector |
|
506 | 506 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
507 | 507 | PyColorize.ANSICodeColors, |
|
508 | 508 | 'NoColor', |
|
509 | 509 | self.object_info_string_level) |
|
510 | 510 | |
|
511 | 511 | def init_io(self): |
|
512 | 512 | # This will just use sys.stdout and sys.stderr. If you want to |
|
513 | 513 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
514 |
# *before* instantiating this class, because |
|
|
514 | # *before* instantiating this class, because io holds onto | |
|
515 | 515 | # references to the underlying streams. |
|
516 | 516 | if sys.platform == 'win32' and self.has_readline: |
|
517 |
|
|
|
518 | cerr=self.readline._outputfile) | |
|
517 | io.stdout = io.stderr = io.IOStream(self.readline._outputfile) | |
|
519 | 518 | else: |
|
520 |
|
|
|
521 | io.Term = Term | |
|
519 | io.stdout = io.IOStream(sys.stdout) | |
|
520 | io.stderr = io.IOStream(sys.stderr) | |
|
522 | 521 | |
|
523 | 522 | def init_prompts(self): |
|
524 | 523 | # TODO: This is a pass for now because the prompts are managed inside |
|
525 | 524 | # the DisplayHook. Once there is a separate prompt manager, this |
|
526 | 525 | # will initialize that object and all prompt related information. |
|
527 | 526 | pass |
|
528 | 527 | |
|
529 | 528 | def init_display_formatter(self): |
|
530 | 529 | self.display_formatter = DisplayFormatter(config=self.config) |
|
531 | 530 | |
|
532 | 531 | def init_display_pub(self): |
|
533 | 532 | self.display_pub = self.display_pub_class(config=self.config) |
|
534 | 533 | |
|
535 | 534 | def init_displayhook(self): |
|
536 | 535 | # Initialize displayhook, set in/out prompts and printing system |
|
537 | 536 | self.displayhook = self.displayhook_class( |
|
538 | 537 | config=self.config, |
|
539 | 538 | shell=self, |
|
540 | 539 | cache_size=self.cache_size, |
|
541 | 540 | input_sep = self.separate_in, |
|
542 | 541 | output_sep = self.separate_out, |
|
543 | 542 | output_sep2 = self.separate_out2, |
|
544 | 543 | ps1 = self.prompt_in1, |
|
545 | 544 | ps2 = self.prompt_in2, |
|
546 | 545 | ps_out = self.prompt_out, |
|
547 | 546 | pad_left = self.prompts_pad_left |
|
548 | 547 | ) |
|
549 | 548 | # This is a context manager that installs/revmoes the displayhook at |
|
550 | 549 | # the appropriate time. |
|
551 | 550 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
552 | 551 | |
|
553 | 552 | def init_reload_doctest(self): |
|
554 | 553 | # Do a proper resetting of doctest, including the necessary displayhook |
|
555 | 554 | # monkeypatching |
|
556 | 555 | try: |
|
557 | 556 | doctest_reload() |
|
558 | 557 | except ImportError: |
|
559 | 558 | warn("doctest module does not exist.") |
|
560 | 559 | |
|
561 | 560 | #------------------------------------------------------------------------- |
|
562 | 561 | # Things related to injections into the sys module |
|
563 | 562 | #------------------------------------------------------------------------- |
|
564 | 563 | |
|
565 | 564 | def save_sys_module_state(self): |
|
566 | 565 | """Save the state of hooks in the sys module. |
|
567 | 566 | |
|
568 | 567 | This has to be called after self.user_ns is created. |
|
569 | 568 | """ |
|
570 | 569 | self._orig_sys_module_state = {} |
|
571 | 570 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
572 | 571 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
573 | 572 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
574 | 573 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
575 | 574 | try: |
|
576 | 575 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
577 | 576 | except KeyError: |
|
578 | 577 | pass |
|
579 | 578 | |
|
580 | 579 | def restore_sys_module_state(self): |
|
581 | 580 | """Restore the state of the sys module.""" |
|
582 | 581 | try: |
|
583 | 582 | for k, v in self._orig_sys_module_state.iteritems(): |
|
584 | 583 | setattr(sys, k, v) |
|
585 | 584 | except AttributeError: |
|
586 | 585 | pass |
|
587 | 586 | # Reset what what done in self.init_sys_modules |
|
588 | 587 | try: |
|
589 | 588 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
590 | 589 | except (AttributeError, KeyError): |
|
591 | 590 | pass |
|
592 | 591 | |
|
593 | 592 | #------------------------------------------------------------------------- |
|
594 | 593 | # Things related to hooks |
|
595 | 594 | #------------------------------------------------------------------------- |
|
596 | 595 | |
|
597 | 596 | def init_hooks(self): |
|
598 | 597 | # hooks holds pointers used for user-side customizations |
|
599 | 598 | self.hooks = Struct() |
|
600 | 599 | |
|
601 | 600 | self.strdispatchers = {} |
|
602 | 601 | |
|
603 | 602 | # Set all default hooks, defined in the IPython.hooks module. |
|
604 | 603 | hooks = IPython.core.hooks |
|
605 | 604 | for hook_name in hooks.__all__: |
|
606 | 605 | # default hooks have priority 100, i.e. low; user hooks should have |
|
607 | 606 | # 0-100 priority |
|
608 | 607 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
609 | 608 | |
|
610 | 609 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
611 | 610 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
612 | 611 | |
|
613 | 612 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
614 | 613 | adding your function to one of these hooks, you can modify IPython's |
|
615 | 614 | behavior to call at runtime your own routines.""" |
|
616 | 615 | |
|
617 | 616 | # At some point in the future, this should validate the hook before it |
|
618 | 617 | # accepts it. Probably at least check that the hook takes the number |
|
619 | 618 | # of args it's supposed to. |
|
620 | 619 | |
|
621 | 620 | f = types.MethodType(hook,self) |
|
622 | 621 | |
|
623 | 622 | # check if the hook is for strdispatcher first |
|
624 | 623 | if str_key is not None: |
|
625 | 624 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
626 | 625 | sdp.add_s(str_key, f, priority ) |
|
627 | 626 | self.strdispatchers[name] = sdp |
|
628 | 627 | return |
|
629 | 628 | if re_key is not None: |
|
630 | 629 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
631 | 630 | sdp.add_re(re.compile(re_key), f, priority ) |
|
632 | 631 | self.strdispatchers[name] = sdp |
|
633 | 632 | return |
|
634 | 633 | |
|
635 | 634 | dp = getattr(self.hooks, name, None) |
|
636 | 635 | if name not in IPython.core.hooks.__all__: |
|
637 | 636 | print "Warning! Hook '%s' is not one of %s" % \ |
|
638 | 637 | (name, IPython.core.hooks.__all__ ) |
|
639 | 638 | if not dp: |
|
640 | 639 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
641 | 640 | |
|
642 | 641 | try: |
|
643 | 642 | dp.add(f,priority) |
|
644 | 643 | except AttributeError: |
|
645 | 644 | # it was not commandchain, plain old func - replace |
|
646 | 645 | dp = f |
|
647 | 646 | |
|
648 | 647 | setattr(self.hooks,name, dp) |
|
649 | 648 | |
|
650 | 649 | def register_post_execute(self, func): |
|
651 | 650 | """Register a function for calling after code execution. |
|
652 | 651 | """ |
|
653 | 652 | if not callable(func): |
|
654 | 653 | raise ValueError('argument %s must be callable' % func) |
|
655 | 654 | self._post_execute[func] = True |
|
656 | 655 | |
|
657 | 656 | #------------------------------------------------------------------------- |
|
658 | 657 | # Things related to the "main" module |
|
659 | 658 | #------------------------------------------------------------------------- |
|
660 | 659 | |
|
661 | 660 | def new_main_mod(self,ns=None): |
|
662 | 661 | """Return a new 'main' module object for user code execution. |
|
663 | 662 | """ |
|
664 | 663 | main_mod = self._user_main_module |
|
665 | 664 | init_fakemod_dict(main_mod,ns) |
|
666 | 665 | return main_mod |
|
667 | 666 | |
|
668 | 667 | def cache_main_mod(self,ns,fname): |
|
669 | 668 | """Cache a main module's namespace. |
|
670 | 669 | |
|
671 | 670 | When scripts are executed via %run, we must keep a reference to the |
|
672 | 671 | namespace of their __main__ module (a FakeModule instance) around so |
|
673 | 672 | that Python doesn't clear it, rendering objects defined therein |
|
674 | 673 | useless. |
|
675 | 674 | |
|
676 | 675 | This method keeps said reference in a private dict, keyed by the |
|
677 | 676 | absolute path of the module object (which corresponds to the script |
|
678 | 677 | path). This way, for multiple executions of the same script we only |
|
679 | 678 | keep one copy of the namespace (the last one), thus preventing memory |
|
680 | 679 | leaks from old references while allowing the objects from the last |
|
681 | 680 | execution to be accessible. |
|
682 | 681 | |
|
683 | 682 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
684 | 683 | because of how Python tears down modules (it hard-sets all their |
|
685 | 684 | references to None without regard for reference counts). This method |
|
686 | 685 | must therefore make a *copy* of the given namespace, to allow the |
|
687 | 686 | original module's __dict__ to be cleared and reused. |
|
688 | 687 | |
|
689 | 688 | |
|
690 | 689 | Parameters |
|
691 | 690 | ---------- |
|
692 | 691 | ns : a namespace (a dict, typically) |
|
693 | 692 | |
|
694 | 693 | fname : str |
|
695 | 694 | Filename associated with the namespace. |
|
696 | 695 | |
|
697 | 696 | Examples |
|
698 | 697 | -------- |
|
699 | 698 | |
|
700 | 699 | In [10]: import IPython |
|
701 | 700 | |
|
702 | 701 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
703 | 702 | |
|
704 | 703 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
705 | 704 | Out[12]: True |
|
706 | 705 | """ |
|
707 | 706 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
708 | 707 | |
|
709 | 708 | def clear_main_mod_cache(self): |
|
710 | 709 | """Clear the cache of main modules. |
|
711 | 710 | |
|
712 | 711 | Mainly for use by utilities like %reset. |
|
713 | 712 | |
|
714 | 713 | Examples |
|
715 | 714 | -------- |
|
716 | 715 | |
|
717 | 716 | In [15]: import IPython |
|
718 | 717 | |
|
719 | 718 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
720 | 719 | |
|
721 | 720 | In [17]: len(_ip._main_ns_cache) > 0 |
|
722 | 721 | Out[17]: True |
|
723 | 722 | |
|
724 | 723 | In [18]: _ip.clear_main_mod_cache() |
|
725 | 724 | |
|
726 | 725 | In [19]: len(_ip._main_ns_cache) == 0 |
|
727 | 726 | Out[19]: True |
|
728 | 727 | """ |
|
729 | 728 | self._main_ns_cache.clear() |
|
730 | 729 | |
|
731 | 730 | #------------------------------------------------------------------------- |
|
732 | 731 | # Things related to debugging |
|
733 | 732 | #------------------------------------------------------------------------- |
|
734 | 733 | |
|
735 | 734 | def init_pdb(self): |
|
736 | 735 | # Set calling of pdb on exceptions |
|
737 | 736 | # self.call_pdb is a property |
|
738 | 737 | self.call_pdb = self.pdb |
|
739 | 738 | |
|
740 | 739 | def _get_call_pdb(self): |
|
741 | 740 | return self._call_pdb |
|
742 | 741 | |
|
743 | 742 | def _set_call_pdb(self,val): |
|
744 | 743 | |
|
745 | 744 | if val not in (0,1,False,True): |
|
746 | 745 | raise ValueError,'new call_pdb value must be boolean' |
|
747 | 746 | |
|
748 | 747 | # store value in instance |
|
749 | 748 | self._call_pdb = val |
|
750 | 749 | |
|
751 | 750 | # notify the actual exception handlers |
|
752 | 751 | self.InteractiveTB.call_pdb = val |
|
753 | 752 | |
|
754 | 753 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
755 | 754 | 'Control auto-activation of pdb at exceptions') |
|
756 | 755 | |
|
757 | 756 | def debugger(self,force=False): |
|
758 | 757 | """Call the pydb/pdb debugger. |
|
759 | 758 | |
|
760 | 759 | Keywords: |
|
761 | 760 | |
|
762 | 761 | - force(False): by default, this routine checks the instance call_pdb |
|
763 | 762 | flag and does not actually invoke the debugger if the flag is false. |
|
764 | 763 | The 'force' option forces the debugger to activate even if the flag |
|
765 | 764 | is false. |
|
766 | 765 | """ |
|
767 | 766 | |
|
768 | 767 | if not (force or self.call_pdb): |
|
769 | 768 | return |
|
770 | 769 | |
|
771 | 770 | if not hasattr(sys,'last_traceback'): |
|
772 | 771 | error('No traceback has been produced, nothing to debug.') |
|
773 | 772 | return |
|
774 | 773 | |
|
775 | 774 | # use pydb if available |
|
776 | 775 | if debugger.has_pydb: |
|
777 | 776 | from pydb import pm |
|
778 | 777 | else: |
|
779 | 778 | # fallback to our internal debugger |
|
780 | 779 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
781 | 780 | |
|
782 | 781 | with self.readline_no_record: |
|
783 | 782 | pm() |
|
784 | 783 | |
|
785 | 784 | #------------------------------------------------------------------------- |
|
786 | 785 | # Things related to IPython's various namespaces |
|
787 | 786 | #------------------------------------------------------------------------- |
|
788 | 787 | |
|
789 | 788 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
790 | 789 | # Create the namespace where the user will operate. user_ns is |
|
791 | 790 | # normally the only one used, and it is passed to the exec calls as |
|
792 | 791 | # the locals argument. But we do carry a user_global_ns namespace |
|
793 | 792 | # given as the exec 'globals' argument, This is useful in embedding |
|
794 | 793 | # situations where the ipython shell opens in a context where the |
|
795 | 794 | # distinction between locals and globals is meaningful. For |
|
796 | 795 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
797 | 796 | |
|
798 | 797 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
799 | 798 | # level as a dict instead of a module. This is a manual fix, but I |
|
800 | 799 | # should really track down where the problem is coming from. Alex |
|
801 | 800 | # Schmolck reported this problem first. |
|
802 | 801 | |
|
803 | 802 | # A useful post by Alex Martelli on this topic: |
|
804 | 803 | # Re: inconsistent value from __builtins__ |
|
805 | 804 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
806 | 805 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
807 | 806 | # Gruppen: comp.lang.python |
|
808 | 807 | |
|
809 | 808 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
810 | 809 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
811 | 810 | # > <type 'dict'> |
|
812 | 811 | # > >>> print type(__builtins__) |
|
813 | 812 | # > <type 'module'> |
|
814 | 813 | # > Is this difference in return value intentional? |
|
815 | 814 | |
|
816 | 815 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
817 | 816 | # or a module, and it's been that way for a long time. Whether it's |
|
818 | 817 | # intentional (or sensible), I don't know. In any case, the idea is |
|
819 | 818 | # that if you need to access the built-in namespace directly, you |
|
820 | 819 | # should start with "import __builtin__" (note, no 's') which will |
|
821 | 820 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
822 | 821 | |
|
823 | 822 | # These routines return properly built dicts as needed by the rest of |
|
824 | 823 | # the code, and can also be used by extension writers to generate |
|
825 | 824 | # properly initialized namespaces. |
|
826 | 825 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
827 | 826 | user_global_ns) |
|
828 | 827 | |
|
829 | 828 | # Assign namespaces |
|
830 | 829 | # This is the namespace where all normal user variables live |
|
831 | 830 | self.user_ns = user_ns |
|
832 | 831 | self.user_global_ns = user_global_ns |
|
833 | 832 | |
|
834 | 833 | # An auxiliary namespace that checks what parts of the user_ns were |
|
835 | 834 | # loaded at startup, so we can list later only variables defined in |
|
836 | 835 | # actual interactive use. Since it is always a subset of user_ns, it |
|
837 | 836 | # doesn't need to be separately tracked in the ns_table. |
|
838 | 837 | self.user_ns_hidden = {} |
|
839 | 838 | |
|
840 | 839 | # A namespace to keep track of internal data structures to prevent |
|
841 | 840 | # them from cluttering user-visible stuff. Will be updated later |
|
842 | 841 | self.internal_ns = {} |
|
843 | 842 | |
|
844 | 843 | # Now that FakeModule produces a real module, we've run into a nasty |
|
845 | 844 | # problem: after script execution (via %run), the module where the user |
|
846 | 845 | # code ran is deleted. Now that this object is a true module (needed |
|
847 | 846 | # so docetst and other tools work correctly), the Python module |
|
848 | 847 | # teardown mechanism runs over it, and sets to None every variable |
|
849 | 848 | # present in that module. Top-level references to objects from the |
|
850 | 849 | # script survive, because the user_ns is updated with them. However, |
|
851 | 850 | # calling functions defined in the script that use other things from |
|
852 | 851 | # the script will fail, because the function's closure had references |
|
853 | 852 | # to the original objects, which are now all None. So we must protect |
|
854 | 853 | # these modules from deletion by keeping a cache. |
|
855 | 854 | # |
|
856 | 855 | # To avoid keeping stale modules around (we only need the one from the |
|
857 | 856 | # last run), we use a dict keyed with the full path to the script, so |
|
858 | 857 | # only the last version of the module is held in the cache. Note, |
|
859 | 858 | # however, that we must cache the module *namespace contents* (their |
|
860 | 859 | # __dict__). Because if we try to cache the actual modules, old ones |
|
861 | 860 | # (uncached) could be destroyed while still holding references (such as |
|
862 | 861 | # those held by GUI objects that tend to be long-lived)> |
|
863 | 862 | # |
|
864 | 863 | # The %reset command will flush this cache. See the cache_main_mod() |
|
865 | 864 | # and clear_main_mod_cache() methods for details on use. |
|
866 | 865 | |
|
867 | 866 | # This is the cache used for 'main' namespaces |
|
868 | 867 | self._main_ns_cache = {} |
|
869 | 868 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
870 | 869 | # copying and clearing for reuse on each %run |
|
871 | 870 | self._user_main_module = FakeModule() |
|
872 | 871 | |
|
873 | 872 | # A table holding all the namespaces IPython deals with, so that |
|
874 | 873 | # introspection facilities can search easily. |
|
875 | 874 | self.ns_table = {'user':user_ns, |
|
876 | 875 | 'user_global':user_global_ns, |
|
877 | 876 | 'internal':self.internal_ns, |
|
878 | 877 | 'builtin':__builtin__.__dict__ |
|
879 | 878 | } |
|
880 | 879 | |
|
881 | 880 | # Similarly, track all namespaces where references can be held and that |
|
882 | 881 | # we can safely clear (so it can NOT include builtin). This one can be |
|
883 | 882 | # a simple list. Note that the main execution namespaces, user_ns and |
|
884 | 883 | # user_global_ns, can NOT be listed here, as clearing them blindly |
|
885 | 884 | # causes errors in object __del__ methods. Instead, the reset() method |
|
886 | 885 | # clears them manually and carefully. |
|
887 | 886 | self.ns_refs_table = [ self.user_ns_hidden, |
|
888 | 887 | self.internal_ns, self._main_ns_cache ] |
|
889 | 888 | |
|
890 | 889 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
891 | 890 | """Return a valid local and global user interactive namespaces. |
|
892 | 891 | |
|
893 | 892 | This builds a dict with the minimal information needed to operate as a |
|
894 | 893 | valid IPython user namespace, which you can pass to the various |
|
895 | 894 | embedding classes in ipython. The default implementation returns the |
|
896 | 895 | same dict for both the locals and the globals to allow functions to |
|
897 | 896 | refer to variables in the namespace. Customized implementations can |
|
898 | 897 | return different dicts. The locals dictionary can actually be anything |
|
899 | 898 | following the basic mapping protocol of a dict, but the globals dict |
|
900 | 899 | must be a true dict, not even a subclass. It is recommended that any |
|
901 | 900 | custom object for the locals namespace synchronize with the globals |
|
902 | 901 | dict somehow. |
|
903 | 902 | |
|
904 | 903 | Raises TypeError if the provided globals namespace is not a true dict. |
|
905 | 904 | |
|
906 | 905 | Parameters |
|
907 | 906 | ---------- |
|
908 | 907 | user_ns : dict-like, optional |
|
909 | 908 | The current user namespace. The items in this namespace should |
|
910 | 909 | be included in the output. If None, an appropriate blank |
|
911 | 910 | namespace should be created. |
|
912 | 911 | user_global_ns : dict, optional |
|
913 | 912 | The current user global namespace. The items in this namespace |
|
914 | 913 | should be included in the output. If None, an appropriate |
|
915 | 914 | blank namespace should be created. |
|
916 | 915 | |
|
917 | 916 | Returns |
|
918 | 917 | ------- |
|
919 | 918 | A pair of dictionary-like object to be used as the local namespace |
|
920 | 919 | of the interpreter and a dict to be used as the global namespace. |
|
921 | 920 | """ |
|
922 | 921 | |
|
923 | 922 | |
|
924 | 923 | # We must ensure that __builtin__ (without the final 's') is always |
|
925 | 924 | # available and pointing to the __builtin__ *module*. For more details: |
|
926 | 925 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
927 | 926 | |
|
928 | 927 | if user_ns is None: |
|
929 | 928 | # Set __name__ to __main__ to better match the behavior of the |
|
930 | 929 | # normal interpreter. |
|
931 | 930 | user_ns = {'__name__' :'__main__', |
|
932 | 931 | '__builtin__' : __builtin__, |
|
933 | 932 | '__builtins__' : __builtin__, |
|
934 | 933 | } |
|
935 | 934 | else: |
|
936 | 935 | user_ns.setdefault('__name__','__main__') |
|
937 | 936 | user_ns.setdefault('__builtin__',__builtin__) |
|
938 | 937 | user_ns.setdefault('__builtins__',__builtin__) |
|
939 | 938 | |
|
940 | 939 | if user_global_ns is None: |
|
941 | 940 | user_global_ns = user_ns |
|
942 | 941 | if type(user_global_ns) is not dict: |
|
943 | 942 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
944 | 943 | % type(user_global_ns)) |
|
945 | 944 | |
|
946 | 945 | return user_ns, user_global_ns |
|
947 | 946 | |
|
948 | 947 | def init_sys_modules(self): |
|
949 | 948 | # We need to insert into sys.modules something that looks like a |
|
950 | 949 | # module but which accesses the IPython namespace, for shelve and |
|
951 | 950 | # pickle to work interactively. Normally they rely on getting |
|
952 | 951 | # everything out of __main__, but for embedding purposes each IPython |
|
953 | 952 | # instance has its own private namespace, so we can't go shoving |
|
954 | 953 | # everything into __main__. |
|
955 | 954 | |
|
956 | 955 | # note, however, that we should only do this for non-embedded |
|
957 | 956 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
958 | 957 | # namespace. Embedded instances, on the other hand, should not do |
|
959 | 958 | # this because they need to manage the user local/global namespaces |
|
960 | 959 | # only, but they live within a 'normal' __main__ (meaning, they |
|
961 | 960 | # shouldn't overtake the execution environment of the script they're |
|
962 | 961 | # embedded in). |
|
963 | 962 | |
|
964 | 963 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
965 | 964 | |
|
966 | 965 | try: |
|
967 | 966 | main_name = self.user_ns['__name__'] |
|
968 | 967 | except KeyError: |
|
969 | 968 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
970 | 969 | else: |
|
971 | 970 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
972 | 971 | |
|
973 | 972 | def init_user_ns(self): |
|
974 | 973 | """Initialize all user-visible namespaces to their minimum defaults. |
|
975 | 974 | |
|
976 | 975 | Certain history lists are also initialized here, as they effectively |
|
977 | 976 | act as user namespaces. |
|
978 | 977 | |
|
979 | 978 | Notes |
|
980 | 979 | ----- |
|
981 | 980 | All data structures here are only filled in, they are NOT reset by this |
|
982 | 981 | method. If they were not empty before, data will simply be added to |
|
983 | 982 | therm. |
|
984 | 983 | """ |
|
985 | 984 | # This function works in two parts: first we put a few things in |
|
986 | 985 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
987 | 986 | # initial variables aren't shown by %who. After the sync, we add the |
|
988 | 987 | # rest of what we *do* want the user to see with %who even on a new |
|
989 | 988 | # session (probably nothing, so theye really only see their own stuff) |
|
990 | 989 | |
|
991 | 990 | # The user dict must *always* have a __builtin__ reference to the |
|
992 | 991 | # Python standard __builtin__ namespace, which must be imported. |
|
993 | 992 | # This is so that certain operations in prompt evaluation can be |
|
994 | 993 | # reliably executed with builtins. Note that we can NOT use |
|
995 | 994 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
996 | 995 | # module, and can even mutate at runtime, depending on the context |
|
997 | 996 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
998 | 997 | # always a module object, though it must be explicitly imported. |
|
999 | 998 | |
|
1000 | 999 | # For more details: |
|
1001 | 1000 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1002 | 1001 | ns = dict(__builtin__ = __builtin__) |
|
1003 | 1002 | |
|
1004 | 1003 | # Put 'help' in the user namespace |
|
1005 | 1004 | try: |
|
1006 | 1005 | from site import _Helper |
|
1007 | 1006 | ns['help'] = _Helper() |
|
1008 | 1007 | except ImportError: |
|
1009 | 1008 | warn('help() not available - check site.py') |
|
1010 | 1009 | |
|
1011 | 1010 | # make global variables for user access to the histories |
|
1012 | 1011 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1013 | 1012 | ns['_oh'] = self.history_manager.output_hist |
|
1014 | 1013 | ns['_dh'] = self.history_manager.dir_hist |
|
1015 | 1014 | |
|
1016 | 1015 | ns['_sh'] = shadowns |
|
1017 | 1016 | |
|
1018 | 1017 | # user aliases to input and output histories. These shouldn't show up |
|
1019 | 1018 | # in %who, as they can have very large reprs. |
|
1020 | 1019 | ns['In'] = self.history_manager.input_hist_parsed |
|
1021 | 1020 | ns['Out'] = self.history_manager.output_hist |
|
1022 | 1021 | |
|
1023 | 1022 | # Store myself as the public api!!! |
|
1024 | 1023 | ns['get_ipython'] = self.get_ipython |
|
1025 | 1024 | |
|
1026 | 1025 | ns['exit'] = self.exiter |
|
1027 | 1026 | ns['quit'] = self.exiter |
|
1028 | 1027 | |
|
1029 | 1028 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1030 | 1029 | # by %who |
|
1031 | 1030 | self.user_ns_hidden.update(ns) |
|
1032 | 1031 | |
|
1033 | 1032 | # Anything put into ns now would show up in %who. Think twice before |
|
1034 | 1033 | # putting anything here, as we really want %who to show the user their |
|
1035 | 1034 | # stuff, not our variables. |
|
1036 | 1035 | |
|
1037 | 1036 | # Finally, update the real user's namespace |
|
1038 | 1037 | self.user_ns.update(ns) |
|
1039 | 1038 | |
|
1040 | 1039 | def reset(self, new_session=True): |
|
1041 | 1040 | """Clear all internal namespaces, and attempt to release references to |
|
1042 | 1041 | user objects. |
|
1043 | 1042 | |
|
1044 | 1043 | If new_session is True, a new history session will be opened. |
|
1045 | 1044 | """ |
|
1046 | 1045 | # Clear histories |
|
1047 | 1046 | self.history_manager.reset(new_session) |
|
1048 | 1047 | # Reset counter used to index all histories |
|
1049 | 1048 | if new_session: |
|
1050 | 1049 | self.execution_count = 1 |
|
1051 | 1050 | |
|
1052 | 1051 | # Flush cached output items |
|
1053 | 1052 | self.displayhook.flush() |
|
1054 | 1053 | |
|
1055 | 1054 | # Restore the user namespaces to minimal usability |
|
1056 | 1055 | for ns in self.ns_refs_table: |
|
1057 | 1056 | ns.clear() |
|
1058 | 1057 | |
|
1059 | 1058 | # The main execution namespaces must be cleared very carefully, |
|
1060 | 1059 | # skipping the deletion of the builtin-related keys, because doing so |
|
1061 | 1060 | # would cause errors in many object's __del__ methods. |
|
1062 | 1061 | for ns in [self.user_ns, self.user_global_ns]: |
|
1063 | 1062 | drop_keys = set(ns.keys()) |
|
1064 | 1063 | drop_keys.discard('__builtin__') |
|
1065 | 1064 | drop_keys.discard('__builtins__') |
|
1066 | 1065 | for k in drop_keys: |
|
1067 | 1066 | del ns[k] |
|
1068 | 1067 | |
|
1069 | 1068 | # Restore the user namespaces to minimal usability |
|
1070 | 1069 | self.init_user_ns() |
|
1071 | 1070 | |
|
1072 | 1071 | # Restore the default and user aliases |
|
1073 | 1072 | self.alias_manager.clear_aliases() |
|
1074 | 1073 | self.alias_manager.init_aliases() |
|
1075 | 1074 | |
|
1076 | 1075 | # Flush the private list of module references kept for script |
|
1077 | 1076 | # execution protection |
|
1078 | 1077 | self.clear_main_mod_cache() |
|
1079 | 1078 | |
|
1080 | 1079 | # Clear out the namespace from the last %run |
|
1081 | 1080 | self.new_main_mod() |
|
1082 | 1081 | |
|
1083 | 1082 | def reset_selective(self, regex=None): |
|
1084 | 1083 | """Clear selective variables from internal namespaces based on a |
|
1085 | 1084 | specified regular expression. |
|
1086 | 1085 | |
|
1087 | 1086 | Parameters |
|
1088 | 1087 | ---------- |
|
1089 | 1088 | regex : string or compiled pattern, optional |
|
1090 | 1089 | A regular expression pattern that will be used in searching |
|
1091 | 1090 | variable names in the users namespaces. |
|
1092 | 1091 | """ |
|
1093 | 1092 | if regex is not None: |
|
1094 | 1093 | try: |
|
1095 | 1094 | m = re.compile(regex) |
|
1096 | 1095 | except TypeError: |
|
1097 | 1096 | raise TypeError('regex must be a string or compiled pattern') |
|
1098 | 1097 | # Search for keys in each namespace that match the given regex |
|
1099 | 1098 | # If a match is found, delete the key/value pair. |
|
1100 | 1099 | for ns in self.ns_refs_table: |
|
1101 | 1100 | for var in ns: |
|
1102 | 1101 | if m.search(var): |
|
1103 | 1102 | del ns[var] |
|
1104 | 1103 | |
|
1105 | 1104 | def push(self, variables, interactive=True): |
|
1106 | 1105 | """Inject a group of variables into the IPython user namespace. |
|
1107 | 1106 | |
|
1108 | 1107 | Parameters |
|
1109 | 1108 | ---------- |
|
1110 | 1109 | variables : dict, str or list/tuple of str |
|
1111 | 1110 | The variables to inject into the user's namespace. If a dict, a |
|
1112 | 1111 | simple update is done. If a str, the string is assumed to have |
|
1113 | 1112 | variable names separated by spaces. A list/tuple of str can also |
|
1114 | 1113 | be used to give the variable names. If just the variable names are |
|
1115 | 1114 | give (list/tuple/str) then the variable values looked up in the |
|
1116 | 1115 | callers frame. |
|
1117 | 1116 | interactive : bool |
|
1118 | 1117 | If True (default), the variables will be listed with the ``who`` |
|
1119 | 1118 | magic. |
|
1120 | 1119 | """ |
|
1121 | 1120 | vdict = None |
|
1122 | 1121 | |
|
1123 | 1122 | # We need a dict of name/value pairs to do namespace updates. |
|
1124 | 1123 | if isinstance(variables, dict): |
|
1125 | 1124 | vdict = variables |
|
1126 | 1125 | elif isinstance(variables, (basestring, list, tuple)): |
|
1127 | 1126 | if isinstance(variables, basestring): |
|
1128 | 1127 | vlist = variables.split() |
|
1129 | 1128 | else: |
|
1130 | 1129 | vlist = variables |
|
1131 | 1130 | vdict = {} |
|
1132 | 1131 | cf = sys._getframe(1) |
|
1133 | 1132 | for name in vlist: |
|
1134 | 1133 | try: |
|
1135 | 1134 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1136 | 1135 | except: |
|
1137 | 1136 | print ('Could not get variable %s from %s' % |
|
1138 | 1137 | (name,cf.f_code.co_name)) |
|
1139 | 1138 | else: |
|
1140 | 1139 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1141 | 1140 | |
|
1142 | 1141 | # Propagate variables to user namespace |
|
1143 | 1142 | self.user_ns.update(vdict) |
|
1144 | 1143 | |
|
1145 | 1144 | # And configure interactive visibility |
|
1146 | 1145 | config_ns = self.user_ns_hidden |
|
1147 | 1146 | if interactive: |
|
1148 | 1147 | for name, val in vdict.iteritems(): |
|
1149 | 1148 | config_ns.pop(name, None) |
|
1150 | 1149 | else: |
|
1151 | 1150 | for name,val in vdict.iteritems(): |
|
1152 | 1151 | config_ns[name] = val |
|
1153 | 1152 | |
|
1154 | 1153 | #------------------------------------------------------------------------- |
|
1155 | 1154 | # Things related to object introspection |
|
1156 | 1155 | #------------------------------------------------------------------------- |
|
1157 | 1156 | |
|
1158 | 1157 | def _ofind(self, oname, namespaces=None): |
|
1159 | 1158 | """Find an object in the available namespaces. |
|
1160 | 1159 | |
|
1161 | 1160 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1162 | 1161 | |
|
1163 | 1162 | Has special code to detect magic functions. |
|
1164 | 1163 | """ |
|
1165 | 1164 | #oname = oname.strip() |
|
1166 | 1165 | #print '1- oname: <%r>' % oname # dbg |
|
1167 | 1166 | try: |
|
1168 | 1167 | oname = oname.strip().encode('ascii') |
|
1169 | 1168 | #print '2- oname: <%r>' % oname # dbg |
|
1170 | 1169 | except UnicodeEncodeError: |
|
1171 | 1170 | print 'Python identifiers can only contain ascii characters.' |
|
1172 | 1171 | return dict(found=False) |
|
1173 | 1172 | |
|
1174 | 1173 | alias_ns = None |
|
1175 | 1174 | if namespaces is None: |
|
1176 | 1175 | # Namespaces to search in: |
|
1177 | 1176 | # Put them in a list. The order is important so that we |
|
1178 | 1177 | # find things in the same order that Python finds them. |
|
1179 | 1178 | namespaces = [ ('Interactive', self.user_ns), |
|
1180 | 1179 | ('IPython internal', self.internal_ns), |
|
1181 | 1180 | ('Python builtin', __builtin__.__dict__), |
|
1182 | 1181 | ('Alias', self.alias_manager.alias_table), |
|
1183 | 1182 | ] |
|
1184 | 1183 | alias_ns = self.alias_manager.alias_table |
|
1185 | 1184 | |
|
1186 | 1185 | # initialize results to 'null' |
|
1187 | 1186 | found = False; obj = None; ospace = None; ds = None; |
|
1188 | 1187 | ismagic = False; isalias = False; parent = None |
|
1189 | 1188 | |
|
1190 | 1189 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1191 | 1190 | # function but should only be treated as one if print_function was |
|
1192 | 1191 | # loaded with a future import. In this case, just bail. |
|
1193 | 1192 | if (oname == 'print' and not (self.compile.compiler_flags & |
|
1194 | 1193 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1195 | 1194 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1196 | 1195 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1197 | 1196 | |
|
1198 | 1197 | # Look for the given name by splitting it in parts. If the head is |
|
1199 | 1198 | # found, then we look for all the remaining parts as members, and only |
|
1200 | 1199 | # declare success if we can find them all. |
|
1201 | 1200 | oname_parts = oname.split('.') |
|
1202 | 1201 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1203 | 1202 | for nsname,ns in namespaces: |
|
1204 | 1203 | try: |
|
1205 | 1204 | obj = ns[oname_head] |
|
1206 | 1205 | except KeyError: |
|
1207 | 1206 | continue |
|
1208 | 1207 | else: |
|
1209 | 1208 | #print 'oname_rest:', oname_rest # dbg |
|
1210 | 1209 | for part in oname_rest: |
|
1211 | 1210 | try: |
|
1212 | 1211 | parent = obj |
|
1213 | 1212 | obj = getattr(obj,part) |
|
1214 | 1213 | except: |
|
1215 | 1214 | # Blanket except b/c some badly implemented objects |
|
1216 | 1215 | # allow __getattr__ to raise exceptions other than |
|
1217 | 1216 | # AttributeError, which then crashes IPython. |
|
1218 | 1217 | break |
|
1219 | 1218 | else: |
|
1220 | 1219 | # If we finish the for loop (no break), we got all members |
|
1221 | 1220 | found = True |
|
1222 | 1221 | ospace = nsname |
|
1223 | 1222 | if ns == alias_ns: |
|
1224 | 1223 | isalias = True |
|
1225 | 1224 | break # namespace loop |
|
1226 | 1225 | |
|
1227 | 1226 | # Try to see if it's magic |
|
1228 | 1227 | if not found: |
|
1229 | 1228 | if oname.startswith(ESC_MAGIC): |
|
1230 | 1229 | oname = oname[1:] |
|
1231 | 1230 | obj = getattr(self,'magic_'+oname,None) |
|
1232 | 1231 | if obj is not None: |
|
1233 | 1232 | found = True |
|
1234 | 1233 | ospace = 'IPython internal' |
|
1235 | 1234 | ismagic = True |
|
1236 | 1235 | |
|
1237 | 1236 | # Last try: special-case some literals like '', [], {}, etc: |
|
1238 | 1237 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1239 | 1238 | obj = eval(oname_head) |
|
1240 | 1239 | found = True |
|
1241 | 1240 | ospace = 'Interactive' |
|
1242 | 1241 | |
|
1243 | 1242 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1244 | 1243 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1245 | 1244 | |
|
1246 | 1245 | def _ofind_property(self, oname, info): |
|
1247 | 1246 | """Second part of object finding, to look for property details.""" |
|
1248 | 1247 | if info.found: |
|
1249 | 1248 | # Get the docstring of the class property if it exists. |
|
1250 | 1249 | path = oname.split('.') |
|
1251 | 1250 | root = '.'.join(path[:-1]) |
|
1252 | 1251 | if info.parent is not None: |
|
1253 | 1252 | try: |
|
1254 | 1253 | target = getattr(info.parent, '__class__') |
|
1255 | 1254 | # The object belongs to a class instance. |
|
1256 | 1255 | try: |
|
1257 | 1256 | target = getattr(target, path[-1]) |
|
1258 | 1257 | # The class defines the object. |
|
1259 | 1258 | if isinstance(target, property): |
|
1260 | 1259 | oname = root + '.__class__.' + path[-1] |
|
1261 | 1260 | info = Struct(self._ofind(oname)) |
|
1262 | 1261 | except AttributeError: pass |
|
1263 | 1262 | except AttributeError: pass |
|
1264 | 1263 | |
|
1265 | 1264 | # We return either the new info or the unmodified input if the object |
|
1266 | 1265 | # hadn't been found |
|
1267 | 1266 | return info |
|
1268 | 1267 | |
|
1269 | 1268 | def _object_find(self, oname, namespaces=None): |
|
1270 | 1269 | """Find an object and return a struct with info about it.""" |
|
1271 | 1270 | inf = Struct(self._ofind(oname, namespaces)) |
|
1272 | 1271 | return Struct(self._ofind_property(oname, inf)) |
|
1273 | 1272 | |
|
1274 | 1273 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1275 | 1274 | """Generic interface to the inspector system. |
|
1276 | 1275 | |
|
1277 | 1276 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1278 | 1277 | info = self._object_find(oname) |
|
1279 | 1278 | if info.found: |
|
1280 | 1279 | pmethod = getattr(self.inspector, meth) |
|
1281 | 1280 | formatter = format_screen if info.ismagic else None |
|
1282 | 1281 | if meth == 'pdoc': |
|
1283 | 1282 | pmethod(info.obj, oname, formatter) |
|
1284 | 1283 | elif meth == 'pinfo': |
|
1285 | 1284 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1286 | 1285 | else: |
|
1287 | 1286 | pmethod(info.obj, oname) |
|
1288 | 1287 | else: |
|
1289 | 1288 | print 'Object `%s` not found.' % oname |
|
1290 | 1289 | return 'not found' # so callers can take other action |
|
1291 | 1290 | |
|
1292 | 1291 | def object_inspect(self, oname): |
|
1293 | 1292 | with self.builtin_trap: |
|
1294 | 1293 | info = self._object_find(oname) |
|
1295 | 1294 | if info.found: |
|
1296 | 1295 | return self.inspector.info(info.obj, oname, info=info) |
|
1297 | 1296 | else: |
|
1298 | 1297 | return oinspect.object_info(name=oname, found=False) |
|
1299 | 1298 | |
|
1300 | 1299 | #------------------------------------------------------------------------- |
|
1301 | 1300 | # Things related to history management |
|
1302 | 1301 | #------------------------------------------------------------------------- |
|
1303 | 1302 | |
|
1304 | 1303 | def init_history(self): |
|
1305 | 1304 | """Sets up the command history, and starts regular autosaves.""" |
|
1306 | 1305 | self.history_manager = HistoryManager(shell=self, config=self.config) |
|
1307 | 1306 | |
|
1308 | 1307 | #------------------------------------------------------------------------- |
|
1309 | 1308 | # Things related to exception handling and tracebacks (not debugging) |
|
1310 | 1309 | #------------------------------------------------------------------------- |
|
1311 | 1310 | |
|
1312 | 1311 | def init_traceback_handlers(self, custom_exceptions): |
|
1313 | 1312 | # Syntax error handler. |
|
1314 | 1313 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1315 | 1314 | |
|
1316 | 1315 | # The interactive one is initialized with an offset, meaning we always |
|
1317 | 1316 | # want to remove the topmost item in the traceback, which is our own |
|
1318 | 1317 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1319 | 1318 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1320 | 1319 | color_scheme='NoColor', |
|
1321 | 1320 | tb_offset = 1, |
|
1322 | 1321 | check_cache=self.compile.check_cache) |
|
1323 | 1322 | |
|
1324 | 1323 | # The instance will store a pointer to the system-wide exception hook, |
|
1325 | 1324 | # so that runtime code (such as magics) can access it. This is because |
|
1326 | 1325 | # during the read-eval loop, it may get temporarily overwritten. |
|
1327 | 1326 | self.sys_excepthook = sys.excepthook |
|
1328 | 1327 | |
|
1329 | 1328 | # and add any custom exception handlers the user may have specified |
|
1330 | 1329 | self.set_custom_exc(*custom_exceptions) |
|
1331 | 1330 | |
|
1332 | 1331 | # Set the exception mode |
|
1333 | 1332 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1334 | 1333 | |
|
1335 | 1334 | def set_custom_exc(self, exc_tuple, handler): |
|
1336 | 1335 | """set_custom_exc(exc_tuple,handler) |
|
1337 | 1336 | |
|
1338 | 1337 | Set a custom exception handler, which will be called if any of the |
|
1339 | 1338 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1340 | 1339 | run_code() method. |
|
1341 | 1340 | |
|
1342 | 1341 | Inputs: |
|
1343 | 1342 | |
|
1344 | 1343 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1345 | 1344 | handler for. It is very important that you use a tuple, and NOT A |
|
1346 | 1345 | LIST here, because of the way Python's except statement works. If |
|
1347 | 1346 | you only want to trap a single exception, use a singleton tuple: |
|
1348 | 1347 | |
|
1349 | 1348 | exc_tuple == (MyCustomException,) |
|
1350 | 1349 | |
|
1351 | 1350 | - handler: this must be defined as a function with the following |
|
1352 | 1351 | basic interface:: |
|
1353 | 1352 | |
|
1354 | 1353 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1355 | 1354 | ... |
|
1356 | 1355 | # The return value must be |
|
1357 | 1356 | return structured_traceback |
|
1358 | 1357 | |
|
1359 | 1358 | This will be made into an instance method (via types.MethodType) |
|
1360 | 1359 | of IPython itself, and it will be called if any of the exceptions |
|
1361 | 1360 | listed in the exc_tuple are caught. If the handler is None, an |
|
1362 | 1361 | internal basic one is used, which just prints basic info. |
|
1363 | 1362 | |
|
1364 | 1363 | WARNING: by putting in your own exception handler into IPython's main |
|
1365 | 1364 | execution loop, you run a very good chance of nasty crashes. This |
|
1366 | 1365 | facility should only be used if you really know what you are doing.""" |
|
1367 | 1366 | |
|
1368 | 1367 | assert type(exc_tuple)==type(()) , \ |
|
1369 | 1368 | "The custom exceptions must be given AS A TUPLE." |
|
1370 | 1369 | |
|
1371 | 1370 | def dummy_handler(self,etype,value,tb): |
|
1372 | 1371 | print '*** Simple custom exception handler ***' |
|
1373 | 1372 | print 'Exception type :',etype |
|
1374 | 1373 | print 'Exception value:',value |
|
1375 | 1374 | print 'Traceback :',tb |
|
1376 | 1375 | #print 'Source code :','\n'.join(self.buffer) |
|
1377 | 1376 | |
|
1378 | 1377 | if handler is None: handler = dummy_handler |
|
1379 | 1378 | |
|
1380 | 1379 | self.CustomTB = types.MethodType(handler,self) |
|
1381 | 1380 | self.custom_exceptions = exc_tuple |
|
1382 | 1381 | |
|
1383 | 1382 | def excepthook(self, etype, value, tb): |
|
1384 | 1383 | """One more defense for GUI apps that call sys.excepthook. |
|
1385 | 1384 | |
|
1386 | 1385 | GUI frameworks like wxPython trap exceptions and call |
|
1387 | 1386 | sys.excepthook themselves. I guess this is a feature that |
|
1388 | 1387 | enables them to keep running after exceptions that would |
|
1389 | 1388 | otherwise kill their mainloop. This is a bother for IPython |
|
1390 | 1389 | which excepts to catch all of the program exceptions with a try: |
|
1391 | 1390 | except: statement. |
|
1392 | 1391 | |
|
1393 | 1392 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1394 | 1393 | any app directly invokes sys.excepthook, it will look to the user like |
|
1395 | 1394 | IPython crashed. In order to work around this, we can disable the |
|
1396 | 1395 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1397 | 1396 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1398 | 1397 | call sys.excepthook will generate a regular-looking exception from |
|
1399 | 1398 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1400 | 1399 | crashes. |
|
1401 | 1400 | |
|
1402 | 1401 | This hook should be used sparingly, only in places which are not likely |
|
1403 | 1402 | to be true IPython errors. |
|
1404 | 1403 | """ |
|
1405 | 1404 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1406 | 1405 | |
|
1407 | 1406 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1408 | 1407 | exception_only=False): |
|
1409 | 1408 | """Display the exception that just occurred. |
|
1410 | 1409 | |
|
1411 | 1410 | If nothing is known about the exception, this is the method which |
|
1412 | 1411 | should be used throughout the code for presenting user tracebacks, |
|
1413 | 1412 | rather than directly invoking the InteractiveTB object. |
|
1414 | 1413 | |
|
1415 | 1414 | A specific showsyntaxerror() also exists, but this method can take |
|
1416 | 1415 | care of calling it if needed, so unless you are explicitly catching a |
|
1417 | 1416 | SyntaxError exception, don't try to analyze the stack manually and |
|
1418 | 1417 | simply call this method.""" |
|
1419 | 1418 | |
|
1420 | 1419 | try: |
|
1421 | 1420 | if exc_tuple is None: |
|
1422 | 1421 | etype, value, tb = sys.exc_info() |
|
1423 | 1422 | else: |
|
1424 | 1423 | etype, value, tb = exc_tuple |
|
1425 | 1424 | |
|
1426 | 1425 | if etype is None: |
|
1427 | 1426 | if hasattr(sys, 'last_type'): |
|
1428 | 1427 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1429 | 1428 | sys.last_traceback |
|
1430 | 1429 | else: |
|
1431 | 1430 | self.write_err('No traceback available to show.\n') |
|
1432 | 1431 | return |
|
1433 | 1432 | |
|
1434 | 1433 | if etype is SyntaxError: |
|
1435 | 1434 | # Though this won't be called by syntax errors in the input |
|
1436 | 1435 | # line, there may be SyntaxError cases whith imported code. |
|
1437 | 1436 | self.showsyntaxerror(filename) |
|
1438 | 1437 | elif etype is UsageError: |
|
1439 | 1438 | print "UsageError:", value |
|
1440 | 1439 | else: |
|
1441 | 1440 | # WARNING: these variables are somewhat deprecated and not |
|
1442 | 1441 | # necessarily safe to use in a threaded environment, but tools |
|
1443 | 1442 | # like pdb depend on their existence, so let's set them. If we |
|
1444 | 1443 | # find problems in the field, we'll need to revisit their use. |
|
1445 | 1444 | sys.last_type = etype |
|
1446 | 1445 | sys.last_value = value |
|
1447 | 1446 | sys.last_traceback = tb |
|
1448 | 1447 | if etype in self.custom_exceptions: |
|
1449 | 1448 | # FIXME: Old custom traceback objects may just return a |
|
1450 | 1449 | # string, in that case we just put it into a list |
|
1451 | 1450 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1452 | 1451 | if isinstance(ctb, basestring): |
|
1453 | 1452 | stb = [stb] |
|
1454 | 1453 | else: |
|
1455 | 1454 | if exception_only: |
|
1456 | 1455 | stb = ['An exception has occurred, use %tb to see ' |
|
1457 | 1456 | 'the full traceback.\n'] |
|
1458 | 1457 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1459 | 1458 | value)) |
|
1460 | 1459 | else: |
|
1461 | 1460 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1462 | 1461 | value, tb, tb_offset=tb_offset) |
|
1463 | 1462 | |
|
1464 | 1463 | if self.call_pdb: |
|
1465 | 1464 | # drop into debugger |
|
1466 | 1465 | self.debugger(force=True) |
|
1467 | 1466 | |
|
1468 | 1467 | # Actually show the traceback |
|
1469 | 1468 | self._showtraceback(etype, value, stb) |
|
1470 | 1469 | |
|
1471 | 1470 | except KeyboardInterrupt: |
|
1472 | 1471 | self.write_err("\nKeyboardInterrupt\n") |
|
1473 | 1472 | |
|
1474 | 1473 | def _showtraceback(self, etype, evalue, stb): |
|
1475 | 1474 | """Actually show a traceback. |
|
1476 | 1475 | |
|
1477 | 1476 | Subclasses may override this method to put the traceback on a different |
|
1478 | 1477 | place, like a side channel. |
|
1479 | 1478 | """ |
|
1480 |
print >> io. |
|
|
1479 | print >> io.stdout, self.InteractiveTB.stb2text(stb) | |
|
1481 | 1480 | |
|
1482 | 1481 | def showsyntaxerror(self, filename=None): |
|
1483 | 1482 | """Display the syntax error that just occurred. |
|
1484 | 1483 | |
|
1485 | 1484 | This doesn't display a stack trace because there isn't one. |
|
1486 | 1485 | |
|
1487 | 1486 | If a filename is given, it is stuffed in the exception instead |
|
1488 | 1487 | of what was there before (because Python's parser always uses |
|
1489 | 1488 | "<string>" when reading from a string). |
|
1490 | 1489 | """ |
|
1491 | 1490 | etype, value, last_traceback = sys.exc_info() |
|
1492 | 1491 | |
|
1493 | 1492 | # See note about these variables in showtraceback() above |
|
1494 | 1493 | sys.last_type = etype |
|
1495 | 1494 | sys.last_value = value |
|
1496 | 1495 | sys.last_traceback = last_traceback |
|
1497 | 1496 | |
|
1498 | 1497 | if filename and etype is SyntaxError: |
|
1499 | 1498 | # Work hard to stuff the correct filename in the exception |
|
1500 | 1499 | try: |
|
1501 | 1500 | msg, (dummy_filename, lineno, offset, line) = value |
|
1502 | 1501 | except: |
|
1503 | 1502 | # Not the format we expect; leave it alone |
|
1504 | 1503 | pass |
|
1505 | 1504 | else: |
|
1506 | 1505 | # Stuff in the right filename |
|
1507 | 1506 | try: |
|
1508 | 1507 | # Assume SyntaxError is a class exception |
|
1509 | 1508 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1510 | 1509 | except: |
|
1511 | 1510 | # If that failed, assume SyntaxError is a string |
|
1512 | 1511 | value = msg, (filename, lineno, offset, line) |
|
1513 | 1512 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1514 | 1513 | self._showtraceback(etype, value, stb) |
|
1515 | 1514 | |
|
1516 | 1515 | #------------------------------------------------------------------------- |
|
1517 | 1516 | # Things related to readline |
|
1518 | 1517 | #------------------------------------------------------------------------- |
|
1519 | 1518 | |
|
1520 | 1519 | def init_readline(self): |
|
1521 | 1520 | """Command history completion/saving/reloading.""" |
|
1522 | 1521 | |
|
1523 | 1522 | if self.readline_use: |
|
1524 | 1523 | import IPython.utils.rlineimpl as readline |
|
1525 | 1524 | |
|
1526 | 1525 | self.rl_next_input = None |
|
1527 | 1526 | self.rl_do_indent = False |
|
1528 | 1527 | |
|
1529 | 1528 | if not self.readline_use or not readline.have_readline: |
|
1530 | 1529 | self.has_readline = False |
|
1531 | 1530 | self.readline = None |
|
1532 | 1531 | # Set a number of methods that depend on readline to be no-op |
|
1533 | 1532 | self.set_readline_completer = no_op |
|
1534 | 1533 | self.set_custom_completer = no_op |
|
1535 | 1534 | self.set_completer_frame = no_op |
|
1536 | 1535 | warn('Readline services not available or not loaded.') |
|
1537 | 1536 | else: |
|
1538 | 1537 | self.has_readline = True |
|
1539 | 1538 | self.readline = readline |
|
1540 | 1539 | sys.modules['readline'] = readline |
|
1541 | 1540 | |
|
1542 | 1541 | # Platform-specific configuration |
|
1543 | 1542 | if os.name == 'nt': |
|
1544 | 1543 | # FIXME - check with Frederick to see if we can harmonize |
|
1545 | 1544 | # naming conventions with pyreadline to avoid this |
|
1546 | 1545 | # platform-dependent check |
|
1547 | 1546 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1548 | 1547 | else: |
|
1549 | 1548 | self.readline_startup_hook = readline.set_startup_hook |
|
1550 | 1549 | |
|
1551 | 1550 | # Load user's initrc file (readline config) |
|
1552 | 1551 | # Or if libedit is used, load editrc. |
|
1553 | 1552 | inputrc_name = os.environ.get('INPUTRC') |
|
1554 | 1553 | if inputrc_name is None: |
|
1555 | 1554 | home_dir = get_home_dir() |
|
1556 | 1555 | if home_dir is not None: |
|
1557 | 1556 | inputrc_name = '.inputrc' |
|
1558 | 1557 | if readline.uses_libedit: |
|
1559 | 1558 | inputrc_name = '.editrc' |
|
1560 | 1559 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1561 | 1560 | if os.path.isfile(inputrc_name): |
|
1562 | 1561 | try: |
|
1563 | 1562 | readline.read_init_file(inputrc_name) |
|
1564 | 1563 | except: |
|
1565 | 1564 | warn('Problems reading readline initialization file <%s>' |
|
1566 | 1565 | % inputrc_name) |
|
1567 | 1566 | |
|
1568 | 1567 | # Configure readline according to user's prefs |
|
1569 | 1568 | # This is only done if GNU readline is being used. If libedit |
|
1570 | 1569 | # is being used (as on Leopard) the readline config is |
|
1571 | 1570 | # not run as the syntax for libedit is different. |
|
1572 | 1571 | if not readline.uses_libedit: |
|
1573 | 1572 | for rlcommand in self.readline_parse_and_bind: |
|
1574 | 1573 | #print "loading rl:",rlcommand # dbg |
|
1575 | 1574 | readline.parse_and_bind(rlcommand) |
|
1576 | 1575 | |
|
1577 | 1576 | # Remove some chars from the delimiters list. If we encounter |
|
1578 | 1577 | # unicode chars, discard them. |
|
1579 | 1578 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1580 | 1579 | delims = delims.translate(None, self.readline_remove_delims) |
|
1581 | 1580 | delims = delims.replace(ESC_MAGIC, '') |
|
1582 | 1581 | readline.set_completer_delims(delims) |
|
1583 | 1582 | # otherwise we end up with a monster history after a while: |
|
1584 | 1583 | readline.set_history_length(self.history_length) |
|
1585 | 1584 | |
|
1586 | 1585 | self.refill_readline_hist() |
|
1587 | 1586 | self.readline_no_record = ReadlineNoRecord(self) |
|
1588 | 1587 | |
|
1589 | 1588 | # Configure auto-indent for all platforms |
|
1590 | 1589 | self.set_autoindent(self.autoindent) |
|
1591 | 1590 | |
|
1592 | 1591 | def refill_readline_hist(self): |
|
1593 | 1592 | # Load the last 1000 lines from history |
|
1594 | 1593 | self.readline.clear_history() |
|
1595 | 1594 | stdin_encoding = sys.stdin.encoding or "utf-8" |
|
1596 | 1595 | for _, _, cell in self.history_manager.get_tail(1000, |
|
1597 | 1596 | include_latest=True): |
|
1598 | 1597 | if cell.strip(): # Ignore blank lines |
|
1599 | 1598 | for line in cell.splitlines(): |
|
1600 | 1599 | self.readline.add_history(line.encode(stdin_encoding)) |
|
1601 | 1600 | |
|
1602 | 1601 | def set_next_input(self, s): |
|
1603 | 1602 | """ Sets the 'default' input string for the next command line. |
|
1604 | 1603 | |
|
1605 | 1604 | Requires readline. |
|
1606 | 1605 | |
|
1607 | 1606 | Example: |
|
1608 | 1607 | |
|
1609 | 1608 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1610 | 1609 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1611 | 1610 | """ |
|
1612 | 1611 | |
|
1613 | 1612 | self.rl_next_input = s |
|
1614 | 1613 | |
|
1615 | 1614 | # Maybe move this to the terminal subclass? |
|
1616 | 1615 | def pre_readline(self): |
|
1617 | 1616 | """readline hook to be used at the start of each line. |
|
1618 | 1617 | |
|
1619 | 1618 | Currently it handles auto-indent only.""" |
|
1620 | 1619 | |
|
1621 | 1620 | if self.rl_do_indent: |
|
1622 | 1621 | self.readline.insert_text(self._indent_current_str()) |
|
1623 | 1622 | if self.rl_next_input is not None: |
|
1624 | 1623 | self.readline.insert_text(self.rl_next_input) |
|
1625 | 1624 | self.rl_next_input = None |
|
1626 | 1625 | |
|
1627 | 1626 | def _indent_current_str(self): |
|
1628 | 1627 | """return the current level of indentation as a string""" |
|
1629 | 1628 | return self.input_splitter.indent_spaces * ' ' |
|
1630 | 1629 | |
|
1631 | 1630 | #------------------------------------------------------------------------- |
|
1632 | 1631 | # Things related to text completion |
|
1633 | 1632 | #------------------------------------------------------------------------- |
|
1634 | 1633 | |
|
1635 | 1634 | def init_completer(self): |
|
1636 | 1635 | """Initialize the completion machinery. |
|
1637 | 1636 | |
|
1638 | 1637 | This creates completion machinery that can be used by client code, |
|
1639 | 1638 | either interactively in-process (typically triggered by the readline |
|
1640 | 1639 | library), programatically (such as in test suites) or out-of-prcess |
|
1641 | 1640 | (typically over the network by remote frontends). |
|
1642 | 1641 | """ |
|
1643 | 1642 | from IPython.core.completer import IPCompleter |
|
1644 | 1643 | from IPython.core.completerlib import (module_completer, |
|
1645 | 1644 | magic_run_completer, cd_completer) |
|
1646 | 1645 | |
|
1647 | 1646 | self.Completer = IPCompleter(self, |
|
1648 | 1647 | self.user_ns, |
|
1649 | 1648 | self.user_global_ns, |
|
1650 | 1649 | self.readline_omit__names, |
|
1651 | 1650 | self.alias_manager.alias_table, |
|
1652 | 1651 | self.has_readline) |
|
1653 | 1652 | |
|
1654 | 1653 | # Add custom completers to the basic ones built into IPCompleter |
|
1655 | 1654 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1656 | 1655 | self.strdispatchers['complete_command'] = sdisp |
|
1657 | 1656 | self.Completer.custom_completers = sdisp |
|
1658 | 1657 | |
|
1659 | 1658 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1660 | 1659 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1661 | 1660 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1662 | 1661 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1663 | 1662 | |
|
1664 | 1663 | # Only configure readline if we truly are using readline. IPython can |
|
1665 | 1664 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1666 | 1665 | # itself may be absent |
|
1667 | 1666 | if self.has_readline: |
|
1668 | 1667 | self.set_readline_completer() |
|
1669 | 1668 | |
|
1670 | 1669 | def complete(self, text, line=None, cursor_pos=None): |
|
1671 | 1670 | """Return the completed text and a list of completions. |
|
1672 | 1671 | |
|
1673 | 1672 | Parameters |
|
1674 | 1673 | ---------- |
|
1675 | 1674 | |
|
1676 | 1675 | text : string |
|
1677 | 1676 | A string of text to be completed on. It can be given as empty and |
|
1678 | 1677 | instead a line/position pair are given. In this case, the |
|
1679 | 1678 | completer itself will split the line like readline does. |
|
1680 | 1679 | |
|
1681 | 1680 | line : string, optional |
|
1682 | 1681 | The complete line that text is part of. |
|
1683 | 1682 | |
|
1684 | 1683 | cursor_pos : int, optional |
|
1685 | 1684 | The position of the cursor on the input line. |
|
1686 | 1685 | |
|
1687 | 1686 | Returns |
|
1688 | 1687 | ------- |
|
1689 | 1688 | text : string |
|
1690 | 1689 | The actual text that was completed. |
|
1691 | 1690 | |
|
1692 | 1691 | matches : list |
|
1693 | 1692 | A sorted list with all possible completions. |
|
1694 | 1693 | |
|
1695 | 1694 | The optional arguments allow the completion to take more context into |
|
1696 | 1695 | account, and are part of the low-level completion API. |
|
1697 | 1696 | |
|
1698 | 1697 | This is a wrapper around the completion mechanism, similar to what |
|
1699 | 1698 | readline does at the command line when the TAB key is hit. By |
|
1700 | 1699 | exposing it as a method, it can be used by other non-readline |
|
1701 | 1700 | environments (such as GUIs) for text completion. |
|
1702 | 1701 | |
|
1703 | 1702 | Simple usage example: |
|
1704 | 1703 | |
|
1705 | 1704 | In [1]: x = 'hello' |
|
1706 | 1705 | |
|
1707 | 1706 | In [2]: _ip.complete('x.l') |
|
1708 | 1707 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1709 | 1708 | """ |
|
1710 | 1709 | |
|
1711 | 1710 | # Inject names into __builtin__ so we can complete on the added names. |
|
1712 | 1711 | with self.builtin_trap: |
|
1713 | 1712 | return self.Completer.complete(text, line, cursor_pos) |
|
1714 | 1713 | |
|
1715 | 1714 | def set_custom_completer(self, completer, pos=0): |
|
1716 | 1715 | """Adds a new custom completer function. |
|
1717 | 1716 | |
|
1718 | 1717 | The position argument (defaults to 0) is the index in the completers |
|
1719 | 1718 | list where you want the completer to be inserted.""" |
|
1720 | 1719 | |
|
1721 | 1720 | newcomp = types.MethodType(completer,self.Completer) |
|
1722 | 1721 | self.Completer.matchers.insert(pos,newcomp) |
|
1723 | 1722 | |
|
1724 | 1723 | def set_readline_completer(self): |
|
1725 | 1724 | """Reset readline's completer to be our own.""" |
|
1726 | 1725 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1727 | 1726 | |
|
1728 | 1727 | def set_completer_frame(self, frame=None): |
|
1729 | 1728 | """Set the frame of the completer.""" |
|
1730 | 1729 | if frame: |
|
1731 | 1730 | self.Completer.namespace = frame.f_locals |
|
1732 | 1731 | self.Completer.global_namespace = frame.f_globals |
|
1733 | 1732 | else: |
|
1734 | 1733 | self.Completer.namespace = self.user_ns |
|
1735 | 1734 | self.Completer.global_namespace = self.user_global_ns |
|
1736 | 1735 | |
|
1737 | 1736 | #------------------------------------------------------------------------- |
|
1738 | 1737 | # Things related to magics |
|
1739 | 1738 | #------------------------------------------------------------------------- |
|
1740 | 1739 | |
|
1741 | 1740 | def init_magics(self): |
|
1742 | 1741 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1743 | 1742 | # should be split into a prompt manager and displayhook. We probably |
|
1744 | 1743 | # even need a centralize colors management object. |
|
1745 | 1744 | self.magic_colors(self.colors) |
|
1746 | 1745 | # History was moved to a separate module |
|
1747 | 1746 | from . import history |
|
1748 | 1747 | history.init_ipython(self) |
|
1749 | 1748 | |
|
1750 | 1749 | def magic(self,arg_s): |
|
1751 | 1750 | """Call a magic function by name. |
|
1752 | 1751 | |
|
1753 | 1752 | Input: a string containing the name of the magic function to call and |
|
1754 | 1753 | any additional arguments to be passed to the magic. |
|
1755 | 1754 | |
|
1756 | 1755 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1757 | 1756 | prompt: |
|
1758 | 1757 | |
|
1759 | 1758 | In[1]: %name -opt foo bar |
|
1760 | 1759 | |
|
1761 | 1760 | To call a magic without arguments, simply use magic('name'). |
|
1762 | 1761 | |
|
1763 | 1762 | This provides a proper Python function to call IPython's magics in any |
|
1764 | 1763 | valid Python code you can type at the interpreter, including loops and |
|
1765 | 1764 | compound statements. |
|
1766 | 1765 | """ |
|
1767 | 1766 | args = arg_s.split(' ',1) |
|
1768 | 1767 | magic_name = args[0] |
|
1769 | 1768 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1770 | 1769 | |
|
1771 | 1770 | try: |
|
1772 | 1771 | magic_args = args[1] |
|
1773 | 1772 | except IndexError: |
|
1774 | 1773 | magic_args = '' |
|
1775 | 1774 | fn = getattr(self,'magic_'+magic_name,None) |
|
1776 | 1775 | if fn is None: |
|
1777 | 1776 | error("Magic function `%s` not found." % magic_name) |
|
1778 | 1777 | else: |
|
1779 | 1778 | magic_args = self.var_expand(magic_args,1) |
|
1780 | 1779 | # Grab local namespace if we need it: |
|
1781 | 1780 | if getattr(fn, "needs_local_scope", False): |
|
1782 | 1781 | self._magic_locals = sys._getframe(1).f_locals |
|
1783 | 1782 | with self.builtin_trap: |
|
1784 | 1783 | result = fn(magic_args) |
|
1785 | 1784 | # Ensure we're not keeping object references around: |
|
1786 | 1785 | self._magic_locals = {} |
|
1787 | 1786 | return result |
|
1788 | 1787 | |
|
1789 | 1788 | def define_magic(self, magicname, func): |
|
1790 | 1789 | """Expose own function as magic function for ipython |
|
1791 | 1790 | |
|
1792 | 1791 | def foo_impl(self,parameter_s=''): |
|
1793 | 1792 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1794 | 1793 | print 'Magic function. Passed parameter is between < >:' |
|
1795 | 1794 | print '<%s>' % parameter_s |
|
1796 | 1795 | print 'The self object is:',self |
|
1797 | 1796 | |
|
1798 | 1797 | self.define_magic('foo',foo_impl) |
|
1799 | 1798 | """ |
|
1800 | 1799 | |
|
1801 | 1800 | import new |
|
1802 | 1801 | im = types.MethodType(func,self) |
|
1803 | 1802 | old = getattr(self, "magic_" + magicname, None) |
|
1804 | 1803 | setattr(self, "magic_" + magicname, im) |
|
1805 | 1804 | return old |
|
1806 | 1805 | |
|
1807 | 1806 | #------------------------------------------------------------------------- |
|
1808 | 1807 | # Things related to macros |
|
1809 | 1808 | #------------------------------------------------------------------------- |
|
1810 | 1809 | |
|
1811 | 1810 | def define_macro(self, name, themacro): |
|
1812 | 1811 | """Define a new macro |
|
1813 | 1812 | |
|
1814 | 1813 | Parameters |
|
1815 | 1814 | ---------- |
|
1816 | 1815 | name : str |
|
1817 | 1816 | The name of the macro. |
|
1818 | 1817 | themacro : str or Macro |
|
1819 | 1818 | The action to do upon invoking the macro. If a string, a new |
|
1820 | 1819 | Macro object is created by passing the string to it. |
|
1821 | 1820 | """ |
|
1822 | 1821 | |
|
1823 | 1822 | from IPython.core import macro |
|
1824 | 1823 | |
|
1825 | 1824 | if isinstance(themacro, basestring): |
|
1826 | 1825 | themacro = macro.Macro(themacro) |
|
1827 | 1826 | if not isinstance(themacro, macro.Macro): |
|
1828 | 1827 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1829 | 1828 | self.user_ns[name] = themacro |
|
1830 | 1829 | |
|
1831 | 1830 | #------------------------------------------------------------------------- |
|
1832 | 1831 | # Things related to the running of system commands |
|
1833 | 1832 | #------------------------------------------------------------------------- |
|
1834 | 1833 | |
|
1835 | 1834 | def system(self, cmd): |
|
1836 | 1835 | """Call the given cmd in a subprocess. |
|
1837 | 1836 | |
|
1838 | 1837 | Parameters |
|
1839 | 1838 | ---------- |
|
1840 | 1839 | cmd : str |
|
1841 | 1840 | Command to execute (can not end in '&', as bacground processes are |
|
1842 | 1841 | not supported. |
|
1843 | 1842 | """ |
|
1844 | 1843 | # We do not support backgrounding processes because we either use |
|
1845 | 1844 | # pexpect or pipes to read from. Users can always just call |
|
1846 | 1845 | # os.system() if they really want a background process. |
|
1847 | 1846 | if cmd.endswith('&'): |
|
1848 | 1847 | raise OSError("Background processes not supported.") |
|
1849 | 1848 | |
|
1850 | 1849 | return system(self.var_expand(cmd, depth=2)) |
|
1851 | 1850 | |
|
1852 | 1851 | def getoutput(self, cmd, split=True): |
|
1853 | 1852 | """Get output (possibly including stderr) from a subprocess. |
|
1854 | 1853 | |
|
1855 | 1854 | Parameters |
|
1856 | 1855 | ---------- |
|
1857 | 1856 | cmd : str |
|
1858 | 1857 | Command to execute (can not end in '&', as background processes are |
|
1859 | 1858 | not supported. |
|
1860 | 1859 | split : bool, optional |
|
1861 | 1860 | |
|
1862 | 1861 | If True, split the output into an IPython SList. Otherwise, an |
|
1863 | 1862 | IPython LSString is returned. These are objects similar to normal |
|
1864 | 1863 | lists and strings, with a few convenience attributes for easier |
|
1865 | 1864 | manipulation of line-based output. You can use '?' on them for |
|
1866 | 1865 | details. |
|
1867 | 1866 | """ |
|
1868 | 1867 | if cmd.endswith('&'): |
|
1869 | 1868 | raise OSError("Background processes not supported.") |
|
1870 | 1869 | out = getoutput(self.var_expand(cmd, depth=2)) |
|
1871 | 1870 | if split: |
|
1872 | 1871 | out = SList(out.splitlines()) |
|
1873 | 1872 | else: |
|
1874 | 1873 | out = LSString(out) |
|
1875 | 1874 | return out |
|
1876 | 1875 | |
|
1877 | 1876 | #------------------------------------------------------------------------- |
|
1878 | 1877 | # Things related to aliases |
|
1879 | 1878 | #------------------------------------------------------------------------- |
|
1880 | 1879 | |
|
1881 | 1880 | def init_alias(self): |
|
1882 | 1881 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1883 | 1882 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1884 | 1883 | |
|
1885 | 1884 | #------------------------------------------------------------------------- |
|
1886 | 1885 | # Things related to extensions and plugins |
|
1887 | 1886 | #------------------------------------------------------------------------- |
|
1888 | 1887 | |
|
1889 | 1888 | def init_extension_manager(self): |
|
1890 | 1889 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1891 | 1890 | |
|
1892 | 1891 | def init_plugin_manager(self): |
|
1893 | 1892 | self.plugin_manager = PluginManager(config=self.config) |
|
1894 | 1893 | |
|
1895 | 1894 | #------------------------------------------------------------------------- |
|
1896 | 1895 | # Things related to payloads |
|
1897 | 1896 | #------------------------------------------------------------------------- |
|
1898 | 1897 | |
|
1899 | 1898 | def init_payload(self): |
|
1900 | 1899 | self.payload_manager = PayloadManager(config=self.config) |
|
1901 | 1900 | |
|
1902 | 1901 | #------------------------------------------------------------------------- |
|
1903 | 1902 | # Things related to the prefilter |
|
1904 | 1903 | #------------------------------------------------------------------------- |
|
1905 | 1904 | |
|
1906 | 1905 | def init_prefilter(self): |
|
1907 | 1906 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1908 | 1907 | # Ultimately this will be refactored in the new interpreter code, but |
|
1909 | 1908 | # for now, we should expose the main prefilter method (there's legacy |
|
1910 | 1909 | # code out there that may rely on this). |
|
1911 | 1910 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1912 | 1911 | |
|
1913 | 1912 | def auto_rewrite_input(self, cmd): |
|
1914 | 1913 | """Print to the screen the rewritten form of the user's command. |
|
1915 | 1914 | |
|
1916 | 1915 | This shows visual feedback by rewriting input lines that cause |
|
1917 | 1916 | automatic calling to kick in, like:: |
|
1918 | 1917 | |
|
1919 | 1918 | /f x |
|
1920 | 1919 | |
|
1921 | 1920 | into:: |
|
1922 | 1921 | |
|
1923 | 1922 | ------> f(x) |
|
1924 | 1923 | |
|
1925 | 1924 | after the user's input prompt. This helps the user understand that the |
|
1926 | 1925 | input line was transformed automatically by IPython. |
|
1927 | 1926 | """ |
|
1928 | 1927 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1929 | 1928 | |
|
1930 | 1929 | try: |
|
1931 | 1930 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1932 | 1931 | # we use it and only print uncolored rewrite if we have unicode |
|
1933 | 1932 | rw = str(rw) |
|
1934 |
print >> |
|
|
1933 | print >> io.stdout, rw | |
|
1935 | 1934 | except UnicodeEncodeError: |
|
1936 | 1935 | print "------> " + cmd |
|
1937 | 1936 | |
|
1938 | 1937 | #------------------------------------------------------------------------- |
|
1939 | 1938 | # Things related to extracting values/expressions from kernel and user_ns |
|
1940 | 1939 | #------------------------------------------------------------------------- |
|
1941 | 1940 | |
|
1942 | 1941 | def _simple_error(self): |
|
1943 | 1942 | etype, value = sys.exc_info()[:2] |
|
1944 | 1943 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1945 | 1944 | |
|
1946 | 1945 | def user_variables(self, names): |
|
1947 | 1946 | """Get a list of variable names from the user's namespace. |
|
1948 | 1947 | |
|
1949 | 1948 | Parameters |
|
1950 | 1949 | ---------- |
|
1951 | 1950 | names : list of strings |
|
1952 | 1951 | A list of names of variables to be read from the user namespace. |
|
1953 | 1952 | |
|
1954 | 1953 | Returns |
|
1955 | 1954 | ------- |
|
1956 | 1955 | A dict, keyed by the input names and with the repr() of each value. |
|
1957 | 1956 | """ |
|
1958 | 1957 | out = {} |
|
1959 | 1958 | user_ns = self.user_ns |
|
1960 | 1959 | for varname in names: |
|
1961 | 1960 | try: |
|
1962 | 1961 | value = repr(user_ns[varname]) |
|
1963 | 1962 | except: |
|
1964 | 1963 | value = self._simple_error() |
|
1965 | 1964 | out[varname] = value |
|
1966 | 1965 | return out |
|
1967 | 1966 | |
|
1968 | 1967 | def user_expressions(self, expressions): |
|
1969 | 1968 | """Evaluate a dict of expressions in the user's namespace. |
|
1970 | 1969 | |
|
1971 | 1970 | Parameters |
|
1972 | 1971 | ---------- |
|
1973 | 1972 | expressions : dict |
|
1974 | 1973 | A dict with string keys and string values. The expression values |
|
1975 | 1974 | should be valid Python expressions, each of which will be evaluated |
|
1976 | 1975 | in the user namespace. |
|
1977 | 1976 | |
|
1978 | 1977 | Returns |
|
1979 | 1978 | ------- |
|
1980 | 1979 | A dict, keyed like the input expressions dict, with the repr() of each |
|
1981 | 1980 | value. |
|
1982 | 1981 | """ |
|
1983 | 1982 | out = {} |
|
1984 | 1983 | user_ns = self.user_ns |
|
1985 | 1984 | global_ns = self.user_global_ns |
|
1986 | 1985 | for key, expr in expressions.iteritems(): |
|
1987 | 1986 | try: |
|
1988 | 1987 | value = repr(eval(expr, global_ns, user_ns)) |
|
1989 | 1988 | except: |
|
1990 | 1989 | value = self._simple_error() |
|
1991 | 1990 | out[key] = value |
|
1992 | 1991 | return out |
|
1993 | 1992 | |
|
1994 | 1993 | #------------------------------------------------------------------------- |
|
1995 | 1994 | # Things related to the running of code |
|
1996 | 1995 | #------------------------------------------------------------------------- |
|
1997 | 1996 | |
|
1998 | 1997 | def ex(self, cmd): |
|
1999 | 1998 | """Execute a normal python statement in user namespace.""" |
|
2000 | 1999 | with self.builtin_trap: |
|
2001 | 2000 | exec cmd in self.user_global_ns, self.user_ns |
|
2002 | 2001 | |
|
2003 | 2002 | def ev(self, expr): |
|
2004 | 2003 | """Evaluate python expression expr in user namespace. |
|
2005 | 2004 | |
|
2006 | 2005 | Returns the result of evaluation |
|
2007 | 2006 | """ |
|
2008 | 2007 | with self.builtin_trap: |
|
2009 | 2008 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2010 | 2009 | |
|
2011 | 2010 | def safe_execfile(self, fname, *where, **kw): |
|
2012 | 2011 | """A safe version of the builtin execfile(). |
|
2013 | 2012 | |
|
2014 | 2013 | This version will never throw an exception, but instead print |
|
2015 | 2014 | helpful error messages to the screen. This only works on pure |
|
2016 | 2015 | Python files with the .py extension. |
|
2017 | 2016 | |
|
2018 | 2017 | Parameters |
|
2019 | 2018 | ---------- |
|
2020 | 2019 | fname : string |
|
2021 | 2020 | The name of the file to be executed. |
|
2022 | 2021 | where : tuple |
|
2023 | 2022 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2024 | 2023 | If only one is given, it is passed as both. |
|
2025 | 2024 | exit_ignore : bool (False) |
|
2026 | 2025 | If True, then silence SystemExit for non-zero status (it is always |
|
2027 | 2026 | silenced for zero status, as it is so common). |
|
2028 | 2027 | """ |
|
2029 | 2028 | kw.setdefault('exit_ignore', False) |
|
2030 | 2029 | |
|
2031 | 2030 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2032 | 2031 | # Make sure we have a .py file |
|
2033 | 2032 | if not fname.endswith('.py'): |
|
2034 | 2033 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2035 | 2034 | |
|
2036 | 2035 | # Make sure we can open the file |
|
2037 | 2036 | try: |
|
2038 | 2037 | with open(fname) as thefile: |
|
2039 | 2038 | pass |
|
2040 | 2039 | except: |
|
2041 | 2040 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2042 | 2041 | return |
|
2043 | 2042 | |
|
2044 | 2043 | # Find things also in current directory. This is needed to mimic the |
|
2045 | 2044 | # behavior of running a script from the system command line, where |
|
2046 | 2045 | # Python inserts the script's directory into sys.path |
|
2047 | 2046 | dname = os.path.dirname(fname) |
|
2048 | 2047 | |
|
2049 | 2048 | if isinstance(fname, unicode): |
|
2050 | 2049 | # execfile uses default encoding instead of filesystem encoding |
|
2051 | 2050 | # so unicode filenames will fail |
|
2052 | 2051 | fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding()) |
|
2053 | 2052 | |
|
2054 | 2053 | with prepended_to_syspath(dname): |
|
2055 | 2054 | try: |
|
2056 | 2055 | execfile(fname,*where) |
|
2057 | 2056 | except SystemExit, status: |
|
2058 | 2057 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2059 | 2058 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2060 | 2059 | # these are considered normal by the OS: |
|
2061 | 2060 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2062 | 2061 | # 0 |
|
2063 | 2062 | # > python -c'import sys;sys.exit()'; echo $? |
|
2064 | 2063 | # 0 |
|
2065 | 2064 | # For other exit status, we show the exception unless |
|
2066 | 2065 | # explicitly silenced, but only in short form. |
|
2067 | 2066 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2068 | 2067 | self.showtraceback(exception_only=True) |
|
2069 | 2068 | except: |
|
2070 | 2069 | self.showtraceback() |
|
2071 | 2070 | |
|
2072 | 2071 | def safe_execfile_ipy(self, fname): |
|
2073 | 2072 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2074 | 2073 | |
|
2075 | 2074 | Parameters |
|
2076 | 2075 | ---------- |
|
2077 | 2076 | fname : str |
|
2078 | 2077 | The name of the file to execute. The filename must have a |
|
2079 | 2078 | .ipy extension. |
|
2080 | 2079 | """ |
|
2081 | 2080 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2082 | 2081 | |
|
2083 | 2082 | # Make sure we have a .py file |
|
2084 | 2083 | if not fname.endswith('.ipy'): |
|
2085 | 2084 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2086 | 2085 | |
|
2087 | 2086 | # Make sure we can open the file |
|
2088 | 2087 | try: |
|
2089 | 2088 | with open(fname) as thefile: |
|
2090 | 2089 | pass |
|
2091 | 2090 | except: |
|
2092 | 2091 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2093 | 2092 | return |
|
2094 | 2093 | |
|
2095 | 2094 | # Find things also in current directory. This is needed to mimic the |
|
2096 | 2095 | # behavior of running a script from the system command line, where |
|
2097 | 2096 | # Python inserts the script's directory into sys.path |
|
2098 | 2097 | dname = os.path.dirname(fname) |
|
2099 | 2098 | |
|
2100 | 2099 | with prepended_to_syspath(dname): |
|
2101 | 2100 | try: |
|
2102 | 2101 | with open(fname) as thefile: |
|
2103 | 2102 | # self.run_cell currently captures all exceptions |
|
2104 | 2103 | # raised in user code. It would be nice if there were |
|
2105 | 2104 | # versions of runlines, execfile that did raise, so |
|
2106 | 2105 | # we could catch the errors. |
|
2107 | 2106 | self.run_cell(thefile.read(), store_history=False) |
|
2108 | 2107 | except: |
|
2109 | 2108 | self.showtraceback() |
|
2110 | 2109 | warn('Unknown failure executing file: <%s>' % fname) |
|
2111 | 2110 | |
|
2112 | 2111 | def run_cell(self, raw_cell, store_history=True): |
|
2113 | 2112 | """Run a complete IPython cell. |
|
2114 | 2113 | |
|
2115 | 2114 | Parameters |
|
2116 | 2115 | ---------- |
|
2117 | 2116 | raw_cell : str |
|
2118 | 2117 | The code (including IPython code such as %magic functions) to run. |
|
2119 | 2118 | store_history : bool |
|
2120 | 2119 | If True, the raw and translated cell will be stored in IPython's |
|
2121 | 2120 | history. For user code calling back into IPython's machinery, this |
|
2122 | 2121 | should be set to False. |
|
2123 | 2122 | """ |
|
2124 | 2123 | if (not raw_cell) or raw_cell.isspace(): |
|
2125 | 2124 | return |
|
2126 | 2125 | |
|
2127 | 2126 | for line in raw_cell.splitlines(): |
|
2128 | 2127 | self.input_splitter.push(line) |
|
2129 | 2128 | cell = self.input_splitter.source_reset() |
|
2130 | 2129 | |
|
2131 | 2130 | with self.builtin_trap: |
|
2132 | 2131 | if len(cell.splitlines()) == 1: |
|
2133 | 2132 | cell = self.prefilter_manager.prefilter_lines(cell) |
|
2134 | 2133 | |
|
2135 | 2134 | # Store raw and processed history |
|
2136 | 2135 | if store_history: |
|
2137 | 2136 | self.history_manager.store_inputs(self.execution_count, |
|
2138 | 2137 | cell, raw_cell) |
|
2139 | 2138 | |
|
2140 | 2139 | self.logger.log(cell, raw_cell) |
|
2141 | 2140 | |
|
2142 | 2141 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2143 | 2142 | |
|
2144 | 2143 | with self.display_trap: |
|
2145 | 2144 | try: |
|
2146 | 2145 | code_ast = ast.parse(cell, filename=cell_name) |
|
2147 | 2146 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2148 | 2147 | MemoryError): |
|
2149 | 2148 | self.showsyntaxerror() |
|
2150 | 2149 | self.execution_count += 1 |
|
2151 | 2150 | return None |
|
2152 | 2151 | |
|
2153 | 2152 | self.run_ast_nodes(code_ast.body, cell_name, |
|
2154 | 2153 | interactivity="last_expr") |
|
2155 | 2154 | |
|
2156 | 2155 | # Execute any registered post-execution functions. |
|
2157 | 2156 | for func, status in self._post_execute.iteritems(): |
|
2158 | 2157 | if not status: |
|
2159 | 2158 | continue |
|
2160 | 2159 | try: |
|
2161 | 2160 | func() |
|
2162 | 2161 | except: |
|
2163 | 2162 | self.showtraceback() |
|
2164 | 2163 | # Deactivate failing function |
|
2165 | 2164 | self._post_execute[func] = False |
|
2166 | 2165 | |
|
2167 | 2166 | if store_history: |
|
2168 | 2167 | # Write output to the database. Does nothing unless |
|
2169 | 2168 | # history output logging is enabled. |
|
2170 | 2169 | self.history_manager.store_output(self.execution_count) |
|
2171 | 2170 | # Each cell is a *single* input, regardless of how many lines it has |
|
2172 | 2171 | self.execution_count += 1 |
|
2173 | 2172 | |
|
2174 | 2173 | def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'): |
|
2175 | 2174 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2176 | 2175 | interactivity parameter. |
|
2177 | 2176 | |
|
2178 | 2177 | Parameters |
|
2179 | 2178 | ---------- |
|
2180 | 2179 | nodelist : list |
|
2181 | 2180 | A sequence of AST nodes to run. |
|
2182 | 2181 | cell_name : str |
|
2183 | 2182 | Will be passed to the compiler as the filename of the cell. Typically |
|
2184 | 2183 | the value returned by ip.compile.cache(cell). |
|
2185 | 2184 | interactivity : str |
|
2186 | 2185 | 'all', 'last', 'last_expr' or 'none', specifying which nodes should be |
|
2187 | 2186 | run interactively (displaying output from expressions). 'last_expr' |
|
2188 | 2187 | will run the last node interactively only if it is an expression (i.e. |
|
2189 | 2188 | expressions in loops or other blocks are not displayed. Other values |
|
2190 | 2189 | for this parameter will raise a ValueError. |
|
2191 | 2190 | """ |
|
2192 | 2191 | if not nodelist: |
|
2193 | 2192 | return |
|
2194 | 2193 | |
|
2195 | 2194 | if interactivity == 'last_expr': |
|
2196 | 2195 | if isinstance(nodelist[-1], ast.Expr): |
|
2197 | 2196 | interactivity = "last" |
|
2198 | 2197 | else: |
|
2199 | 2198 | interactivity = "none" |
|
2200 | 2199 | |
|
2201 | 2200 | if interactivity == 'none': |
|
2202 | 2201 | to_run_exec, to_run_interactive = nodelist, [] |
|
2203 | 2202 | elif interactivity == 'last': |
|
2204 | 2203 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2205 | 2204 | elif interactivity == 'all': |
|
2206 | 2205 | to_run_exec, to_run_interactive = [], nodelist |
|
2207 | 2206 | else: |
|
2208 | 2207 | raise ValueError("Interactivity was %r" % interactivity) |
|
2209 | 2208 | |
|
2210 | 2209 | exec_count = self.execution_count |
|
2211 | 2210 | |
|
2212 | 2211 | for i, node in enumerate(to_run_exec): |
|
2213 | 2212 | mod = ast.Module([node]) |
|
2214 | 2213 | code = self.compile(mod, cell_name, "exec") |
|
2215 | 2214 | if self.run_code(code): |
|
2216 | 2215 | return True |
|
2217 | 2216 | |
|
2218 | 2217 | for i, node in enumerate(to_run_interactive): |
|
2219 | 2218 | mod = ast.Interactive([node]) |
|
2220 | 2219 | code = self.compile(mod, cell_name, "single") |
|
2221 | 2220 | if self.run_code(code): |
|
2222 | 2221 | return True |
|
2223 | 2222 | |
|
2224 | 2223 | return False |
|
2225 | 2224 | |
|
2226 | 2225 | def run_code(self, code_obj): |
|
2227 | 2226 | """Execute a code object. |
|
2228 | 2227 | |
|
2229 | 2228 | When an exception occurs, self.showtraceback() is called to display a |
|
2230 | 2229 | traceback. |
|
2231 | 2230 | |
|
2232 | 2231 | Parameters |
|
2233 | 2232 | ---------- |
|
2234 | 2233 | code_obj : code object |
|
2235 | 2234 | A compiled code object, to be executed |
|
2236 | 2235 | post_execute : bool [default: True] |
|
2237 | 2236 | whether to call post_execute hooks after this particular execution. |
|
2238 | 2237 | |
|
2239 | 2238 | Returns |
|
2240 | 2239 | ------- |
|
2241 | 2240 | False : successful execution. |
|
2242 | 2241 | True : an error occurred. |
|
2243 | 2242 | """ |
|
2244 | 2243 | |
|
2245 | 2244 | # Set our own excepthook in case the user code tries to call it |
|
2246 | 2245 | # directly, so that the IPython crash handler doesn't get triggered |
|
2247 | 2246 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2248 | 2247 | |
|
2249 | 2248 | # we save the original sys.excepthook in the instance, in case config |
|
2250 | 2249 | # code (such as magics) needs access to it. |
|
2251 | 2250 | self.sys_excepthook = old_excepthook |
|
2252 | 2251 | outflag = 1 # happens in more places, so it's easier as default |
|
2253 | 2252 | try: |
|
2254 | 2253 | try: |
|
2255 | 2254 | self.hooks.pre_run_code_hook() |
|
2256 | 2255 | #rprint('Running code', repr(code_obj)) # dbg |
|
2257 | 2256 | exec code_obj in self.user_global_ns, self.user_ns |
|
2258 | 2257 | finally: |
|
2259 | 2258 | # Reset our crash handler in place |
|
2260 | 2259 | sys.excepthook = old_excepthook |
|
2261 | 2260 | except SystemExit: |
|
2262 | 2261 | self.showtraceback(exception_only=True) |
|
2263 | 2262 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1) |
|
2264 | 2263 | except self.custom_exceptions: |
|
2265 | 2264 | etype,value,tb = sys.exc_info() |
|
2266 | 2265 | self.CustomTB(etype,value,tb) |
|
2267 | 2266 | except: |
|
2268 | 2267 | self.showtraceback() |
|
2269 | 2268 | else: |
|
2270 | 2269 | outflag = 0 |
|
2271 | 2270 | if softspace(sys.stdout, 0): |
|
2272 | 2271 | |
|
2273 | 2272 | |
|
2274 | 2273 | return outflag |
|
2275 | 2274 | |
|
2276 | 2275 | # For backwards compatibility |
|
2277 | 2276 | runcode = run_code |
|
2278 | 2277 | |
|
2279 | 2278 | #------------------------------------------------------------------------- |
|
2280 | 2279 | # Things related to GUI support and pylab |
|
2281 | 2280 | #------------------------------------------------------------------------- |
|
2282 | 2281 | |
|
2283 | 2282 | def enable_pylab(self, gui=None): |
|
2284 | 2283 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2285 | 2284 | |
|
2286 | 2285 | #------------------------------------------------------------------------- |
|
2287 | 2286 | # Utilities |
|
2288 | 2287 | #------------------------------------------------------------------------- |
|
2289 | 2288 | |
|
2290 | 2289 | def var_expand(self,cmd,depth=0): |
|
2291 | 2290 | """Expand python variables in a string. |
|
2292 | 2291 | |
|
2293 | 2292 | The depth argument indicates how many frames above the caller should |
|
2294 | 2293 | be walked to look for the local namespace where to expand variables. |
|
2295 | 2294 | |
|
2296 | 2295 | The global namespace for expansion is always the user's interactive |
|
2297 | 2296 | namespace. |
|
2298 | 2297 | """ |
|
2299 | 2298 | res = ItplNS(cmd, self.user_ns, # globals |
|
2300 | 2299 | # Skip our own frame in searching for locals: |
|
2301 | 2300 | sys._getframe(depth+1).f_locals # locals |
|
2302 | 2301 | ) |
|
2303 | 2302 | return str(res).decode(res.codec) |
|
2304 | 2303 | |
|
2305 | 2304 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
2306 | 2305 | """Make a new tempfile and return its filename. |
|
2307 | 2306 | |
|
2308 | 2307 | This makes a call to tempfile.mktemp, but it registers the created |
|
2309 | 2308 | filename internally so ipython cleans it up at exit time. |
|
2310 | 2309 | |
|
2311 | 2310 | Optional inputs: |
|
2312 | 2311 | |
|
2313 | 2312 | - data(None): if data is given, it gets written out to the temp file |
|
2314 | 2313 | immediately, and the file is closed again.""" |
|
2315 | 2314 | |
|
2316 | 2315 | filename = tempfile.mktemp('.py', prefix) |
|
2317 | 2316 | self.tempfiles.append(filename) |
|
2318 | 2317 | |
|
2319 | 2318 | if data: |
|
2320 | 2319 | tmp_file = open(filename,'w') |
|
2321 | 2320 | tmp_file.write(data) |
|
2322 | 2321 | tmp_file.close() |
|
2323 | 2322 | return filename |
|
2324 | 2323 | |
|
2325 | 2324 | # TODO: This should be removed when Term is refactored. |
|
2326 | 2325 | def write(self,data): |
|
2327 | 2326 | """Write a string to the default output""" |
|
2328 |
io. |
|
|
2327 | io.stdout.write(data) | |
|
2329 | 2328 | |
|
2330 | 2329 | # TODO: This should be removed when Term is refactored. |
|
2331 | 2330 | def write_err(self,data): |
|
2332 | 2331 | """Write a string to the default error output""" |
|
2333 |
io. |
|
|
2332 | io.stderr.write(data) | |
|
2334 | 2333 | |
|
2335 | 2334 | def ask_yes_no(self,prompt,default=True): |
|
2336 | 2335 | if self.quiet: |
|
2337 | 2336 | return True |
|
2338 | 2337 | return ask_yes_no(prompt,default) |
|
2339 | 2338 | |
|
2340 | 2339 | def show_usage(self): |
|
2341 | 2340 | """Show a usage message""" |
|
2342 | 2341 | page.page(IPython.core.usage.interactive_usage) |
|
2343 | 2342 | |
|
2344 | 2343 | def find_user_code(self, target, raw=True): |
|
2345 | 2344 | """Get a code string from history, file, or a string or macro. |
|
2346 | 2345 | |
|
2347 | 2346 | This is mainly used by magic functions. |
|
2348 | 2347 | |
|
2349 | 2348 | Parameters |
|
2350 | 2349 | ---------- |
|
2351 | 2350 | target : str |
|
2352 | 2351 | A string specifying code to retrieve. This will be tried respectively |
|
2353 | 2352 | as: ranges of input history (see %history for syntax), a filename, or |
|
2354 | 2353 | an expression evaluating to a string or Macro in the user namespace. |
|
2355 | 2354 | raw : bool |
|
2356 | 2355 | If true (default), retrieve raw history. Has no effect on the other |
|
2357 | 2356 | retrieval mechanisms. |
|
2358 | 2357 | |
|
2359 | 2358 | Returns |
|
2360 | 2359 | ------- |
|
2361 | 2360 | A string of code. |
|
2362 | 2361 | |
|
2363 | 2362 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
2364 | 2363 | to an object of another type. In each case, .args[0] is a printable |
|
2365 | 2364 | message. |
|
2366 | 2365 | """ |
|
2367 | 2366 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
2368 | 2367 | if code: |
|
2369 | 2368 | return code |
|
2370 | 2369 | if os.path.isfile(target): # Read file |
|
2371 | 2370 | return open(target, "r").read() |
|
2372 | 2371 | |
|
2373 | 2372 | try: # User namespace |
|
2374 | 2373 | codeobj = eval(target, self.user_ns) |
|
2375 | 2374 | except Exception: |
|
2376 | 2375 | raise ValueError(("'%s' was not found in history, as a file, nor in" |
|
2377 | 2376 | " the user namespace.") % target) |
|
2378 | 2377 | if isinstance(codeobj, basestring): |
|
2379 | 2378 | return codeobj |
|
2380 | 2379 | elif isinstance(codeobj, Macro): |
|
2381 | 2380 | return codeobj.value |
|
2382 | 2381 | |
|
2383 | 2382 | raise TypeError("%s is neither a string nor a macro." % target, |
|
2384 | 2383 | codeobj) |
|
2385 | 2384 | |
|
2386 | 2385 | #------------------------------------------------------------------------- |
|
2387 | 2386 | # Things related to IPython exiting |
|
2388 | 2387 | #------------------------------------------------------------------------- |
|
2389 | 2388 | def atexit_operations(self): |
|
2390 | 2389 | """This will be executed at the time of exit. |
|
2391 | 2390 | |
|
2392 | 2391 | Cleanup operations and saving of persistent data that is done |
|
2393 | 2392 | unconditionally by IPython should be performed here. |
|
2394 | 2393 | |
|
2395 | 2394 | For things that may depend on startup flags or platform specifics (such |
|
2396 | 2395 | as having readline or not), register a separate atexit function in the |
|
2397 | 2396 | code that has the appropriate information, rather than trying to |
|
2398 | 2397 | clutter |
|
2399 | 2398 | """ |
|
2400 | 2399 | # Cleanup all tempfiles left around |
|
2401 | 2400 | for tfile in self.tempfiles: |
|
2402 | 2401 | try: |
|
2403 | 2402 | os.unlink(tfile) |
|
2404 | 2403 | except OSError: |
|
2405 | 2404 | pass |
|
2406 | 2405 | |
|
2407 | 2406 | # Close the history session (this stores the end time and line count) |
|
2408 | 2407 | self.history_manager.end_session() |
|
2409 | 2408 | |
|
2410 | 2409 | # Clear all user namespaces to release all references cleanly. |
|
2411 | 2410 | self.reset(new_session=False) |
|
2412 | 2411 | |
|
2413 | 2412 | # Run user hooks |
|
2414 | 2413 | self.hooks.shutdown_hook() |
|
2415 | 2414 | |
|
2416 | 2415 | def cleanup(self): |
|
2417 | 2416 | self.restore_sys_module_state() |
|
2418 | 2417 | |
|
2419 | 2418 | |
|
2420 | 2419 | class InteractiveShellABC(object): |
|
2421 | 2420 | """An abstract base class for InteractiveShell.""" |
|
2422 | 2421 | __metaclass__ = abc.ABCMeta |
|
2423 | 2422 | |
|
2424 | 2423 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,60 +1,58 b'' | |||
|
1 | 1 | """Support for interactive macros in IPython""" |
|
2 | 2 | |
|
3 | 3 | #***************************************************************************** |
|
4 | 4 | # Copyright (C) 2001-2005 Fernando Perez <fperez@colorado.edu> |
|
5 | 5 | # |
|
6 | 6 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | 7 | # the file COPYING, distributed as part of this software. |
|
8 | 8 | #***************************************************************************** |
|
9 | 9 | |
|
10 | 10 | import re |
|
11 | 11 | import sys |
|
12 | 12 | |
|
13 | import IPython.utils.io | |
|
14 | ||
|
15 | 13 | coding_declaration = re.compile(r"#\s*coding[:=]\s*([-\w.]+)") |
|
16 | 14 | |
|
17 | 15 | class Macro(object): |
|
18 | 16 | """Simple class to store the value of macros as strings. |
|
19 | 17 | |
|
20 | 18 | Macro is just a callable that executes a string of IPython |
|
21 | 19 | input when called. |
|
22 | 20 | |
|
23 | 21 | Args to macro are available in _margv list if you need them. |
|
24 | 22 | """ |
|
25 | 23 | |
|
26 | 24 | def __init__(self,code): |
|
27 | 25 | """store the macro value, as a single string which can be executed""" |
|
28 | 26 | lines = [] |
|
29 | 27 | enc = None |
|
30 | 28 | for line in code.splitlines(): |
|
31 | 29 | coding_match = coding_declaration.match(line) |
|
32 | 30 | if coding_match: |
|
33 | 31 | enc = coding_match.group(1) |
|
34 | 32 | else: |
|
35 | 33 | lines.append(line) |
|
36 | 34 | code = "\n".join(lines) |
|
37 | 35 | if isinstance(code, bytes): |
|
38 | 36 | code = code.decode(enc or sys.getdefaultencoding()) |
|
39 | 37 | self.value = code + '\n' |
|
40 | 38 | |
|
41 | 39 | def __str__(self): |
|
42 | 40 | enc = sys.stdin.encoding or sys.getdefaultencoding() |
|
43 | 41 | return self.value.encode(enc, "replace") |
|
44 | 42 | |
|
45 | 43 | def __unicode__(self): |
|
46 | 44 | return self.value |
|
47 | 45 | |
|
48 | 46 | def __repr__(self): |
|
49 | 47 | return 'IPython.macro.Macro(%s)' % repr(self.value) |
|
50 | 48 | |
|
51 | 49 | def __getstate__(self): |
|
52 | 50 | """ needed for safe pickling via %store """ |
|
53 | 51 | return {'value': self.value} |
|
54 | 52 | |
|
55 | 53 | def __add__(self, other): |
|
56 | 54 | if isinstance(other, Macro): |
|
57 | 55 | return Macro(self.value + other.value) |
|
58 | 56 | elif isinstance(other, basestring): |
|
59 | 57 | return Macro(self.value + other) |
|
60 | 58 | raise TypeError |
@@ -1,3470 +1,3469 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Magic functions for InteractiveShell. |
|
3 | 3 | """ |
|
4 | 4 | |
|
5 | 5 | #----------------------------------------------------------------------------- |
|
6 | 6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
7 | 7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
8 | 8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
9 | 9 | |
|
10 | 10 | # Distributed under the terms of the BSD License. The full license is in |
|
11 | 11 | # the file COPYING, distributed as part of this software. |
|
12 | 12 | #----------------------------------------------------------------------------- |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | |
|
18 | 18 | import __builtin__ |
|
19 | 19 | import __future__ |
|
20 | 20 | import bdb |
|
21 | 21 | import inspect |
|
22 | 22 | import os |
|
23 | 23 | import sys |
|
24 | 24 | import shutil |
|
25 | 25 | import re |
|
26 | 26 | import time |
|
27 | 27 | import textwrap |
|
28 | 28 | from cStringIO import StringIO |
|
29 | 29 | from getopt import getopt,GetoptError |
|
30 | 30 | from pprint import pformat |
|
31 | 31 | from xmlrpclib import ServerProxy |
|
32 | 32 | |
|
33 | 33 | # cProfile was added in Python2.5 |
|
34 | 34 | try: |
|
35 | 35 | import cProfile as profile |
|
36 | 36 | import pstats |
|
37 | 37 | except ImportError: |
|
38 | 38 | # profile isn't bundled by default in Debian for license reasons |
|
39 | 39 | try: |
|
40 | 40 | import profile,pstats |
|
41 | 41 | except ImportError: |
|
42 | 42 | profile = pstats = None |
|
43 | 43 | |
|
44 | 44 | import IPython |
|
45 | 45 | from IPython.core import debugger, oinspect |
|
46 | 46 | from IPython.core.error import TryNext |
|
47 | 47 | from IPython.core.error import UsageError |
|
48 | 48 | from IPython.core.fakemodule import FakeModule |
|
49 | 49 | from IPython.core.macro import Macro |
|
50 | 50 | from IPython.core import page |
|
51 | 51 | from IPython.core.prefilter import ESC_MAGIC |
|
52 | 52 | from IPython.lib.pylabtools import mpl_runner |
|
53 | 53 | from IPython.external.Itpl import itpl, printpl |
|
54 | 54 | from IPython.testing import decorators as testdec |
|
55 | 55 | from IPython.utils.io import file_read, nlprint |
|
56 | import IPython.utils.io | |
|
57 | 56 | from IPython.utils.path import get_py_filename |
|
58 | 57 | from IPython.utils.process import arg_split, abbrev_cwd |
|
59 | 58 | from IPython.utils.terminal import set_term_title |
|
60 | 59 | from IPython.utils.text import LSString, SList, format_screen |
|
61 | 60 | from IPython.utils.timing import clock, clock2 |
|
62 | 61 | from IPython.utils.warn import warn, error |
|
63 | 62 | from IPython.utils.ipstruct import Struct |
|
64 | 63 | import IPython.utils.generics |
|
65 | 64 | |
|
66 | 65 | #----------------------------------------------------------------------------- |
|
67 | 66 | # Utility functions |
|
68 | 67 | #----------------------------------------------------------------------------- |
|
69 | 68 | |
|
70 | 69 | def on_off(tag): |
|
71 | 70 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
72 | 71 | return ['OFF','ON'][tag] |
|
73 | 72 | |
|
74 | 73 | class Bunch: pass |
|
75 | 74 | |
|
76 | 75 | def compress_dhist(dh): |
|
77 | 76 | head, tail = dh[:-10], dh[-10:] |
|
78 | 77 | |
|
79 | 78 | newhead = [] |
|
80 | 79 | done = set() |
|
81 | 80 | for h in head: |
|
82 | 81 | if h in done: |
|
83 | 82 | continue |
|
84 | 83 | newhead.append(h) |
|
85 | 84 | done.add(h) |
|
86 | 85 | |
|
87 | 86 | return newhead + tail |
|
88 | 87 | |
|
89 | 88 | def needs_local_scope(func): |
|
90 | 89 | """Decorator to mark magic functions which need to local scope to run.""" |
|
91 | 90 | func.needs_local_scope = True |
|
92 | 91 | return func |
|
93 | 92 | |
|
94 | 93 | #*************************************************************************** |
|
95 | 94 | # Main class implementing Magic functionality |
|
96 | 95 | |
|
97 | 96 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
98 | 97 | # on construction of the main InteractiveShell object. Something odd is going |
|
99 | 98 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
100 | 99 | # eventually this needs to be clarified. |
|
101 | 100 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
102 | 101 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
103 | 102 | # make Magic a configurable that InteractiveShell does not subclass. |
|
104 | 103 | |
|
105 | 104 | class Magic: |
|
106 | 105 | """Magic functions for InteractiveShell. |
|
107 | 106 | |
|
108 | 107 | Shell functions which can be reached as %function_name. All magic |
|
109 | 108 | functions should accept a string, which they can parse for their own |
|
110 | 109 | needs. This can make some functions easier to type, eg `%cd ../` |
|
111 | 110 | vs. `%cd("../")` |
|
112 | 111 | |
|
113 | 112 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
114 | 113 | at the command line, but it is is needed in the definition. """ |
|
115 | 114 | |
|
116 | 115 | # class globals |
|
117 | 116 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
118 | 117 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
119 | 118 | |
|
120 | 119 | #...................................................................... |
|
121 | 120 | # some utility functions |
|
122 | 121 | |
|
123 | 122 | def __init__(self,shell): |
|
124 | 123 | |
|
125 | 124 | self.options_table = {} |
|
126 | 125 | if profile is None: |
|
127 | 126 | self.magic_prun = self.profile_missing_notice |
|
128 | 127 | self.shell = shell |
|
129 | 128 | |
|
130 | 129 | # namespace for holding state we may need |
|
131 | 130 | self._magic_state = Bunch() |
|
132 | 131 | |
|
133 | 132 | def profile_missing_notice(self, *args, **kwargs): |
|
134 | 133 | error("""\ |
|
135 | 134 | The profile module could not be found. It has been removed from the standard |
|
136 | 135 | python packages because of its non-free license. To use profiling, install the |
|
137 | 136 | python-profiler package from non-free.""") |
|
138 | 137 | |
|
139 | 138 | def default_option(self,fn,optstr): |
|
140 | 139 | """Make an entry in the options_table for fn, with value optstr""" |
|
141 | 140 | |
|
142 | 141 | if fn not in self.lsmagic(): |
|
143 | 142 | error("%s is not a magic function" % fn) |
|
144 | 143 | self.options_table[fn] = optstr |
|
145 | 144 | |
|
146 | 145 | def lsmagic(self): |
|
147 | 146 | """Return a list of currently available magic functions. |
|
148 | 147 | |
|
149 | 148 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
150 | 149 | ['magic_ls','magic_cd',...]""" |
|
151 | 150 | |
|
152 | 151 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
153 | 152 | |
|
154 | 153 | # magics in class definition |
|
155 | 154 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
156 | 155 | callable(Magic.__dict__[fn]) |
|
157 | 156 | # in instance namespace (run-time user additions) |
|
158 | 157 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
159 | 158 | callable(self.__dict__[fn]) |
|
160 | 159 | # and bound magics by user (so they can access self): |
|
161 | 160 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
162 | 161 | callable(self.__class__.__dict__[fn]) |
|
163 | 162 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
164 | 163 | filter(inst_magic,self.__dict__.keys()) + \ |
|
165 | 164 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
166 | 165 | out = [] |
|
167 | 166 | for fn in set(magics): |
|
168 | 167 | out.append(fn.replace('magic_','',1)) |
|
169 | 168 | out.sort() |
|
170 | 169 | return out |
|
171 | 170 | |
|
172 | 171 | def extract_input_lines(self, range_str, raw=False): |
|
173 | 172 | """Return as a string a set of input history slices. |
|
174 | 173 | |
|
175 | 174 | Inputs: |
|
176 | 175 | |
|
177 | 176 | - range_str: the set of slices is given as a string, like |
|
178 | 177 | "~5/6-~4/2 4:8 9", since this function is for use by magic functions |
|
179 | 178 | which get their arguments as strings. The number before the / is the |
|
180 | 179 | session number: ~n goes n back from the current session. |
|
181 | 180 | |
|
182 | 181 | Optional inputs: |
|
183 | 182 | |
|
184 | 183 | - raw(False): by default, the processed input is used. If this is |
|
185 | 184 | true, the raw input history is used instead. |
|
186 | 185 | |
|
187 | 186 | Note that slices can be called with two notations: |
|
188 | 187 | |
|
189 | 188 | N:M -> standard python form, means including items N...(M-1). |
|
190 | 189 | |
|
191 | 190 | N-M -> include items N..M (closed endpoint).""" |
|
192 | 191 | lines = self.shell.history_manager.\ |
|
193 | 192 | get_range_by_str(range_str, raw=raw) |
|
194 | 193 | return "\n".join(x for _, _, x in lines) |
|
195 | 194 | |
|
196 | 195 | def arg_err(self,func): |
|
197 | 196 | """Print docstring if incorrect arguments were passed""" |
|
198 | 197 | print 'Error in arguments:' |
|
199 | 198 | print oinspect.getdoc(func) |
|
200 | 199 | |
|
201 | 200 | def format_latex(self,strng): |
|
202 | 201 | """Format a string for latex inclusion.""" |
|
203 | 202 | |
|
204 | 203 | # Characters that need to be escaped for latex: |
|
205 | 204 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
206 | 205 | # Magic command names as headers: |
|
207 | 206 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
208 | 207 | re.MULTILINE) |
|
209 | 208 | # Magic commands |
|
210 | 209 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
211 | 210 | re.MULTILINE) |
|
212 | 211 | # Paragraph continue |
|
213 | 212 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
214 | 213 | |
|
215 | 214 | # The "\n" symbol |
|
216 | 215 | newline_re = re.compile(r'\\n') |
|
217 | 216 | |
|
218 | 217 | # Now build the string for output: |
|
219 | 218 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
220 | 219 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
221 | 220 | strng) |
|
222 | 221 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
223 | 222 | strng = par_re.sub(r'\\\\',strng) |
|
224 | 223 | strng = escape_re.sub(r'\\\1',strng) |
|
225 | 224 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
226 | 225 | return strng |
|
227 | 226 | |
|
228 | 227 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
229 | 228 | """Parse options passed to an argument string. |
|
230 | 229 | |
|
231 | 230 | The interface is similar to that of getopt(), but it returns back a |
|
232 | 231 | Struct with the options as keys and the stripped argument string still |
|
233 | 232 | as a string. |
|
234 | 233 | |
|
235 | 234 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
236 | 235 | This allows us to easily expand variables, glob files, quote |
|
237 | 236 | arguments, etc. |
|
238 | 237 | |
|
239 | 238 | Options: |
|
240 | 239 | -mode: default 'string'. If given as 'list', the argument string is |
|
241 | 240 | returned as a list (split on whitespace) instead of a string. |
|
242 | 241 | |
|
243 | 242 | -list_all: put all option values in lists. Normally only options |
|
244 | 243 | appearing more than once are put in a list. |
|
245 | 244 | |
|
246 | 245 | -posix (True): whether to split the input line in POSIX mode or not, |
|
247 | 246 | as per the conventions outlined in the shlex module from the |
|
248 | 247 | standard library.""" |
|
249 | 248 | |
|
250 | 249 | # inject default options at the beginning of the input line |
|
251 | 250 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
252 | 251 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
253 | 252 | |
|
254 | 253 | mode = kw.get('mode','string') |
|
255 | 254 | if mode not in ['string','list']: |
|
256 | 255 | raise ValueError,'incorrect mode given: %s' % mode |
|
257 | 256 | # Get options |
|
258 | 257 | list_all = kw.get('list_all',0) |
|
259 | 258 | posix = kw.get('posix', os.name == 'posix') |
|
260 | 259 | |
|
261 | 260 | # Check if we have more than one argument to warrant extra processing: |
|
262 | 261 | odict = {} # Dictionary with options |
|
263 | 262 | args = arg_str.split() |
|
264 | 263 | if len(args) >= 1: |
|
265 | 264 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
266 | 265 | # need to look for options |
|
267 | 266 | argv = arg_split(arg_str,posix) |
|
268 | 267 | # Do regular option processing |
|
269 | 268 | try: |
|
270 | 269 | opts,args = getopt(argv,opt_str,*long_opts) |
|
271 | 270 | except GetoptError,e: |
|
272 | 271 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
273 | 272 | " ".join(long_opts))) |
|
274 | 273 | for o,a in opts: |
|
275 | 274 | if o.startswith('--'): |
|
276 | 275 | o = o[2:] |
|
277 | 276 | else: |
|
278 | 277 | o = o[1:] |
|
279 | 278 | try: |
|
280 | 279 | odict[o].append(a) |
|
281 | 280 | except AttributeError: |
|
282 | 281 | odict[o] = [odict[o],a] |
|
283 | 282 | except KeyError: |
|
284 | 283 | if list_all: |
|
285 | 284 | odict[o] = [a] |
|
286 | 285 | else: |
|
287 | 286 | odict[o] = a |
|
288 | 287 | |
|
289 | 288 | # Prepare opts,args for return |
|
290 | 289 | opts = Struct(odict) |
|
291 | 290 | if mode == 'string': |
|
292 | 291 | args = ' '.join(args) |
|
293 | 292 | |
|
294 | 293 | return opts,args |
|
295 | 294 | |
|
296 | 295 | #...................................................................... |
|
297 | 296 | # And now the actual magic functions |
|
298 | 297 | |
|
299 | 298 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
300 | 299 | def magic_lsmagic(self, parameter_s = ''): |
|
301 | 300 | """List currently available magic functions.""" |
|
302 | 301 | mesc = ESC_MAGIC |
|
303 | 302 | print 'Available magic functions:\n'+mesc+\ |
|
304 | 303 | (' '+mesc).join(self.lsmagic()) |
|
305 | 304 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
306 | 305 | return None |
|
307 | 306 | |
|
308 | 307 | def magic_magic(self, parameter_s = ''): |
|
309 | 308 | """Print information about the magic function system. |
|
310 | 309 | |
|
311 | 310 | Supported formats: -latex, -brief, -rest |
|
312 | 311 | """ |
|
313 | 312 | |
|
314 | 313 | mode = '' |
|
315 | 314 | try: |
|
316 | 315 | if parameter_s.split()[0] == '-latex': |
|
317 | 316 | mode = 'latex' |
|
318 | 317 | if parameter_s.split()[0] == '-brief': |
|
319 | 318 | mode = 'brief' |
|
320 | 319 | if parameter_s.split()[0] == '-rest': |
|
321 | 320 | mode = 'rest' |
|
322 | 321 | rest_docs = [] |
|
323 | 322 | except: |
|
324 | 323 | pass |
|
325 | 324 | |
|
326 | 325 | magic_docs = [] |
|
327 | 326 | for fname in self.lsmagic(): |
|
328 | 327 | mname = 'magic_' + fname |
|
329 | 328 | for space in (Magic,self,self.__class__): |
|
330 | 329 | try: |
|
331 | 330 | fn = space.__dict__[mname] |
|
332 | 331 | except KeyError: |
|
333 | 332 | pass |
|
334 | 333 | else: |
|
335 | 334 | break |
|
336 | 335 | if mode == 'brief': |
|
337 | 336 | # only first line |
|
338 | 337 | if fn.__doc__: |
|
339 | 338 | fndoc = fn.__doc__.split('\n',1)[0] |
|
340 | 339 | else: |
|
341 | 340 | fndoc = 'No documentation' |
|
342 | 341 | else: |
|
343 | 342 | if fn.__doc__: |
|
344 | 343 | fndoc = fn.__doc__.rstrip() |
|
345 | 344 | else: |
|
346 | 345 | fndoc = 'No documentation' |
|
347 | 346 | |
|
348 | 347 | |
|
349 | 348 | if mode == 'rest': |
|
350 | 349 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
351 | 350 | fname,fndoc)) |
|
352 | 351 | |
|
353 | 352 | else: |
|
354 | 353 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
355 | 354 | fname,fndoc)) |
|
356 | 355 | |
|
357 | 356 | magic_docs = ''.join(magic_docs) |
|
358 | 357 | |
|
359 | 358 | if mode == 'rest': |
|
360 | 359 | return "".join(rest_docs) |
|
361 | 360 | |
|
362 | 361 | if mode == 'latex': |
|
363 | 362 | print self.format_latex(magic_docs) |
|
364 | 363 | return |
|
365 | 364 | else: |
|
366 | 365 | magic_docs = format_screen(magic_docs) |
|
367 | 366 | if mode == 'brief': |
|
368 | 367 | return magic_docs |
|
369 | 368 | |
|
370 | 369 | outmsg = """ |
|
371 | 370 | IPython's 'magic' functions |
|
372 | 371 | =========================== |
|
373 | 372 | |
|
374 | 373 | The magic function system provides a series of functions which allow you to |
|
375 | 374 | control the behavior of IPython itself, plus a lot of system-type |
|
376 | 375 | features. All these functions are prefixed with a % character, but parameters |
|
377 | 376 | are given without parentheses or quotes. |
|
378 | 377 | |
|
379 | 378 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
380 | 379 | %automagic function), you don't need to type in the % explicitly. By default, |
|
381 | 380 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
382 | 381 | |
|
383 | 382 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
384 | 383 | to 'mydir', if it exists. |
|
385 | 384 | |
|
386 | 385 | You can define your own magic functions to extend the system. See the supplied |
|
387 | 386 | ipythonrc and example-magic.py files for details (in your ipython |
|
388 | 387 | configuration directory, typically $HOME/.config/ipython on Linux or $HOME/.ipython elsewhere). |
|
389 | 388 | |
|
390 | 389 | You can also define your own aliased names for magic functions. In your |
|
391 | 390 | ipythonrc file, placing a line like: |
|
392 | 391 | |
|
393 | 392 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
394 | 393 | |
|
395 | 394 | will define %pf as a new name for %profile. |
|
396 | 395 | |
|
397 | 396 | You can also call magics in code using the magic() function, which IPython |
|
398 | 397 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
399 | 398 | |
|
400 | 399 | For a list of the available magic functions, use %lsmagic. For a description |
|
401 | 400 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
402 | 401 | |
|
403 | 402 | Currently the magic system has the following functions:\n""" |
|
404 | 403 | |
|
405 | 404 | mesc = ESC_MAGIC |
|
406 | 405 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
407 | 406 | "\n\n%s%s\n\n%s" % (outmsg, |
|
408 | 407 | magic_docs,mesc,mesc, |
|
409 | 408 | (' '+mesc).join(self.lsmagic()), |
|
410 | 409 | Magic.auto_status[self.shell.automagic] ) ) |
|
411 | 410 | page.page(outmsg) |
|
412 | 411 | |
|
413 | 412 | def magic_automagic(self, parameter_s = ''): |
|
414 | 413 | """Make magic functions callable without having to type the initial %. |
|
415 | 414 | |
|
416 | 415 | Without argumentsl toggles on/off (when off, you must call it as |
|
417 | 416 | %automagic, of course). With arguments it sets the value, and you can |
|
418 | 417 | use any of (case insensitive): |
|
419 | 418 | |
|
420 | 419 | - on,1,True: to activate |
|
421 | 420 | |
|
422 | 421 | - off,0,False: to deactivate. |
|
423 | 422 | |
|
424 | 423 | Note that magic functions have lowest priority, so if there's a |
|
425 | 424 | variable whose name collides with that of a magic fn, automagic won't |
|
426 | 425 | work for that function (you get the variable instead). However, if you |
|
427 | 426 | delete the variable (del var), the previously shadowed magic function |
|
428 | 427 | becomes visible to automagic again.""" |
|
429 | 428 | |
|
430 | 429 | arg = parameter_s.lower() |
|
431 | 430 | if parameter_s in ('on','1','true'): |
|
432 | 431 | self.shell.automagic = True |
|
433 | 432 | elif parameter_s in ('off','0','false'): |
|
434 | 433 | self.shell.automagic = False |
|
435 | 434 | else: |
|
436 | 435 | self.shell.automagic = not self.shell.automagic |
|
437 | 436 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
438 | 437 | |
|
439 | 438 | @testdec.skip_doctest |
|
440 | 439 | def magic_autocall(self, parameter_s = ''): |
|
441 | 440 | """Make functions callable without having to type parentheses. |
|
442 | 441 | |
|
443 | 442 | Usage: |
|
444 | 443 | |
|
445 | 444 | %autocall [mode] |
|
446 | 445 | |
|
447 | 446 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
448 | 447 | value is toggled on and off (remembering the previous state). |
|
449 | 448 | |
|
450 | 449 | In more detail, these values mean: |
|
451 | 450 | |
|
452 | 451 | 0 -> fully disabled |
|
453 | 452 | |
|
454 | 453 | 1 -> active, but do not apply if there are no arguments on the line. |
|
455 | 454 | |
|
456 | 455 | In this mode, you get: |
|
457 | 456 | |
|
458 | 457 | In [1]: callable |
|
459 | 458 | Out[1]: <built-in function callable> |
|
460 | 459 | |
|
461 | 460 | In [2]: callable 'hello' |
|
462 | 461 | ------> callable('hello') |
|
463 | 462 | Out[2]: False |
|
464 | 463 | |
|
465 | 464 | 2 -> Active always. Even if no arguments are present, the callable |
|
466 | 465 | object is called: |
|
467 | 466 | |
|
468 | 467 | In [2]: float |
|
469 | 468 | ------> float() |
|
470 | 469 | Out[2]: 0.0 |
|
471 | 470 | |
|
472 | 471 | Note that even with autocall off, you can still use '/' at the start of |
|
473 | 472 | a line to treat the first argument on the command line as a function |
|
474 | 473 | and add parentheses to it: |
|
475 | 474 | |
|
476 | 475 | In [8]: /str 43 |
|
477 | 476 | ------> str(43) |
|
478 | 477 | Out[8]: '43' |
|
479 | 478 | |
|
480 | 479 | # all-random (note for auto-testing) |
|
481 | 480 | """ |
|
482 | 481 | |
|
483 | 482 | if parameter_s: |
|
484 | 483 | arg = int(parameter_s) |
|
485 | 484 | else: |
|
486 | 485 | arg = 'toggle' |
|
487 | 486 | |
|
488 | 487 | if not arg in (0,1,2,'toggle'): |
|
489 | 488 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
490 | 489 | return |
|
491 | 490 | |
|
492 | 491 | if arg in (0,1,2): |
|
493 | 492 | self.shell.autocall = arg |
|
494 | 493 | else: # toggle |
|
495 | 494 | if self.shell.autocall: |
|
496 | 495 | self._magic_state.autocall_save = self.shell.autocall |
|
497 | 496 | self.shell.autocall = 0 |
|
498 | 497 | else: |
|
499 | 498 | try: |
|
500 | 499 | self.shell.autocall = self._magic_state.autocall_save |
|
501 | 500 | except AttributeError: |
|
502 | 501 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
503 | 502 | |
|
504 | 503 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
505 | 504 | |
|
506 | 505 | |
|
507 | 506 | def magic_page(self, parameter_s=''): |
|
508 | 507 | """Pretty print the object and display it through a pager. |
|
509 | 508 | |
|
510 | 509 | %page [options] OBJECT |
|
511 | 510 | |
|
512 | 511 | If no object is given, use _ (last output). |
|
513 | 512 | |
|
514 | 513 | Options: |
|
515 | 514 | |
|
516 | 515 | -r: page str(object), don't pretty-print it.""" |
|
517 | 516 | |
|
518 | 517 | # After a function contributed by Olivier Aubert, slightly modified. |
|
519 | 518 | |
|
520 | 519 | # Process options/args |
|
521 | 520 | opts,args = self.parse_options(parameter_s,'r') |
|
522 | 521 | raw = 'r' in opts |
|
523 | 522 | |
|
524 | 523 | oname = args and args or '_' |
|
525 | 524 | info = self._ofind(oname) |
|
526 | 525 | if info['found']: |
|
527 | 526 | txt = (raw and str or pformat)( info['obj'] ) |
|
528 | 527 | page.page(txt) |
|
529 | 528 | else: |
|
530 | 529 | print 'Object `%s` not found' % oname |
|
531 | 530 | |
|
532 | 531 | def magic_profile(self, parameter_s=''): |
|
533 | 532 | """Print your currently active IPython profile.""" |
|
534 | 533 | if self.shell.profile: |
|
535 | 534 | printpl('Current IPython profile: $self.shell.profile.') |
|
536 | 535 | else: |
|
537 | 536 | print 'No profile active.' |
|
538 | 537 | |
|
539 | 538 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
540 | 539 | """Provide detailed information about an object. |
|
541 | 540 | |
|
542 | 541 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
543 | 542 | |
|
544 | 543 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
545 | 544 | |
|
546 | 545 | |
|
547 | 546 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
548 | 547 | detail_level = 0 |
|
549 | 548 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
550 | 549 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
551 | 550 | pinfo,qmark1,oname,qmark2 = \ |
|
552 | 551 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
553 | 552 | if pinfo or qmark1 or qmark2: |
|
554 | 553 | detail_level = 1 |
|
555 | 554 | if "*" in oname: |
|
556 | 555 | self.magic_psearch(oname) |
|
557 | 556 | else: |
|
558 | 557 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
559 | 558 | namespaces=namespaces) |
|
560 | 559 | |
|
561 | 560 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
562 | 561 | """Provide extra detailed information about an object. |
|
563 | 562 | |
|
564 | 563 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
565 | 564 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
566 | 565 | namespaces=namespaces) |
|
567 | 566 | |
|
568 | 567 | @testdec.skip_doctest |
|
569 | 568 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
570 | 569 | """Print the definition header for any callable object. |
|
571 | 570 | |
|
572 | 571 | If the object is a class, print the constructor information. |
|
573 | 572 | |
|
574 | 573 | Examples |
|
575 | 574 | -------- |
|
576 | 575 | :: |
|
577 | 576 | |
|
578 | 577 | In [3]: %pdef urllib.urlopen |
|
579 | 578 | urllib.urlopen(url, data=None, proxies=None) |
|
580 | 579 | """ |
|
581 | 580 | self._inspect('pdef',parameter_s, namespaces) |
|
582 | 581 | |
|
583 | 582 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
584 | 583 | """Print the docstring for an object. |
|
585 | 584 | |
|
586 | 585 | If the given object is a class, it will print both the class and the |
|
587 | 586 | constructor docstrings.""" |
|
588 | 587 | self._inspect('pdoc',parameter_s, namespaces) |
|
589 | 588 | |
|
590 | 589 | def magic_psource(self, parameter_s='', namespaces=None): |
|
591 | 590 | """Print (or run through pager) the source code for an object.""" |
|
592 | 591 | self._inspect('psource',parameter_s, namespaces) |
|
593 | 592 | |
|
594 | 593 | def magic_pfile(self, parameter_s=''): |
|
595 | 594 | """Print (or run through pager) the file where an object is defined. |
|
596 | 595 | |
|
597 | 596 | The file opens at the line where the object definition begins. IPython |
|
598 | 597 | will honor the environment variable PAGER if set, and otherwise will |
|
599 | 598 | do its best to print the file in a convenient form. |
|
600 | 599 | |
|
601 | 600 | If the given argument is not an object currently defined, IPython will |
|
602 | 601 | try to interpret it as a filename (automatically adding a .py extension |
|
603 | 602 | if needed). You can thus use %pfile as a syntax highlighting code |
|
604 | 603 | viewer.""" |
|
605 | 604 | |
|
606 | 605 | # first interpret argument as an object name |
|
607 | 606 | out = self._inspect('pfile',parameter_s) |
|
608 | 607 | # if not, try the input as a filename |
|
609 | 608 | if out == 'not found': |
|
610 | 609 | try: |
|
611 | 610 | filename = get_py_filename(parameter_s) |
|
612 | 611 | except IOError,msg: |
|
613 | 612 | print msg |
|
614 | 613 | return |
|
615 | 614 | page.page(self.shell.inspector.format(file(filename).read())) |
|
616 | 615 | |
|
617 | 616 | def magic_psearch(self, parameter_s=''): |
|
618 | 617 | """Search for object in namespaces by wildcard. |
|
619 | 618 | |
|
620 | 619 | %psearch [options] PATTERN [OBJECT TYPE] |
|
621 | 620 | |
|
622 | 621 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
623 | 622 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
624 | 623 | rest of the command line must be unchanged (options come first), so |
|
625 | 624 | for example the following forms are equivalent |
|
626 | 625 | |
|
627 | 626 | %psearch -i a* function |
|
628 | 627 | -i a* function? |
|
629 | 628 | ?-i a* function |
|
630 | 629 | |
|
631 | 630 | Arguments: |
|
632 | 631 | |
|
633 | 632 | PATTERN |
|
634 | 633 | |
|
635 | 634 | where PATTERN is a string containing * as a wildcard similar to its |
|
636 | 635 | use in a shell. The pattern is matched in all namespaces on the |
|
637 | 636 | search path. By default objects starting with a single _ are not |
|
638 | 637 | matched, many IPython generated objects have a single |
|
639 | 638 | underscore. The default is case insensitive matching. Matching is |
|
640 | 639 | also done on the attributes of objects and not only on the objects |
|
641 | 640 | in a module. |
|
642 | 641 | |
|
643 | 642 | [OBJECT TYPE] |
|
644 | 643 | |
|
645 | 644 | Is the name of a python type from the types module. The name is |
|
646 | 645 | given in lowercase without the ending type, ex. StringType is |
|
647 | 646 | written string. By adding a type here only objects matching the |
|
648 | 647 | given type are matched. Using all here makes the pattern match all |
|
649 | 648 | types (this is the default). |
|
650 | 649 | |
|
651 | 650 | Options: |
|
652 | 651 | |
|
653 | 652 | -a: makes the pattern match even objects whose names start with a |
|
654 | 653 | single underscore. These names are normally ommitted from the |
|
655 | 654 | search. |
|
656 | 655 | |
|
657 | 656 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
658 | 657 | these options is given, the default is read from your ipythonrc |
|
659 | 658 | file. The option name which sets this value is |
|
660 | 659 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
661 | 660 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
662 | 661 | search. |
|
663 | 662 | |
|
664 | 663 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
665 | 664 | specifiy can be searched in any of the following namespaces: |
|
666 | 665 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
667 | 666 | 'builtin' and 'user' are the search defaults. Note that you should |
|
668 | 667 | not use quotes when specifying namespaces. |
|
669 | 668 | |
|
670 | 669 | 'Builtin' contains the python module builtin, 'user' contains all |
|
671 | 670 | user data, 'alias' only contain the shell aliases and no python |
|
672 | 671 | objects, 'internal' contains objects used by IPython. The |
|
673 | 672 | 'user_global' namespace is only used by embedded IPython instances, |
|
674 | 673 | and it contains module-level globals. You can add namespaces to the |
|
675 | 674 | search with -s or exclude them with -e (these options can be given |
|
676 | 675 | more than once). |
|
677 | 676 | |
|
678 | 677 | Examples: |
|
679 | 678 | |
|
680 | 679 | %psearch a* -> objects beginning with an a |
|
681 | 680 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
682 | 681 | %psearch a* function -> all functions beginning with an a |
|
683 | 682 | %psearch re.e* -> objects beginning with an e in module re |
|
684 | 683 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
685 | 684 | %psearch r*.* string -> all strings in modules beginning with r |
|
686 | 685 | |
|
687 | 686 | Case sensitve search: |
|
688 | 687 | |
|
689 | 688 | %psearch -c a* list all object beginning with lower case a |
|
690 | 689 | |
|
691 | 690 | Show objects beginning with a single _: |
|
692 | 691 | |
|
693 | 692 | %psearch -a _* list objects beginning with a single underscore""" |
|
694 | 693 | try: |
|
695 | 694 | parameter_s = parameter_s.encode('ascii') |
|
696 | 695 | except UnicodeEncodeError: |
|
697 | 696 | print 'Python identifiers can only contain ascii characters.' |
|
698 | 697 | return |
|
699 | 698 | |
|
700 | 699 | # default namespaces to be searched |
|
701 | 700 | def_search = ['user','builtin'] |
|
702 | 701 | |
|
703 | 702 | # Process options/args |
|
704 | 703 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
705 | 704 | opt = opts.get |
|
706 | 705 | shell = self.shell |
|
707 | 706 | psearch = shell.inspector.psearch |
|
708 | 707 | |
|
709 | 708 | # select case options |
|
710 | 709 | if opts.has_key('i'): |
|
711 | 710 | ignore_case = True |
|
712 | 711 | elif opts.has_key('c'): |
|
713 | 712 | ignore_case = False |
|
714 | 713 | else: |
|
715 | 714 | ignore_case = not shell.wildcards_case_sensitive |
|
716 | 715 | |
|
717 | 716 | # Build list of namespaces to search from user options |
|
718 | 717 | def_search.extend(opt('s',[])) |
|
719 | 718 | ns_exclude = ns_exclude=opt('e',[]) |
|
720 | 719 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
721 | 720 | |
|
722 | 721 | # Call the actual search |
|
723 | 722 | try: |
|
724 | 723 | psearch(args,shell.ns_table,ns_search, |
|
725 | 724 | show_all=opt('a'),ignore_case=ignore_case) |
|
726 | 725 | except: |
|
727 | 726 | shell.showtraceback() |
|
728 | 727 | |
|
729 | 728 | @testdec.skip_doctest |
|
730 | 729 | def magic_who_ls(self, parameter_s=''): |
|
731 | 730 | """Return a sorted list of all interactive variables. |
|
732 | 731 | |
|
733 | 732 | If arguments are given, only variables of types matching these |
|
734 | 733 | arguments are returned. |
|
735 | 734 | |
|
736 | 735 | Examples |
|
737 | 736 | -------- |
|
738 | 737 | |
|
739 | 738 | Define two variables and list them with who_ls:: |
|
740 | 739 | |
|
741 | 740 | In [1]: alpha = 123 |
|
742 | 741 | |
|
743 | 742 | In [2]: beta = 'test' |
|
744 | 743 | |
|
745 | 744 | In [3]: %who_ls |
|
746 | 745 | Out[3]: ['alpha', 'beta'] |
|
747 | 746 | |
|
748 | 747 | In [4]: %who_ls int |
|
749 | 748 | Out[4]: ['alpha'] |
|
750 | 749 | |
|
751 | 750 | In [5]: %who_ls str |
|
752 | 751 | Out[5]: ['beta'] |
|
753 | 752 | """ |
|
754 | 753 | |
|
755 | 754 | user_ns = self.shell.user_ns |
|
756 | 755 | internal_ns = self.shell.internal_ns |
|
757 | 756 | user_ns_hidden = self.shell.user_ns_hidden |
|
758 | 757 | out = [ i for i in user_ns |
|
759 | 758 | if not i.startswith('_') \ |
|
760 | 759 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
761 | 760 | |
|
762 | 761 | typelist = parameter_s.split() |
|
763 | 762 | if typelist: |
|
764 | 763 | typeset = set(typelist) |
|
765 | 764 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
766 | 765 | |
|
767 | 766 | out.sort() |
|
768 | 767 | return out |
|
769 | 768 | |
|
770 | 769 | @testdec.skip_doctest |
|
771 | 770 | def magic_who(self, parameter_s=''): |
|
772 | 771 | """Print all interactive variables, with some minimal formatting. |
|
773 | 772 | |
|
774 | 773 | If any arguments are given, only variables whose type matches one of |
|
775 | 774 | these are printed. For example: |
|
776 | 775 | |
|
777 | 776 | %who function str |
|
778 | 777 | |
|
779 | 778 | will only list functions and strings, excluding all other types of |
|
780 | 779 | variables. To find the proper type names, simply use type(var) at a |
|
781 | 780 | command line to see how python prints type names. For example: |
|
782 | 781 | |
|
783 | 782 | In [1]: type('hello')\\ |
|
784 | 783 | Out[1]: <type 'str'> |
|
785 | 784 | |
|
786 | 785 | indicates that the type name for strings is 'str'. |
|
787 | 786 | |
|
788 | 787 | %who always excludes executed names loaded through your configuration |
|
789 | 788 | file and things which are internal to IPython. |
|
790 | 789 | |
|
791 | 790 | This is deliberate, as typically you may load many modules and the |
|
792 | 791 | purpose of %who is to show you only what you've manually defined. |
|
793 | 792 | |
|
794 | 793 | Examples |
|
795 | 794 | -------- |
|
796 | 795 | |
|
797 | 796 | Define two variables and list them with who:: |
|
798 | 797 | |
|
799 | 798 | In [1]: alpha = 123 |
|
800 | 799 | |
|
801 | 800 | In [2]: beta = 'test' |
|
802 | 801 | |
|
803 | 802 | In [3]: %who |
|
804 | 803 | alpha beta |
|
805 | 804 | |
|
806 | 805 | In [4]: %who int |
|
807 | 806 | alpha |
|
808 | 807 | |
|
809 | 808 | In [5]: %who str |
|
810 | 809 | beta |
|
811 | 810 | """ |
|
812 | 811 | |
|
813 | 812 | varlist = self.magic_who_ls(parameter_s) |
|
814 | 813 | if not varlist: |
|
815 | 814 | if parameter_s: |
|
816 | 815 | print 'No variables match your requested type.' |
|
817 | 816 | else: |
|
818 | 817 | print 'Interactive namespace is empty.' |
|
819 | 818 | return |
|
820 | 819 | |
|
821 | 820 | # if we have variables, move on... |
|
822 | 821 | count = 0 |
|
823 | 822 | for i in varlist: |
|
824 | 823 | print i+'\t', |
|
825 | 824 | count += 1 |
|
826 | 825 | if count > 8: |
|
827 | 826 | count = 0 |
|
828 | 827 | |
|
829 | 828 | |
|
830 | 829 | |
|
831 | 830 | @testdec.skip_doctest |
|
832 | 831 | def magic_whos(self, parameter_s=''): |
|
833 | 832 | """Like %who, but gives some extra information about each variable. |
|
834 | 833 | |
|
835 | 834 | The same type filtering of %who can be applied here. |
|
836 | 835 | |
|
837 | 836 | For all variables, the type is printed. Additionally it prints: |
|
838 | 837 | |
|
839 | 838 | - For {},[],(): their length. |
|
840 | 839 | |
|
841 | 840 | - For numpy arrays, a summary with shape, number of |
|
842 | 841 | elements, typecode and size in memory. |
|
843 | 842 | |
|
844 | 843 | - Everything else: a string representation, snipping their middle if |
|
845 | 844 | too long. |
|
846 | 845 | |
|
847 | 846 | Examples |
|
848 | 847 | -------- |
|
849 | 848 | |
|
850 | 849 | Define two variables and list them with whos:: |
|
851 | 850 | |
|
852 | 851 | In [1]: alpha = 123 |
|
853 | 852 | |
|
854 | 853 | In [2]: beta = 'test' |
|
855 | 854 | |
|
856 | 855 | In [3]: %whos |
|
857 | 856 | Variable Type Data/Info |
|
858 | 857 | -------------------------------- |
|
859 | 858 | alpha int 123 |
|
860 | 859 | beta str test |
|
861 | 860 | """ |
|
862 | 861 | |
|
863 | 862 | varnames = self.magic_who_ls(parameter_s) |
|
864 | 863 | if not varnames: |
|
865 | 864 | if parameter_s: |
|
866 | 865 | print 'No variables match your requested type.' |
|
867 | 866 | else: |
|
868 | 867 | print 'Interactive namespace is empty.' |
|
869 | 868 | return |
|
870 | 869 | |
|
871 | 870 | # if we have variables, move on... |
|
872 | 871 | |
|
873 | 872 | # for these types, show len() instead of data: |
|
874 | 873 | seq_types = ['dict', 'list', 'tuple'] |
|
875 | 874 | |
|
876 | 875 | # for numpy/Numeric arrays, display summary info |
|
877 | 876 | try: |
|
878 | 877 | import numpy |
|
879 | 878 | except ImportError: |
|
880 | 879 | ndarray_type = None |
|
881 | 880 | else: |
|
882 | 881 | ndarray_type = numpy.ndarray.__name__ |
|
883 | 882 | try: |
|
884 | 883 | import Numeric |
|
885 | 884 | except ImportError: |
|
886 | 885 | array_type = None |
|
887 | 886 | else: |
|
888 | 887 | array_type = Numeric.ArrayType.__name__ |
|
889 | 888 | |
|
890 | 889 | # Find all variable names and types so we can figure out column sizes |
|
891 | 890 | def get_vars(i): |
|
892 | 891 | return self.shell.user_ns[i] |
|
893 | 892 | |
|
894 | 893 | # some types are well known and can be shorter |
|
895 | 894 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
896 | 895 | def type_name(v): |
|
897 | 896 | tn = type(v).__name__ |
|
898 | 897 | return abbrevs.get(tn,tn) |
|
899 | 898 | |
|
900 | 899 | varlist = map(get_vars,varnames) |
|
901 | 900 | |
|
902 | 901 | typelist = [] |
|
903 | 902 | for vv in varlist: |
|
904 | 903 | tt = type_name(vv) |
|
905 | 904 | |
|
906 | 905 | if tt=='instance': |
|
907 | 906 | typelist.append( abbrevs.get(str(vv.__class__), |
|
908 | 907 | str(vv.__class__))) |
|
909 | 908 | else: |
|
910 | 909 | typelist.append(tt) |
|
911 | 910 | |
|
912 | 911 | # column labels and # of spaces as separator |
|
913 | 912 | varlabel = 'Variable' |
|
914 | 913 | typelabel = 'Type' |
|
915 | 914 | datalabel = 'Data/Info' |
|
916 | 915 | colsep = 3 |
|
917 | 916 | # variable format strings |
|
918 | 917 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
919 | 918 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
920 | 919 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
921 | 920 | # find the size of the columns to format the output nicely |
|
922 | 921 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
923 | 922 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
924 | 923 | # table header |
|
925 | 924 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
926 | 925 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
927 | 926 | # and the table itself |
|
928 | 927 | kb = 1024 |
|
929 | 928 | Mb = 1048576 # kb**2 |
|
930 | 929 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
931 | 930 | print itpl(vformat), |
|
932 | 931 | if vtype in seq_types: |
|
933 | 932 | print "n="+str(len(var)) |
|
934 | 933 | elif vtype in [array_type,ndarray_type]: |
|
935 | 934 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
936 | 935 | if vtype==ndarray_type: |
|
937 | 936 | # numpy |
|
938 | 937 | vsize = var.size |
|
939 | 938 | vbytes = vsize*var.itemsize |
|
940 | 939 | vdtype = var.dtype |
|
941 | 940 | else: |
|
942 | 941 | # Numeric |
|
943 | 942 | vsize = Numeric.size(var) |
|
944 | 943 | vbytes = vsize*var.itemsize() |
|
945 | 944 | vdtype = var.typecode() |
|
946 | 945 | |
|
947 | 946 | if vbytes < 100000: |
|
948 | 947 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
949 | 948 | else: |
|
950 | 949 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
951 | 950 | if vbytes < Mb: |
|
952 | 951 | print '(%s kb)' % (vbytes/kb,) |
|
953 | 952 | else: |
|
954 | 953 | print '(%s Mb)' % (vbytes/Mb,) |
|
955 | 954 | else: |
|
956 | 955 | try: |
|
957 | 956 | vstr = str(var) |
|
958 | 957 | except UnicodeEncodeError: |
|
959 | 958 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
960 | 959 | 'backslashreplace') |
|
961 | 960 | vstr = vstr.replace('\n','\\n') |
|
962 | 961 | if len(vstr) < 50: |
|
963 | 962 | print vstr |
|
964 | 963 | else: |
|
965 | 964 | printpl(vfmt_short) |
|
966 | 965 | |
|
967 | 966 | def magic_reset(self, parameter_s=''): |
|
968 | 967 | """Resets the namespace by removing all names defined by the user. |
|
969 | 968 | |
|
970 | 969 | Parameters |
|
971 | 970 | ---------- |
|
972 | 971 | -f : force reset without asking for confirmation. |
|
973 | 972 | |
|
974 | 973 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
975 | 974 | References to objects may be kept. By default (without this option), |
|
976 | 975 | we do a 'hard' reset, giving you a new session and removing all |
|
977 | 976 | references to objects from the current session. |
|
978 | 977 | |
|
979 | 978 | Examples |
|
980 | 979 | -------- |
|
981 | 980 | In [6]: a = 1 |
|
982 | 981 | |
|
983 | 982 | In [7]: a |
|
984 | 983 | Out[7]: 1 |
|
985 | 984 | |
|
986 | 985 | In [8]: 'a' in _ip.user_ns |
|
987 | 986 | Out[8]: True |
|
988 | 987 | |
|
989 | 988 | In [9]: %reset -f |
|
990 | 989 | |
|
991 | 990 | In [1]: 'a' in _ip.user_ns |
|
992 | 991 | Out[1]: False |
|
993 | 992 | """ |
|
994 | 993 | opts, args = self.parse_options(parameter_s,'sf') |
|
995 | 994 | if 'f' in opts: |
|
996 | 995 | ans = True |
|
997 | 996 | else: |
|
998 | 997 | ans = self.shell.ask_yes_no( |
|
999 | 998 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1000 | 999 | if not ans: |
|
1001 | 1000 | print 'Nothing done.' |
|
1002 | 1001 | return |
|
1003 | 1002 | |
|
1004 | 1003 | if 's' in opts: # Soft reset |
|
1005 | 1004 | user_ns = self.shell.user_ns |
|
1006 | 1005 | for i in self.magic_who_ls(): |
|
1007 | 1006 | del(user_ns[i]) |
|
1008 | 1007 | |
|
1009 | 1008 | else: # Hard reset |
|
1010 | 1009 | self.shell.reset(new_session = False) |
|
1011 | 1010 | |
|
1012 | 1011 | |
|
1013 | 1012 | |
|
1014 | 1013 | def magic_reset_selective(self, parameter_s=''): |
|
1015 | 1014 | """Resets the namespace by removing names defined by the user. |
|
1016 | 1015 | |
|
1017 | 1016 | Input/Output history are left around in case you need them. |
|
1018 | 1017 | |
|
1019 | 1018 | %reset_selective [-f] regex |
|
1020 | 1019 | |
|
1021 | 1020 | No action is taken if regex is not included |
|
1022 | 1021 | |
|
1023 | 1022 | Options |
|
1024 | 1023 | -f : force reset without asking for confirmation. |
|
1025 | 1024 | |
|
1026 | 1025 | Examples |
|
1027 | 1026 | -------- |
|
1028 | 1027 | |
|
1029 | 1028 | We first fully reset the namespace so your output looks identical to |
|
1030 | 1029 | this example for pedagogical reasons; in practice you do not need a |
|
1031 | 1030 | full reset. |
|
1032 | 1031 | |
|
1033 | 1032 | In [1]: %reset -f |
|
1034 | 1033 | |
|
1035 | 1034 | Now, with a clean namespace we can make a few variables and use |
|
1036 | 1035 | %reset_selective to only delete names that match our regexp: |
|
1037 | 1036 | |
|
1038 | 1037 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
1039 | 1038 | |
|
1040 | 1039 | In [3]: who_ls |
|
1041 | 1040 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
1042 | 1041 | |
|
1043 | 1042 | In [4]: %reset_selective -f b[2-3]m |
|
1044 | 1043 | |
|
1045 | 1044 | In [5]: who_ls |
|
1046 | 1045 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1047 | 1046 | |
|
1048 | 1047 | In [6]: %reset_selective -f d |
|
1049 | 1048 | |
|
1050 | 1049 | In [7]: who_ls |
|
1051 | 1050 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
1052 | 1051 | |
|
1053 | 1052 | In [8]: %reset_selective -f c |
|
1054 | 1053 | |
|
1055 | 1054 | In [9]: who_ls |
|
1056 | 1055 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1057 | 1056 | |
|
1058 | 1057 | In [10]: %reset_selective -f b |
|
1059 | 1058 | |
|
1060 | 1059 | In [11]: who_ls |
|
1061 | 1060 | Out[11]: ['a'] |
|
1062 | 1061 | """ |
|
1063 | 1062 | |
|
1064 | 1063 | opts, regex = self.parse_options(parameter_s,'f') |
|
1065 | 1064 | |
|
1066 | 1065 | if opts.has_key('f'): |
|
1067 | 1066 | ans = True |
|
1068 | 1067 | else: |
|
1069 | 1068 | ans = self.shell.ask_yes_no( |
|
1070 | 1069 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1071 | 1070 | if not ans: |
|
1072 | 1071 | print 'Nothing done.' |
|
1073 | 1072 | return |
|
1074 | 1073 | user_ns = self.shell.user_ns |
|
1075 | 1074 | if not regex: |
|
1076 | 1075 | print 'No regex pattern specified. Nothing done.' |
|
1077 | 1076 | return |
|
1078 | 1077 | else: |
|
1079 | 1078 | try: |
|
1080 | 1079 | m = re.compile(regex) |
|
1081 | 1080 | except TypeError: |
|
1082 | 1081 | raise TypeError('regex must be a string or compiled pattern') |
|
1083 | 1082 | for i in self.magic_who_ls(): |
|
1084 | 1083 | if m.search(i): |
|
1085 | 1084 | del(user_ns[i]) |
|
1086 | 1085 | |
|
1087 | 1086 | def magic_logstart(self,parameter_s=''): |
|
1088 | 1087 | """Start logging anywhere in a session. |
|
1089 | 1088 | |
|
1090 | 1089 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1091 | 1090 | |
|
1092 | 1091 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1093 | 1092 | current directory, in 'rotate' mode (see below). |
|
1094 | 1093 | |
|
1095 | 1094 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1096 | 1095 | history up to that point and then continues logging. |
|
1097 | 1096 | |
|
1098 | 1097 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1099 | 1098 | of (note that the modes are given unquoted):\\ |
|
1100 | 1099 | append: well, that says it.\\ |
|
1101 | 1100 | backup: rename (if exists) to name~ and start name.\\ |
|
1102 | 1101 | global: single logfile in your home dir, appended to.\\ |
|
1103 | 1102 | over : overwrite existing log.\\ |
|
1104 | 1103 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1105 | 1104 | |
|
1106 | 1105 | Options: |
|
1107 | 1106 | |
|
1108 | 1107 | -o: log also IPython's output. In this mode, all commands which |
|
1109 | 1108 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1110 | 1109 | their corresponding input line. The output lines are always |
|
1111 | 1110 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1112 | 1111 | Python code. |
|
1113 | 1112 | |
|
1114 | 1113 | Since this marker is always the same, filtering only the output from |
|
1115 | 1114 | a log is very easy, using for example a simple awk call: |
|
1116 | 1115 | |
|
1117 | 1116 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1118 | 1117 | |
|
1119 | 1118 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1120 | 1119 | input, so that user lines are logged in their final form, converted |
|
1121 | 1120 | into valid Python. For example, %Exit is logged as |
|
1122 | 1121 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1123 | 1122 | exactly as typed, with no transformations applied. |
|
1124 | 1123 | |
|
1125 | 1124 | -t: put timestamps before each input line logged (these are put in |
|
1126 | 1125 | comments).""" |
|
1127 | 1126 | |
|
1128 | 1127 | opts,par = self.parse_options(parameter_s,'ort') |
|
1129 | 1128 | log_output = 'o' in opts |
|
1130 | 1129 | log_raw_input = 'r' in opts |
|
1131 | 1130 | timestamp = 't' in opts |
|
1132 | 1131 | |
|
1133 | 1132 | logger = self.shell.logger |
|
1134 | 1133 | |
|
1135 | 1134 | # if no args are given, the defaults set in the logger constructor by |
|
1136 | 1135 | # ipytohn remain valid |
|
1137 | 1136 | if par: |
|
1138 | 1137 | try: |
|
1139 | 1138 | logfname,logmode = par.split() |
|
1140 | 1139 | except: |
|
1141 | 1140 | logfname = par |
|
1142 | 1141 | logmode = 'backup' |
|
1143 | 1142 | else: |
|
1144 | 1143 | logfname = logger.logfname |
|
1145 | 1144 | logmode = logger.logmode |
|
1146 | 1145 | # put logfname into rc struct as if it had been called on the command |
|
1147 | 1146 | # line, so it ends up saved in the log header Save it in case we need |
|
1148 | 1147 | # to restore it... |
|
1149 | 1148 | old_logfile = self.shell.logfile |
|
1150 | 1149 | if logfname: |
|
1151 | 1150 | logfname = os.path.expanduser(logfname) |
|
1152 | 1151 | self.shell.logfile = logfname |
|
1153 | 1152 | |
|
1154 | 1153 | loghead = '# IPython log file\n\n' |
|
1155 | 1154 | try: |
|
1156 | 1155 | started = logger.logstart(logfname,loghead,logmode, |
|
1157 | 1156 | log_output,timestamp,log_raw_input) |
|
1158 | 1157 | except: |
|
1159 | 1158 | self.shell.logfile = old_logfile |
|
1160 | 1159 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1161 | 1160 | else: |
|
1162 | 1161 | # log input history up to this point, optionally interleaving |
|
1163 | 1162 | # output if requested |
|
1164 | 1163 | |
|
1165 | 1164 | if timestamp: |
|
1166 | 1165 | # disable timestamping for the previous history, since we've |
|
1167 | 1166 | # lost those already (no time machine here). |
|
1168 | 1167 | logger.timestamp = False |
|
1169 | 1168 | |
|
1170 | 1169 | if log_raw_input: |
|
1171 | 1170 | input_hist = self.shell.history_manager.input_hist_raw |
|
1172 | 1171 | else: |
|
1173 | 1172 | input_hist = self.shell.history_manager.input_hist_parsed |
|
1174 | 1173 | |
|
1175 | 1174 | if log_output: |
|
1176 | 1175 | log_write = logger.log_write |
|
1177 | 1176 | output_hist = self.shell.history_manager.output_hist |
|
1178 | 1177 | for n in range(1,len(input_hist)-1): |
|
1179 | 1178 | log_write(input_hist[n].rstrip()) |
|
1180 | 1179 | if n in output_hist: |
|
1181 | 1180 | log_write(repr(output_hist[n]),'output') |
|
1182 | 1181 | else: |
|
1183 | 1182 | logger.log_write(''.join(input_hist[1:])) |
|
1184 | 1183 | if timestamp: |
|
1185 | 1184 | # re-enable timestamping |
|
1186 | 1185 | logger.timestamp = True |
|
1187 | 1186 | |
|
1188 | 1187 | print ('Activating auto-logging. ' |
|
1189 | 1188 | 'Current session state plus future input saved.') |
|
1190 | 1189 | logger.logstate() |
|
1191 | 1190 | |
|
1192 | 1191 | def magic_logstop(self,parameter_s=''): |
|
1193 | 1192 | """Fully stop logging and close log file. |
|
1194 | 1193 | |
|
1195 | 1194 | In order to start logging again, a new %logstart call needs to be made, |
|
1196 | 1195 | possibly (though not necessarily) with a new filename, mode and other |
|
1197 | 1196 | options.""" |
|
1198 | 1197 | self.logger.logstop() |
|
1199 | 1198 | |
|
1200 | 1199 | def magic_logoff(self,parameter_s=''): |
|
1201 | 1200 | """Temporarily stop logging. |
|
1202 | 1201 | |
|
1203 | 1202 | You must have previously started logging.""" |
|
1204 | 1203 | self.shell.logger.switch_log(0) |
|
1205 | 1204 | |
|
1206 | 1205 | def magic_logon(self,parameter_s=''): |
|
1207 | 1206 | """Restart logging. |
|
1208 | 1207 | |
|
1209 | 1208 | This function is for restarting logging which you've temporarily |
|
1210 | 1209 | stopped with %logoff. For starting logging for the first time, you |
|
1211 | 1210 | must use the %logstart function, which allows you to specify an |
|
1212 | 1211 | optional log filename.""" |
|
1213 | 1212 | |
|
1214 | 1213 | self.shell.logger.switch_log(1) |
|
1215 | 1214 | |
|
1216 | 1215 | def magic_logstate(self,parameter_s=''): |
|
1217 | 1216 | """Print the status of the logging system.""" |
|
1218 | 1217 | |
|
1219 | 1218 | self.shell.logger.logstate() |
|
1220 | 1219 | |
|
1221 | 1220 | def magic_pdb(self, parameter_s=''): |
|
1222 | 1221 | """Control the automatic calling of the pdb interactive debugger. |
|
1223 | 1222 | |
|
1224 | 1223 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1225 | 1224 | argument it works as a toggle. |
|
1226 | 1225 | |
|
1227 | 1226 | When an exception is triggered, IPython can optionally call the |
|
1228 | 1227 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1229 | 1228 | this feature on and off. |
|
1230 | 1229 | |
|
1231 | 1230 | The initial state of this feature is set in your ipythonrc |
|
1232 | 1231 | configuration file (the variable is called 'pdb'). |
|
1233 | 1232 | |
|
1234 | 1233 | If you want to just activate the debugger AFTER an exception has fired, |
|
1235 | 1234 | without having to type '%pdb on' and rerunning your code, you can use |
|
1236 | 1235 | the %debug magic.""" |
|
1237 | 1236 | |
|
1238 | 1237 | par = parameter_s.strip().lower() |
|
1239 | 1238 | |
|
1240 | 1239 | if par: |
|
1241 | 1240 | try: |
|
1242 | 1241 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1243 | 1242 | except KeyError: |
|
1244 | 1243 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1245 | 1244 | 'or nothing for a toggle.') |
|
1246 | 1245 | return |
|
1247 | 1246 | else: |
|
1248 | 1247 | # toggle |
|
1249 | 1248 | new_pdb = not self.shell.call_pdb |
|
1250 | 1249 | |
|
1251 | 1250 | # set on the shell |
|
1252 | 1251 | self.shell.call_pdb = new_pdb |
|
1253 | 1252 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1254 | 1253 | |
|
1255 | 1254 | def magic_debug(self, parameter_s=''): |
|
1256 | 1255 | """Activate the interactive debugger in post-mortem mode. |
|
1257 | 1256 | |
|
1258 | 1257 | If an exception has just occurred, this lets you inspect its stack |
|
1259 | 1258 | frames interactively. Note that this will always work only on the last |
|
1260 | 1259 | traceback that occurred, so you must call this quickly after an |
|
1261 | 1260 | exception that you wish to inspect has fired, because if another one |
|
1262 | 1261 | occurs, it clobbers the previous one. |
|
1263 | 1262 | |
|
1264 | 1263 | If you want IPython to automatically do this on every exception, see |
|
1265 | 1264 | the %pdb magic for more details. |
|
1266 | 1265 | """ |
|
1267 | 1266 | self.shell.debugger(force=True) |
|
1268 | 1267 | |
|
1269 | 1268 | @testdec.skip_doctest |
|
1270 | 1269 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1271 | 1270 | opts=None,arg_lst=None,prog_ns=None): |
|
1272 | 1271 | |
|
1273 | 1272 | """Run a statement through the python code profiler. |
|
1274 | 1273 | |
|
1275 | 1274 | Usage: |
|
1276 | 1275 | %prun [options] statement |
|
1277 | 1276 | |
|
1278 | 1277 | The given statement (which doesn't require quote marks) is run via the |
|
1279 | 1278 | python profiler in a manner similar to the profile.run() function. |
|
1280 | 1279 | Namespaces are internally managed to work correctly; profile.run |
|
1281 | 1280 | cannot be used in IPython because it makes certain assumptions about |
|
1282 | 1281 | namespaces which do not hold under IPython. |
|
1283 | 1282 | |
|
1284 | 1283 | Options: |
|
1285 | 1284 | |
|
1286 | 1285 | -l <limit>: you can place restrictions on what or how much of the |
|
1287 | 1286 | profile gets printed. The limit value can be: |
|
1288 | 1287 | |
|
1289 | 1288 | * A string: only information for function names containing this string |
|
1290 | 1289 | is printed. |
|
1291 | 1290 | |
|
1292 | 1291 | * An integer: only these many lines are printed. |
|
1293 | 1292 | |
|
1294 | 1293 | * A float (between 0 and 1): this fraction of the report is printed |
|
1295 | 1294 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1296 | 1295 | |
|
1297 | 1296 | You can combine several limits with repeated use of the option. For |
|
1298 | 1297 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1299 | 1298 | information about class constructors. |
|
1300 | 1299 | |
|
1301 | 1300 | -r: return the pstats.Stats object generated by the profiling. This |
|
1302 | 1301 | object has all the information about the profile in it, and you can |
|
1303 | 1302 | later use it for further analysis or in other functions. |
|
1304 | 1303 | |
|
1305 | 1304 | -s <key>: sort profile by given key. You can provide more than one key |
|
1306 | 1305 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1307 | 1306 | default sorting key is 'time'. |
|
1308 | 1307 | |
|
1309 | 1308 | The following is copied verbatim from the profile documentation |
|
1310 | 1309 | referenced below: |
|
1311 | 1310 | |
|
1312 | 1311 | When more than one key is provided, additional keys are used as |
|
1313 | 1312 | secondary criteria when the there is equality in all keys selected |
|
1314 | 1313 | before them. |
|
1315 | 1314 | |
|
1316 | 1315 | Abbreviations can be used for any key names, as long as the |
|
1317 | 1316 | abbreviation is unambiguous. The following are the keys currently |
|
1318 | 1317 | defined: |
|
1319 | 1318 | |
|
1320 | 1319 | Valid Arg Meaning |
|
1321 | 1320 | "calls" call count |
|
1322 | 1321 | "cumulative" cumulative time |
|
1323 | 1322 | "file" file name |
|
1324 | 1323 | "module" file name |
|
1325 | 1324 | "pcalls" primitive call count |
|
1326 | 1325 | "line" line number |
|
1327 | 1326 | "name" function name |
|
1328 | 1327 | "nfl" name/file/line |
|
1329 | 1328 | "stdname" standard name |
|
1330 | 1329 | "time" internal time |
|
1331 | 1330 | |
|
1332 | 1331 | Note that all sorts on statistics are in descending order (placing |
|
1333 | 1332 | most time consuming items first), where as name, file, and line number |
|
1334 | 1333 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1335 | 1334 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1336 | 1335 | sort of the name as printed, which means that the embedded line |
|
1337 | 1336 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1338 | 1337 | would (if the file names were the same) appear in the string order |
|
1339 | 1338 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1340 | 1339 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1341 | 1340 | sort_stats("name", "file", "line"). |
|
1342 | 1341 | |
|
1343 | 1342 | -T <filename>: save profile results as shown on screen to a text |
|
1344 | 1343 | file. The profile is still shown on screen. |
|
1345 | 1344 | |
|
1346 | 1345 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1347 | 1346 | filename. This data is in a format understod by the pstats module, and |
|
1348 | 1347 | is generated by a call to the dump_stats() method of profile |
|
1349 | 1348 | objects. The profile is still shown on screen. |
|
1350 | 1349 | |
|
1351 | 1350 | If you want to run complete programs under the profiler's control, use |
|
1352 | 1351 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1353 | 1352 | contains profiler specific options as described here. |
|
1354 | 1353 | |
|
1355 | 1354 | You can read the complete documentation for the profile module with:: |
|
1356 | 1355 | |
|
1357 | 1356 | In [1]: import profile; profile.help() |
|
1358 | 1357 | """ |
|
1359 | 1358 | |
|
1360 | 1359 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1361 | 1360 | # protect user quote marks |
|
1362 | 1361 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1363 | 1362 | |
|
1364 | 1363 | if user_mode: # regular user call |
|
1365 | 1364 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1366 | 1365 | list_all=1) |
|
1367 | 1366 | namespace = self.shell.user_ns |
|
1368 | 1367 | else: # called to run a program by %run -p |
|
1369 | 1368 | try: |
|
1370 | 1369 | filename = get_py_filename(arg_lst[0]) |
|
1371 | 1370 | except IOError,msg: |
|
1372 | 1371 | error(msg) |
|
1373 | 1372 | return |
|
1374 | 1373 | |
|
1375 | 1374 | arg_str = 'execfile(filename,prog_ns)' |
|
1376 | 1375 | namespace = locals() |
|
1377 | 1376 | |
|
1378 | 1377 | opts.merge(opts_def) |
|
1379 | 1378 | |
|
1380 | 1379 | prof = profile.Profile() |
|
1381 | 1380 | try: |
|
1382 | 1381 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1383 | 1382 | sys_exit = '' |
|
1384 | 1383 | except SystemExit: |
|
1385 | 1384 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1386 | 1385 | |
|
1387 | 1386 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1388 | 1387 | |
|
1389 | 1388 | lims = opts.l |
|
1390 | 1389 | if lims: |
|
1391 | 1390 | lims = [] # rebuild lims with ints/floats/strings |
|
1392 | 1391 | for lim in opts.l: |
|
1393 | 1392 | try: |
|
1394 | 1393 | lims.append(int(lim)) |
|
1395 | 1394 | except ValueError: |
|
1396 | 1395 | try: |
|
1397 | 1396 | lims.append(float(lim)) |
|
1398 | 1397 | except ValueError: |
|
1399 | 1398 | lims.append(lim) |
|
1400 | 1399 | |
|
1401 | 1400 | # Trap output. |
|
1402 | 1401 | stdout_trap = StringIO() |
|
1403 | 1402 | |
|
1404 | 1403 | if hasattr(stats,'stream'): |
|
1405 | 1404 | # In newer versions of python, the stats object has a 'stream' |
|
1406 | 1405 | # attribute to write into. |
|
1407 | 1406 | stats.stream = stdout_trap |
|
1408 | 1407 | stats.print_stats(*lims) |
|
1409 | 1408 | else: |
|
1410 | 1409 | # For older versions, we manually redirect stdout during printing |
|
1411 | 1410 | sys_stdout = sys.stdout |
|
1412 | 1411 | try: |
|
1413 | 1412 | sys.stdout = stdout_trap |
|
1414 | 1413 | stats.print_stats(*lims) |
|
1415 | 1414 | finally: |
|
1416 | 1415 | sys.stdout = sys_stdout |
|
1417 | 1416 | |
|
1418 | 1417 | output = stdout_trap.getvalue() |
|
1419 | 1418 | output = output.rstrip() |
|
1420 | 1419 | |
|
1421 | 1420 | page.page(output) |
|
1422 | 1421 | print sys_exit, |
|
1423 | 1422 | |
|
1424 | 1423 | dump_file = opts.D[0] |
|
1425 | 1424 | text_file = opts.T[0] |
|
1426 | 1425 | if dump_file: |
|
1427 | 1426 | prof.dump_stats(dump_file) |
|
1428 | 1427 | print '\n*** Profile stats marshalled to file',\ |
|
1429 | 1428 | `dump_file`+'.',sys_exit |
|
1430 | 1429 | if text_file: |
|
1431 | 1430 | pfile = file(text_file,'w') |
|
1432 | 1431 | pfile.write(output) |
|
1433 | 1432 | pfile.close() |
|
1434 | 1433 | print '\n*** Profile printout saved to text file',\ |
|
1435 | 1434 | `text_file`+'.',sys_exit |
|
1436 | 1435 | |
|
1437 | 1436 | if opts.has_key('r'): |
|
1438 | 1437 | return stats |
|
1439 | 1438 | else: |
|
1440 | 1439 | return None |
|
1441 | 1440 | |
|
1442 | 1441 | @testdec.skip_doctest |
|
1443 | 1442 | def magic_run(self, parameter_s ='',runner=None, |
|
1444 | 1443 | file_finder=get_py_filename): |
|
1445 | 1444 | """Run the named file inside IPython as a program. |
|
1446 | 1445 | |
|
1447 | 1446 | Usage:\\ |
|
1448 | 1447 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1449 | 1448 | |
|
1450 | 1449 | Parameters after the filename are passed as command-line arguments to |
|
1451 | 1450 | the program (put in sys.argv). Then, control returns to IPython's |
|
1452 | 1451 | prompt. |
|
1453 | 1452 | |
|
1454 | 1453 | This is similar to running at a system prompt:\\ |
|
1455 | 1454 | $ python file args\\ |
|
1456 | 1455 | but with the advantage of giving you IPython's tracebacks, and of |
|
1457 | 1456 | loading all variables into your interactive namespace for further use |
|
1458 | 1457 | (unless -p is used, see below). |
|
1459 | 1458 | |
|
1460 | 1459 | The file is executed in a namespace initially consisting only of |
|
1461 | 1460 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1462 | 1461 | sees its environment as if it were being run as a stand-alone program |
|
1463 | 1462 | (except for sharing global objects such as previously imported |
|
1464 | 1463 | modules). But after execution, the IPython interactive namespace gets |
|
1465 | 1464 | updated with all variables defined in the program (except for __name__ |
|
1466 | 1465 | and sys.argv). This allows for very convenient loading of code for |
|
1467 | 1466 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1468 | 1467 | |
|
1469 | 1468 | Options: |
|
1470 | 1469 | |
|
1471 | 1470 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1472 | 1471 | without extension (as python does under import). This allows running |
|
1473 | 1472 | scripts and reloading the definitions in them without calling code |
|
1474 | 1473 | protected by an ' if __name__ == "__main__" ' clause. |
|
1475 | 1474 | |
|
1476 | 1475 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1477 | 1476 | is useful if you are experimenting with code written in a text editor |
|
1478 | 1477 | which depends on variables defined interactively. |
|
1479 | 1478 | |
|
1480 | 1479 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1481 | 1480 | being run. This is particularly useful if IPython is being used to |
|
1482 | 1481 | run unittests, which always exit with a sys.exit() call. In such |
|
1483 | 1482 | cases you are interested in the output of the test results, not in |
|
1484 | 1483 | seeing a traceback of the unittest module. |
|
1485 | 1484 | |
|
1486 | 1485 | -t: print timing information at the end of the run. IPython will give |
|
1487 | 1486 | you an estimated CPU time consumption for your script, which under |
|
1488 | 1487 | Unix uses the resource module to avoid the wraparound problems of |
|
1489 | 1488 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1490 | 1489 | is also given (for Windows platforms this is reported as 0.0). |
|
1491 | 1490 | |
|
1492 | 1491 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1493 | 1492 | must be an integer indicating how many times you want the script to |
|
1494 | 1493 | run. The final timing report will include total and per run results. |
|
1495 | 1494 | |
|
1496 | 1495 | For example (testing the script uniq_stable.py): |
|
1497 | 1496 | |
|
1498 | 1497 | In [1]: run -t uniq_stable |
|
1499 | 1498 | |
|
1500 | 1499 | IPython CPU timings (estimated):\\ |
|
1501 | 1500 | User : 0.19597 s.\\ |
|
1502 | 1501 | System: 0.0 s.\\ |
|
1503 | 1502 | |
|
1504 | 1503 | In [2]: run -t -N5 uniq_stable |
|
1505 | 1504 | |
|
1506 | 1505 | IPython CPU timings (estimated):\\ |
|
1507 | 1506 | Total runs performed: 5\\ |
|
1508 | 1507 | Times : Total Per run\\ |
|
1509 | 1508 | User : 0.910862 s, 0.1821724 s.\\ |
|
1510 | 1509 | System: 0.0 s, 0.0 s. |
|
1511 | 1510 | |
|
1512 | 1511 | -d: run your program under the control of pdb, the Python debugger. |
|
1513 | 1512 | This allows you to execute your program step by step, watch variables, |
|
1514 | 1513 | etc. Internally, what IPython does is similar to calling: |
|
1515 | 1514 | |
|
1516 | 1515 | pdb.run('execfile("YOURFILENAME")') |
|
1517 | 1516 | |
|
1518 | 1517 | with a breakpoint set on line 1 of your file. You can change the line |
|
1519 | 1518 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1520 | 1519 | (where N must be an integer). For example: |
|
1521 | 1520 | |
|
1522 | 1521 | %run -d -b40 myscript |
|
1523 | 1522 | |
|
1524 | 1523 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1525 | 1524 | the first breakpoint must be set on a line which actually does |
|
1526 | 1525 | something (not a comment or docstring) for it to stop execution. |
|
1527 | 1526 | |
|
1528 | 1527 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1529 | 1528 | first enter 'c' (without qoutes) to start execution up to the first |
|
1530 | 1529 | breakpoint. |
|
1531 | 1530 | |
|
1532 | 1531 | Entering 'help' gives information about the use of the debugger. You |
|
1533 | 1532 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1534 | 1533 | at a prompt. |
|
1535 | 1534 | |
|
1536 | 1535 | -p: run program under the control of the Python profiler module (which |
|
1537 | 1536 | prints a detailed report of execution times, function calls, etc). |
|
1538 | 1537 | |
|
1539 | 1538 | You can pass other options after -p which affect the behavior of the |
|
1540 | 1539 | profiler itself. See the docs for %prun for details. |
|
1541 | 1540 | |
|
1542 | 1541 | In this mode, the program's variables do NOT propagate back to the |
|
1543 | 1542 | IPython interactive namespace (because they remain in the namespace |
|
1544 | 1543 | where the profiler executes them). |
|
1545 | 1544 | |
|
1546 | 1545 | Internally this triggers a call to %prun, see its documentation for |
|
1547 | 1546 | details on the options available specifically for profiling. |
|
1548 | 1547 | |
|
1549 | 1548 | There is one special usage for which the text above doesn't apply: |
|
1550 | 1549 | if the filename ends with .ipy, the file is run as ipython script, |
|
1551 | 1550 | just as if the commands were written on IPython prompt. |
|
1552 | 1551 | """ |
|
1553 | 1552 | |
|
1554 | 1553 | # get arguments and set sys.argv for program to be run. |
|
1555 | 1554 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1556 | 1555 | mode='list',list_all=1) |
|
1557 | 1556 | |
|
1558 | 1557 | try: |
|
1559 | 1558 | filename = file_finder(arg_lst[0]) |
|
1560 | 1559 | except IndexError: |
|
1561 | 1560 | warn('you must provide at least a filename.') |
|
1562 | 1561 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1563 | 1562 | return |
|
1564 | 1563 | except IOError,msg: |
|
1565 | 1564 | error(msg) |
|
1566 | 1565 | return |
|
1567 | 1566 | |
|
1568 | 1567 | if filename.lower().endswith('.ipy'): |
|
1569 | 1568 | self.shell.safe_execfile_ipy(filename) |
|
1570 | 1569 | return |
|
1571 | 1570 | |
|
1572 | 1571 | # Control the response to exit() calls made by the script being run |
|
1573 | 1572 | exit_ignore = opts.has_key('e') |
|
1574 | 1573 | |
|
1575 | 1574 | # Make sure that the running script gets a proper sys.argv as if it |
|
1576 | 1575 | # were run from a system shell. |
|
1577 | 1576 | save_argv = sys.argv # save it for later restoring |
|
1578 | 1577 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1579 | 1578 | |
|
1580 | 1579 | if opts.has_key('i'): |
|
1581 | 1580 | # Run in user's interactive namespace |
|
1582 | 1581 | prog_ns = self.shell.user_ns |
|
1583 | 1582 | __name__save = self.shell.user_ns['__name__'] |
|
1584 | 1583 | prog_ns['__name__'] = '__main__' |
|
1585 | 1584 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1586 | 1585 | else: |
|
1587 | 1586 | # Run in a fresh, empty namespace |
|
1588 | 1587 | if opts.has_key('n'): |
|
1589 | 1588 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1590 | 1589 | else: |
|
1591 | 1590 | name = '__main__' |
|
1592 | 1591 | |
|
1593 | 1592 | main_mod = self.shell.new_main_mod() |
|
1594 | 1593 | prog_ns = main_mod.__dict__ |
|
1595 | 1594 | prog_ns['__name__'] = name |
|
1596 | 1595 | |
|
1597 | 1596 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1598 | 1597 | # set the __file__ global in the script's namespace |
|
1599 | 1598 | prog_ns['__file__'] = filename |
|
1600 | 1599 | |
|
1601 | 1600 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1602 | 1601 | # that, if we overwrite __main__, we replace it at the end |
|
1603 | 1602 | main_mod_name = prog_ns['__name__'] |
|
1604 | 1603 | |
|
1605 | 1604 | if main_mod_name == '__main__': |
|
1606 | 1605 | restore_main = sys.modules['__main__'] |
|
1607 | 1606 | else: |
|
1608 | 1607 | restore_main = False |
|
1609 | 1608 | |
|
1610 | 1609 | # This needs to be undone at the end to prevent holding references to |
|
1611 | 1610 | # every single object ever created. |
|
1612 | 1611 | sys.modules[main_mod_name] = main_mod |
|
1613 | 1612 | |
|
1614 | 1613 | try: |
|
1615 | 1614 | stats = None |
|
1616 | 1615 | with self.readline_no_record: |
|
1617 | 1616 | if opts.has_key('p'): |
|
1618 | 1617 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1619 | 1618 | else: |
|
1620 | 1619 | if opts.has_key('d'): |
|
1621 | 1620 | deb = debugger.Pdb(self.shell.colors) |
|
1622 | 1621 | # reset Breakpoint state, which is moronically kept |
|
1623 | 1622 | # in a class |
|
1624 | 1623 | bdb.Breakpoint.next = 1 |
|
1625 | 1624 | bdb.Breakpoint.bplist = {} |
|
1626 | 1625 | bdb.Breakpoint.bpbynumber = [None] |
|
1627 | 1626 | # Set an initial breakpoint to stop execution |
|
1628 | 1627 | maxtries = 10 |
|
1629 | 1628 | bp = int(opts.get('b',[1])[0]) |
|
1630 | 1629 | checkline = deb.checkline(filename,bp) |
|
1631 | 1630 | if not checkline: |
|
1632 | 1631 | for bp in range(bp+1,bp+maxtries+1): |
|
1633 | 1632 | if deb.checkline(filename,bp): |
|
1634 | 1633 | break |
|
1635 | 1634 | else: |
|
1636 | 1635 | msg = ("\nI failed to find a valid line to set " |
|
1637 | 1636 | "a breakpoint\n" |
|
1638 | 1637 | "after trying up to line: %s.\n" |
|
1639 | 1638 | "Please set a valid breakpoint manually " |
|
1640 | 1639 | "with the -b option." % bp) |
|
1641 | 1640 | error(msg) |
|
1642 | 1641 | return |
|
1643 | 1642 | # if we find a good linenumber, set the breakpoint |
|
1644 | 1643 | deb.do_break('%s:%s' % (filename,bp)) |
|
1645 | 1644 | # Start file run |
|
1646 | 1645 | print "NOTE: Enter 'c' at the", |
|
1647 | 1646 | print "%s prompt to start your script." % deb.prompt |
|
1648 | 1647 | try: |
|
1649 | 1648 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1650 | 1649 | |
|
1651 | 1650 | except: |
|
1652 | 1651 | etype, value, tb = sys.exc_info() |
|
1653 | 1652 | # Skip three frames in the traceback: the %run one, |
|
1654 | 1653 | # one inside bdb.py, and the command-line typed by the |
|
1655 | 1654 | # user (run by exec in pdb itself). |
|
1656 | 1655 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1657 | 1656 | else: |
|
1658 | 1657 | if runner is None: |
|
1659 | 1658 | runner = self.shell.safe_execfile |
|
1660 | 1659 | if opts.has_key('t'): |
|
1661 | 1660 | # timed execution |
|
1662 | 1661 | try: |
|
1663 | 1662 | nruns = int(opts['N'][0]) |
|
1664 | 1663 | if nruns < 1: |
|
1665 | 1664 | error('Number of runs must be >=1') |
|
1666 | 1665 | return |
|
1667 | 1666 | except (KeyError): |
|
1668 | 1667 | nruns = 1 |
|
1669 | 1668 | if nruns == 1: |
|
1670 | 1669 | t0 = clock2() |
|
1671 | 1670 | runner(filename,prog_ns,prog_ns, |
|
1672 | 1671 | exit_ignore=exit_ignore) |
|
1673 | 1672 | t1 = clock2() |
|
1674 | 1673 | t_usr = t1[0]-t0[0] |
|
1675 | 1674 | t_sys = t1[1]-t0[1] |
|
1676 | 1675 | print "\nIPython CPU timings (estimated):" |
|
1677 | 1676 | print " User : %10s s." % t_usr |
|
1678 | 1677 | print " System: %10s s." % t_sys |
|
1679 | 1678 | else: |
|
1680 | 1679 | runs = range(nruns) |
|
1681 | 1680 | t0 = clock2() |
|
1682 | 1681 | for nr in runs: |
|
1683 | 1682 | runner(filename,prog_ns,prog_ns, |
|
1684 | 1683 | exit_ignore=exit_ignore) |
|
1685 | 1684 | t1 = clock2() |
|
1686 | 1685 | t_usr = t1[0]-t0[0] |
|
1687 | 1686 | t_sys = t1[1]-t0[1] |
|
1688 | 1687 | print "\nIPython CPU timings (estimated):" |
|
1689 | 1688 | print "Total runs performed:",nruns |
|
1690 | 1689 | print " Times : %10s %10s" % ('Total','Per run') |
|
1691 | 1690 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1692 | 1691 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1693 | 1692 | |
|
1694 | 1693 | else: |
|
1695 | 1694 | # regular execution |
|
1696 | 1695 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1697 | 1696 | |
|
1698 | 1697 | if opts.has_key('i'): |
|
1699 | 1698 | self.shell.user_ns['__name__'] = __name__save |
|
1700 | 1699 | else: |
|
1701 | 1700 | # The shell MUST hold a reference to prog_ns so after %run |
|
1702 | 1701 | # exits, the python deletion mechanism doesn't zero it out |
|
1703 | 1702 | # (leaving dangling references). |
|
1704 | 1703 | self.shell.cache_main_mod(prog_ns,filename) |
|
1705 | 1704 | # update IPython interactive namespace |
|
1706 | 1705 | |
|
1707 | 1706 | # Some forms of read errors on the file may mean the |
|
1708 | 1707 | # __name__ key was never set; using pop we don't have to |
|
1709 | 1708 | # worry about a possible KeyError. |
|
1710 | 1709 | prog_ns.pop('__name__', None) |
|
1711 | 1710 | |
|
1712 | 1711 | self.shell.user_ns.update(prog_ns) |
|
1713 | 1712 | finally: |
|
1714 | 1713 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1715 | 1714 | # being a module to becoming a dict missing some key data after |
|
1716 | 1715 | # %run. As best I can see, this is NOT something IPython is doing |
|
1717 | 1716 | # at all, and similar problems have been reported before: |
|
1718 | 1717 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1719 | 1718 | # Since this seems to be done by the interpreter itself, the best |
|
1720 | 1719 | # we can do is to at least restore __builtins__ for the user on |
|
1721 | 1720 | # exit. |
|
1722 | 1721 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1723 | 1722 | |
|
1724 | 1723 | # Ensure key global structures are restored |
|
1725 | 1724 | sys.argv = save_argv |
|
1726 | 1725 | if restore_main: |
|
1727 | 1726 | sys.modules['__main__'] = restore_main |
|
1728 | 1727 | else: |
|
1729 | 1728 | # Remove from sys.modules the reference to main_mod we'd |
|
1730 | 1729 | # added. Otherwise it will trap references to objects |
|
1731 | 1730 | # contained therein. |
|
1732 | 1731 | del sys.modules[main_mod_name] |
|
1733 | 1732 | |
|
1734 | 1733 | return stats |
|
1735 | 1734 | |
|
1736 | 1735 | @testdec.skip_doctest |
|
1737 | 1736 | def magic_timeit(self, parameter_s =''): |
|
1738 | 1737 | """Time execution of a Python statement or expression |
|
1739 | 1738 | |
|
1740 | 1739 | Usage:\\ |
|
1741 | 1740 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1742 | 1741 | |
|
1743 | 1742 | Time execution of a Python statement or expression using the timeit |
|
1744 | 1743 | module. |
|
1745 | 1744 | |
|
1746 | 1745 | Options: |
|
1747 | 1746 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1748 | 1747 | is not given, a fitting value is chosen. |
|
1749 | 1748 | |
|
1750 | 1749 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1751 | 1750 | Default: 3 |
|
1752 | 1751 | |
|
1753 | 1752 | -t: use time.time to measure the time, which is the default on Unix. |
|
1754 | 1753 | This function measures wall time. |
|
1755 | 1754 | |
|
1756 | 1755 | -c: use time.clock to measure the time, which is the default on |
|
1757 | 1756 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1758 | 1757 | instead and returns the CPU user time. |
|
1759 | 1758 | |
|
1760 | 1759 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1761 | 1760 | Default: 3 |
|
1762 | 1761 | |
|
1763 | 1762 | |
|
1764 | 1763 | Examples: |
|
1765 | 1764 | |
|
1766 | 1765 | In [1]: %timeit pass |
|
1767 | 1766 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1768 | 1767 | |
|
1769 | 1768 | In [2]: u = None |
|
1770 | 1769 | |
|
1771 | 1770 | In [3]: %timeit u is None |
|
1772 | 1771 | 10000000 loops, best of 3: 184 ns per loop |
|
1773 | 1772 | |
|
1774 | 1773 | In [4]: %timeit -r 4 u == None |
|
1775 | 1774 | 1000000 loops, best of 4: 242 ns per loop |
|
1776 | 1775 | |
|
1777 | 1776 | In [5]: import time |
|
1778 | 1777 | |
|
1779 | 1778 | In [6]: %timeit -n1 time.sleep(2) |
|
1780 | 1779 | 1 loops, best of 3: 2 s per loop |
|
1781 | 1780 | |
|
1782 | 1781 | |
|
1783 | 1782 | The times reported by %timeit will be slightly higher than those |
|
1784 | 1783 | reported by the timeit.py script when variables are accessed. This is |
|
1785 | 1784 | due to the fact that %timeit executes the statement in the namespace |
|
1786 | 1785 | of the shell, compared with timeit.py, which uses a single setup |
|
1787 | 1786 | statement to import function or create variables. Generally, the bias |
|
1788 | 1787 | does not matter as long as results from timeit.py are not mixed with |
|
1789 | 1788 | those from %timeit.""" |
|
1790 | 1789 | |
|
1791 | 1790 | import timeit |
|
1792 | 1791 | import math |
|
1793 | 1792 | |
|
1794 | 1793 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1795 | 1794 | # certain terminals. Until we figure out a robust way of |
|
1796 | 1795 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1797 | 1796 | # microseconds. I am really NOT happy about disabling the proper |
|
1798 | 1797 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1799 | 1798 | # right solution for this is, I'm all ears... |
|
1800 | 1799 | # |
|
1801 | 1800 | # Note: using |
|
1802 | 1801 | # |
|
1803 | 1802 | # s = u'\xb5' |
|
1804 | 1803 | # s.encode(sys.getdefaultencoding()) |
|
1805 | 1804 | # |
|
1806 | 1805 | # is not sufficient, as I've seen terminals where that fails but |
|
1807 | 1806 | # print s |
|
1808 | 1807 | # |
|
1809 | 1808 | # succeeds |
|
1810 | 1809 | # |
|
1811 | 1810 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1812 | 1811 | |
|
1813 | 1812 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1814 | 1813 | units = [u"s", u"ms",u'us',"ns"] |
|
1815 | 1814 | |
|
1816 | 1815 | scaling = [1, 1e3, 1e6, 1e9] |
|
1817 | 1816 | |
|
1818 | 1817 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1819 | 1818 | posix=False) |
|
1820 | 1819 | if stmt == "": |
|
1821 | 1820 | return |
|
1822 | 1821 | timefunc = timeit.default_timer |
|
1823 | 1822 | number = int(getattr(opts, "n", 0)) |
|
1824 | 1823 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1825 | 1824 | precision = int(getattr(opts, "p", 3)) |
|
1826 | 1825 | if hasattr(opts, "t"): |
|
1827 | 1826 | timefunc = time.time |
|
1828 | 1827 | if hasattr(opts, "c"): |
|
1829 | 1828 | timefunc = clock |
|
1830 | 1829 | |
|
1831 | 1830 | timer = timeit.Timer(timer=timefunc) |
|
1832 | 1831 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1833 | 1832 | # but is there a better way to achieve that the code stmt has access |
|
1834 | 1833 | # to the shell namespace? |
|
1835 | 1834 | |
|
1836 | 1835 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1837 | 1836 | 'setup': "pass"} |
|
1838 | 1837 | # Track compilation time so it can be reported if too long |
|
1839 | 1838 | # Minimum time above which compilation time will be reported |
|
1840 | 1839 | tc_min = 0.1 |
|
1841 | 1840 | |
|
1842 | 1841 | t0 = clock() |
|
1843 | 1842 | code = compile(src, "<magic-timeit>", "exec") |
|
1844 | 1843 | tc = clock()-t0 |
|
1845 | 1844 | |
|
1846 | 1845 | ns = {} |
|
1847 | 1846 | exec code in self.shell.user_ns, ns |
|
1848 | 1847 | timer.inner = ns["inner"] |
|
1849 | 1848 | |
|
1850 | 1849 | if number == 0: |
|
1851 | 1850 | # determine number so that 0.2 <= total time < 2.0 |
|
1852 | 1851 | number = 1 |
|
1853 | 1852 | for i in range(1, 10): |
|
1854 | 1853 | if timer.timeit(number) >= 0.2: |
|
1855 | 1854 | break |
|
1856 | 1855 | number *= 10 |
|
1857 | 1856 | |
|
1858 | 1857 | best = min(timer.repeat(repeat, number)) / number |
|
1859 | 1858 | |
|
1860 | 1859 | if best > 0.0 and best < 1000.0: |
|
1861 | 1860 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1862 | 1861 | elif best >= 1000.0: |
|
1863 | 1862 | order = 0 |
|
1864 | 1863 | else: |
|
1865 | 1864 | order = 3 |
|
1866 | 1865 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1867 | 1866 | precision, |
|
1868 | 1867 | best * scaling[order], |
|
1869 | 1868 | units[order]) |
|
1870 | 1869 | if tc > tc_min: |
|
1871 | 1870 | print "Compiler time: %.2f s" % tc |
|
1872 | 1871 | |
|
1873 | 1872 | @testdec.skip_doctest |
|
1874 | 1873 | @needs_local_scope |
|
1875 | 1874 | def magic_time(self,parameter_s = ''): |
|
1876 | 1875 | """Time execution of a Python statement or expression. |
|
1877 | 1876 | |
|
1878 | 1877 | The CPU and wall clock times are printed, and the value of the |
|
1879 | 1878 | expression (if any) is returned. Note that under Win32, system time |
|
1880 | 1879 | is always reported as 0, since it can not be measured. |
|
1881 | 1880 | |
|
1882 | 1881 | This function provides very basic timing functionality. In Python |
|
1883 | 1882 | 2.3, the timeit module offers more control and sophistication, so this |
|
1884 | 1883 | could be rewritten to use it (patches welcome). |
|
1885 | 1884 | |
|
1886 | 1885 | Some examples: |
|
1887 | 1886 | |
|
1888 | 1887 | In [1]: time 2**128 |
|
1889 | 1888 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1890 | 1889 | Wall time: 0.00 |
|
1891 | 1890 | Out[1]: 340282366920938463463374607431768211456L |
|
1892 | 1891 | |
|
1893 | 1892 | In [2]: n = 1000000 |
|
1894 | 1893 | |
|
1895 | 1894 | In [3]: time sum(range(n)) |
|
1896 | 1895 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1897 | 1896 | Wall time: 1.37 |
|
1898 | 1897 | Out[3]: 499999500000L |
|
1899 | 1898 | |
|
1900 | 1899 | In [4]: time print 'hello world' |
|
1901 | 1900 | hello world |
|
1902 | 1901 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1903 | 1902 | Wall time: 0.00 |
|
1904 | 1903 | |
|
1905 | 1904 | Note that the time needed by Python to compile the given expression |
|
1906 | 1905 | will be reported if it is more than 0.1s. In this example, the |
|
1907 | 1906 | actual exponentiation is done by Python at compilation time, so while |
|
1908 | 1907 | the expression can take a noticeable amount of time to compute, that |
|
1909 | 1908 | time is purely due to the compilation: |
|
1910 | 1909 | |
|
1911 | 1910 | In [5]: time 3**9999; |
|
1912 | 1911 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1913 | 1912 | Wall time: 0.00 s |
|
1914 | 1913 | |
|
1915 | 1914 | In [6]: time 3**999999; |
|
1916 | 1915 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1917 | 1916 | Wall time: 0.00 s |
|
1918 | 1917 | Compiler : 0.78 s |
|
1919 | 1918 | """ |
|
1920 | 1919 | |
|
1921 | 1920 | # fail immediately if the given expression can't be compiled |
|
1922 | 1921 | |
|
1923 | 1922 | expr = self.shell.prefilter(parameter_s,False) |
|
1924 | 1923 | |
|
1925 | 1924 | # Minimum time above which compilation time will be reported |
|
1926 | 1925 | tc_min = 0.1 |
|
1927 | 1926 | |
|
1928 | 1927 | try: |
|
1929 | 1928 | mode = 'eval' |
|
1930 | 1929 | t0 = clock() |
|
1931 | 1930 | code = compile(expr,'<timed eval>',mode) |
|
1932 | 1931 | tc = clock()-t0 |
|
1933 | 1932 | except SyntaxError: |
|
1934 | 1933 | mode = 'exec' |
|
1935 | 1934 | t0 = clock() |
|
1936 | 1935 | code = compile(expr,'<timed exec>',mode) |
|
1937 | 1936 | tc = clock()-t0 |
|
1938 | 1937 | # skew measurement as little as possible |
|
1939 | 1938 | glob = self.shell.user_ns |
|
1940 | 1939 | locs = self._magic_locals |
|
1941 | 1940 | clk = clock2 |
|
1942 | 1941 | wtime = time.time |
|
1943 | 1942 | # time execution |
|
1944 | 1943 | wall_st = wtime() |
|
1945 | 1944 | if mode=='eval': |
|
1946 | 1945 | st = clk() |
|
1947 | 1946 | out = eval(code, glob, locs) |
|
1948 | 1947 | end = clk() |
|
1949 | 1948 | else: |
|
1950 | 1949 | st = clk() |
|
1951 | 1950 | exec code in glob, locs |
|
1952 | 1951 | end = clk() |
|
1953 | 1952 | out = None |
|
1954 | 1953 | wall_end = wtime() |
|
1955 | 1954 | # Compute actual times and report |
|
1956 | 1955 | wall_time = wall_end-wall_st |
|
1957 | 1956 | cpu_user = end[0]-st[0] |
|
1958 | 1957 | cpu_sys = end[1]-st[1] |
|
1959 | 1958 | cpu_tot = cpu_user+cpu_sys |
|
1960 | 1959 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1961 | 1960 | (cpu_user,cpu_sys,cpu_tot) |
|
1962 | 1961 | print "Wall time: %.2f s" % wall_time |
|
1963 | 1962 | if tc > tc_min: |
|
1964 | 1963 | print "Compiler : %.2f s" % tc |
|
1965 | 1964 | return out |
|
1966 | 1965 | |
|
1967 | 1966 | @testdec.skip_doctest |
|
1968 | 1967 | def magic_macro(self,parameter_s = ''): |
|
1969 | 1968 | """Define a macro for future re-execution. It accepts ranges of history, |
|
1970 | 1969 | filenames or string objects. |
|
1971 | 1970 | |
|
1972 | 1971 | Usage:\\ |
|
1973 | 1972 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1974 | 1973 | |
|
1975 | 1974 | Options: |
|
1976 | 1975 | |
|
1977 | 1976 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1978 | 1977 | so that magics are loaded in their transformed version to valid |
|
1979 | 1978 | Python. If this option is given, the raw input as typed as the |
|
1980 | 1979 | command line is used instead. |
|
1981 | 1980 | |
|
1982 | 1981 | This will define a global variable called `name` which is a string |
|
1983 | 1982 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1984 | 1983 | above) from your input history into a single string. This variable |
|
1985 | 1984 | acts like an automatic function which re-executes those lines as if |
|
1986 | 1985 | you had typed them. You just type 'name' at the prompt and the code |
|
1987 | 1986 | executes. |
|
1988 | 1987 | |
|
1989 | 1988 | The syntax for indicating input ranges is described in %history. |
|
1990 | 1989 | |
|
1991 | 1990 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1992 | 1991 | notation, where N:M means numbers N through M-1. |
|
1993 | 1992 | |
|
1994 | 1993 | For example, if your history contains (%hist prints it): |
|
1995 | 1994 | |
|
1996 | 1995 | 44: x=1 |
|
1997 | 1996 | 45: y=3 |
|
1998 | 1997 | 46: z=x+y |
|
1999 | 1998 | 47: print x |
|
2000 | 1999 | 48: a=5 |
|
2001 | 2000 | 49: print 'x',x,'y',y |
|
2002 | 2001 | |
|
2003 | 2002 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
2004 | 2003 | called my_macro with: |
|
2005 | 2004 | |
|
2006 | 2005 | In [55]: %macro my_macro 44-47 49 |
|
2007 | 2006 | |
|
2008 | 2007 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
2009 | 2008 | in one pass. |
|
2010 | 2009 | |
|
2011 | 2010 | You don't need to give the line-numbers in order, and any given line |
|
2012 | 2011 | number can appear multiple times. You can assemble macros with any |
|
2013 | 2012 | lines from your input history in any order. |
|
2014 | 2013 | |
|
2015 | 2014 | The macro is a simple object which holds its value in an attribute, |
|
2016 | 2015 | but IPython's display system checks for macros and executes them as |
|
2017 | 2016 | code instead of printing them when you type their name. |
|
2018 | 2017 | |
|
2019 | 2018 | You can view a macro's contents by explicitly printing it with: |
|
2020 | 2019 | |
|
2021 | 2020 | 'print macro_name'. |
|
2022 | 2021 | |
|
2023 | 2022 | """ |
|
2024 | 2023 | |
|
2025 | 2024 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2026 | 2025 | if not args: # List existing macros |
|
2027 | 2026 | return sorted(k for k,v in self.shell.user_ns.iteritems() if\ |
|
2028 | 2027 | isinstance(v, Macro)) |
|
2029 | 2028 | if len(args) == 1: |
|
2030 | 2029 | raise UsageError( |
|
2031 | 2030 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
2032 | 2031 | name, codefrom = args[0], " ".join(args[1:]) |
|
2033 | 2032 | |
|
2034 | 2033 | #print 'rng',ranges # dbg |
|
2035 | 2034 | try: |
|
2036 | 2035 | lines = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2037 | 2036 | except (ValueError, TypeError) as e: |
|
2038 | 2037 | print e.args[0] |
|
2039 | 2038 | return |
|
2040 | 2039 | macro = Macro(lines) |
|
2041 | 2040 | self.shell.define_macro(name, macro) |
|
2042 | 2041 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
2043 | 2042 | print '=== Macro contents: ===' |
|
2044 | 2043 | print macro, |
|
2045 | 2044 | |
|
2046 | 2045 | def magic_save(self,parameter_s = ''): |
|
2047 | 2046 | """Save a set of lines or a macro to a given filename. |
|
2048 | 2047 | |
|
2049 | 2048 | Usage:\\ |
|
2050 | 2049 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
2051 | 2050 | |
|
2052 | 2051 | Options: |
|
2053 | 2052 | |
|
2054 | 2053 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2055 | 2054 | so that magics are loaded in their transformed version to valid |
|
2056 | 2055 | Python. If this option is given, the raw input as typed as the |
|
2057 | 2056 | command line is used instead. |
|
2058 | 2057 | |
|
2059 | 2058 | This function uses the same syntax as %history for input ranges, |
|
2060 | 2059 | then saves the lines to the filename you specify. |
|
2061 | 2060 | |
|
2062 | 2061 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2063 | 2062 | it asks for confirmation before overwriting existing files.""" |
|
2064 | 2063 | |
|
2065 | 2064 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2066 | 2065 | fname, codefrom = args[0], " ".join(args[1:]) |
|
2067 | 2066 | if not fname.endswith('.py'): |
|
2068 | 2067 | fname += '.py' |
|
2069 | 2068 | if os.path.isfile(fname): |
|
2070 | 2069 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2071 | 2070 | if ans.lower() not in ['y','yes']: |
|
2072 | 2071 | print 'Operation cancelled.' |
|
2073 | 2072 | return |
|
2074 | 2073 | try: |
|
2075 | 2074 | cmds = self.shell.find_user_code(codefrom, 'r' in opts) |
|
2076 | 2075 | except (TypeError, ValueError) as e: |
|
2077 | 2076 | print e.args[0] |
|
2078 | 2077 | return |
|
2079 | 2078 | if isinstance(cmds, unicode): |
|
2080 | 2079 | cmds = cmds.encode("utf-8") |
|
2081 | 2080 | with open(fname,'w') as f: |
|
2082 | 2081 | f.write("# coding: utf-8\n") |
|
2083 | 2082 | f.write(cmds) |
|
2084 | 2083 | print 'The following commands were written to file `%s`:' % fname |
|
2085 | 2084 | print cmds |
|
2086 | 2085 | |
|
2087 | 2086 | def magic_pastebin(self, parameter_s = ''): |
|
2088 | 2087 | """Upload code to the 'Lodge it' paste bin, returning the URL.""" |
|
2089 | 2088 | try: |
|
2090 | 2089 | code = self.shell.find_user_code(parameter_s) |
|
2091 | 2090 | except (ValueError, TypeError) as e: |
|
2092 | 2091 | print e.args[0] |
|
2093 | 2092 | return |
|
2094 | 2093 | pbserver = ServerProxy('http://paste.pocoo.org/xmlrpc/') |
|
2095 | 2094 | id = pbserver.pastes.newPaste("python", code) |
|
2096 | 2095 | return "http://paste.pocoo.org/show/" + id |
|
2097 | 2096 | |
|
2098 | 2097 | def _edit_macro(self,mname,macro): |
|
2099 | 2098 | """open an editor with the macro data in a file""" |
|
2100 | 2099 | filename = self.shell.mktempfile(macro.value) |
|
2101 | 2100 | self.shell.hooks.editor(filename) |
|
2102 | 2101 | |
|
2103 | 2102 | # and make a new macro object, to replace the old one |
|
2104 | 2103 | mfile = open(filename) |
|
2105 | 2104 | mvalue = mfile.read() |
|
2106 | 2105 | mfile.close() |
|
2107 | 2106 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2108 | 2107 | |
|
2109 | 2108 | def magic_ed(self,parameter_s=''): |
|
2110 | 2109 | """Alias to %edit.""" |
|
2111 | 2110 | return self.magic_edit(parameter_s) |
|
2112 | 2111 | |
|
2113 | 2112 | @testdec.skip_doctest |
|
2114 | 2113 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2115 | 2114 | """Bring up an editor and execute the resulting code. |
|
2116 | 2115 | |
|
2117 | 2116 | Usage: |
|
2118 | 2117 | %edit [options] [args] |
|
2119 | 2118 | |
|
2120 | 2119 | %edit runs IPython's editor hook. The default version of this hook is |
|
2121 | 2120 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2122 | 2121 | environment variable $EDITOR. If this isn't found, it will default to |
|
2123 | 2122 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2124 | 2123 | docstring for how to change the editor hook. |
|
2125 | 2124 | |
|
2126 | 2125 | You can also set the value of this editor via the command line option |
|
2127 | 2126 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2128 | 2127 | specifically for IPython an editor different from your typical default |
|
2129 | 2128 | (and for Windows users who typically don't set environment variables). |
|
2130 | 2129 | |
|
2131 | 2130 | This command allows you to conveniently edit multi-line code right in |
|
2132 | 2131 | your IPython session. |
|
2133 | 2132 | |
|
2134 | 2133 | If called without arguments, %edit opens up an empty editor with a |
|
2135 | 2134 | temporary file and will execute the contents of this file when you |
|
2136 | 2135 | close it (don't forget to save it!). |
|
2137 | 2136 | |
|
2138 | 2137 | |
|
2139 | 2138 | Options: |
|
2140 | 2139 | |
|
2141 | 2140 | -n <number>: open the editor at a specified line number. By default, |
|
2142 | 2141 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2143 | 2142 | you can configure this by providing your own modified hook if your |
|
2144 | 2143 | favorite editor supports line-number specifications with a different |
|
2145 | 2144 | syntax. |
|
2146 | 2145 | |
|
2147 | 2146 | -p: this will call the editor with the same data as the previous time |
|
2148 | 2147 | it was used, regardless of how long ago (in your current session) it |
|
2149 | 2148 | was. |
|
2150 | 2149 | |
|
2151 | 2150 | -r: use 'raw' input. This option only applies to input taken from the |
|
2152 | 2151 | user's history. By default, the 'processed' history is used, so that |
|
2153 | 2152 | magics are loaded in their transformed version to valid Python. If |
|
2154 | 2153 | this option is given, the raw input as typed as the command line is |
|
2155 | 2154 | used instead. When you exit the editor, it will be executed by |
|
2156 | 2155 | IPython's own processor. |
|
2157 | 2156 | |
|
2158 | 2157 | -x: do not execute the edited code immediately upon exit. This is |
|
2159 | 2158 | mainly useful if you are editing programs which need to be called with |
|
2160 | 2159 | command line arguments, which you can then do using %run. |
|
2161 | 2160 | |
|
2162 | 2161 | |
|
2163 | 2162 | Arguments: |
|
2164 | 2163 | |
|
2165 | 2164 | If arguments are given, the following possibilites exist: |
|
2166 | 2165 | |
|
2167 | 2166 | - If the argument is a filename, IPython will load that into the |
|
2168 | 2167 | editor. It will execute its contents with execfile() when you exit, |
|
2169 | 2168 | loading any code in the file into your interactive namespace. |
|
2170 | 2169 | |
|
2171 | 2170 | - The arguments are ranges of input history, e.g. "7 ~1/4-6". |
|
2172 | 2171 | The syntax is the same as in the %history magic. |
|
2173 | 2172 | |
|
2174 | 2173 | - If the argument is a string variable, its contents are loaded |
|
2175 | 2174 | into the editor. You can thus edit any string which contains |
|
2176 | 2175 | python code (including the result of previous edits). |
|
2177 | 2176 | |
|
2178 | 2177 | - If the argument is the name of an object (other than a string), |
|
2179 | 2178 | IPython will try to locate the file where it was defined and open the |
|
2180 | 2179 | editor at the point where it is defined. You can use `%edit function` |
|
2181 | 2180 | to load an editor exactly at the point where 'function' is defined, |
|
2182 | 2181 | edit it and have the file be executed automatically. |
|
2183 | 2182 | |
|
2184 | 2183 | If the object is a macro (see %macro for details), this opens up your |
|
2185 | 2184 | specified editor with a temporary file containing the macro's data. |
|
2186 | 2185 | Upon exit, the macro is reloaded with the contents of the file. |
|
2187 | 2186 | |
|
2188 | 2187 | Note: opening at an exact line is only supported under Unix, and some |
|
2189 | 2188 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2190 | 2189 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2191 | 2190 | (X)Emacs, vi, jed, pico and joe all do. |
|
2192 | 2191 | |
|
2193 | 2192 | After executing your code, %edit will return as output the code you |
|
2194 | 2193 | typed in the editor (except when it was an existing file). This way |
|
2195 | 2194 | you can reload the code in further invocations of %edit as a variable, |
|
2196 | 2195 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2197 | 2196 | the output. |
|
2198 | 2197 | |
|
2199 | 2198 | Note that %edit is also available through the alias %ed. |
|
2200 | 2199 | |
|
2201 | 2200 | This is an example of creating a simple function inside the editor and |
|
2202 | 2201 | then modifying it. First, start up the editor: |
|
2203 | 2202 | |
|
2204 | 2203 | In [1]: ed |
|
2205 | 2204 | Editing... done. Executing edited code... |
|
2206 | 2205 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2207 | 2206 | |
|
2208 | 2207 | We can then call the function foo(): |
|
2209 | 2208 | |
|
2210 | 2209 | In [2]: foo() |
|
2211 | 2210 | foo() was defined in an editing session |
|
2212 | 2211 | |
|
2213 | 2212 | Now we edit foo. IPython automatically loads the editor with the |
|
2214 | 2213 | (temporary) file where foo() was previously defined: |
|
2215 | 2214 | |
|
2216 | 2215 | In [3]: ed foo |
|
2217 | 2216 | Editing... done. Executing edited code... |
|
2218 | 2217 | |
|
2219 | 2218 | And if we call foo() again we get the modified version: |
|
2220 | 2219 | |
|
2221 | 2220 | In [4]: foo() |
|
2222 | 2221 | foo() has now been changed! |
|
2223 | 2222 | |
|
2224 | 2223 | Here is an example of how to edit a code snippet successive |
|
2225 | 2224 | times. First we call the editor: |
|
2226 | 2225 | |
|
2227 | 2226 | In [5]: ed |
|
2228 | 2227 | Editing... done. Executing edited code... |
|
2229 | 2228 | hello |
|
2230 | 2229 | Out[5]: "print 'hello'n" |
|
2231 | 2230 | |
|
2232 | 2231 | Now we call it again with the previous output (stored in _): |
|
2233 | 2232 | |
|
2234 | 2233 | In [6]: ed _ |
|
2235 | 2234 | Editing... done. Executing edited code... |
|
2236 | 2235 | hello world |
|
2237 | 2236 | Out[6]: "print 'hello world'n" |
|
2238 | 2237 | |
|
2239 | 2238 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2240 | 2239 | |
|
2241 | 2240 | In [7]: ed _8 |
|
2242 | 2241 | Editing... done. Executing edited code... |
|
2243 | 2242 | hello again |
|
2244 | 2243 | Out[7]: "print 'hello again'n" |
|
2245 | 2244 | |
|
2246 | 2245 | |
|
2247 | 2246 | Changing the default editor hook: |
|
2248 | 2247 | |
|
2249 | 2248 | If you wish to write your own editor hook, you can put it in a |
|
2250 | 2249 | configuration file which you load at startup time. The default hook |
|
2251 | 2250 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2252 | 2251 | starting example for further modifications. That file also has |
|
2253 | 2252 | general instructions on how to set a new hook for use once you've |
|
2254 | 2253 | defined it.""" |
|
2255 | 2254 | |
|
2256 | 2255 | # FIXME: This function has become a convoluted mess. It needs a |
|
2257 | 2256 | # ground-up rewrite with clean, simple logic. |
|
2258 | 2257 | |
|
2259 | 2258 | def make_filename(arg): |
|
2260 | 2259 | "Make a filename from the given args" |
|
2261 | 2260 | try: |
|
2262 | 2261 | filename = get_py_filename(arg) |
|
2263 | 2262 | except IOError: |
|
2264 | 2263 | if args.endswith('.py'): |
|
2265 | 2264 | filename = arg |
|
2266 | 2265 | else: |
|
2267 | 2266 | filename = None |
|
2268 | 2267 | return filename |
|
2269 | 2268 | |
|
2270 | 2269 | # custom exceptions |
|
2271 | 2270 | class DataIsObject(Exception): pass |
|
2272 | 2271 | |
|
2273 | 2272 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2274 | 2273 | # Set a few locals from the options for convenience: |
|
2275 | 2274 | opts_prev = 'p' in opts |
|
2276 | 2275 | opts_raw = 'r' in opts |
|
2277 | 2276 | |
|
2278 | 2277 | # Default line number value |
|
2279 | 2278 | lineno = opts.get('n',None) |
|
2280 | 2279 | |
|
2281 | 2280 | if opts_prev: |
|
2282 | 2281 | args = '_%s' % last_call[0] |
|
2283 | 2282 | if not self.shell.user_ns.has_key(args): |
|
2284 | 2283 | args = last_call[1] |
|
2285 | 2284 | |
|
2286 | 2285 | # use last_call to remember the state of the previous call, but don't |
|
2287 | 2286 | # let it be clobbered by successive '-p' calls. |
|
2288 | 2287 | try: |
|
2289 | 2288 | last_call[0] = self.shell.displayhook.prompt_count |
|
2290 | 2289 | if not opts_prev: |
|
2291 | 2290 | last_call[1] = parameter_s |
|
2292 | 2291 | except: |
|
2293 | 2292 | pass |
|
2294 | 2293 | |
|
2295 | 2294 | # by default this is done with temp files, except when the given |
|
2296 | 2295 | # arg is a filename |
|
2297 | 2296 | use_temp = True |
|
2298 | 2297 | |
|
2299 | 2298 | data = '' |
|
2300 | 2299 | if args.endswith('.py'): |
|
2301 | 2300 | filename = make_filename(args) |
|
2302 | 2301 | use_temp = False |
|
2303 | 2302 | elif args: |
|
2304 | 2303 | # Mode where user specifies ranges of lines, like in %macro. |
|
2305 | 2304 | data = self.extract_input_lines(args, opts_raw) |
|
2306 | 2305 | if not data: |
|
2307 | 2306 | try: |
|
2308 | 2307 | # Load the parameter given as a variable. If not a string, |
|
2309 | 2308 | # process it as an object instead (below) |
|
2310 | 2309 | |
|
2311 | 2310 | #print '*** args',args,'type',type(args) # dbg |
|
2312 | 2311 | data = eval(args, self.shell.user_ns) |
|
2313 | 2312 | if not isinstance(data, basestring): |
|
2314 | 2313 | raise DataIsObject |
|
2315 | 2314 | |
|
2316 | 2315 | except (NameError,SyntaxError): |
|
2317 | 2316 | # given argument is not a variable, try as a filename |
|
2318 | 2317 | filename = make_filename(args) |
|
2319 | 2318 | if filename is None: |
|
2320 | 2319 | warn("Argument given (%s) can't be found as a variable " |
|
2321 | 2320 | "or as a filename." % args) |
|
2322 | 2321 | return |
|
2323 | 2322 | use_temp = False |
|
2324 | 2323 | |
|
2325 | 2324 | except DataIsObject: |
|
2326 | 2325 | # macros have a special edit function |
|
2327 | 2326 | if isinstance(data, Macro): |
|
2328 | 2327 | self._edit_macro(args,data) |
|
2329 | 2328 | return |
|
2330 | 2329 | |
|
2331 | 2330 | # For objects, try to edit the file where they are defined |
|
2332 | 2331 | try: |
|
2333 | 2332 | filename = inspect.getabsfile(data) |
|
2334 | 2333 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2335 | 2334 | # class created by %edit? Try to find source |
|
2336 | 2335 | # by looking for method definitions instead, the |
|
2337 | 2336 | # __module__ in those classes is FakeModule. |
|
2338 | 2337 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2339 | 2338 | for attr in attrs: |
|
2340 | 2339 | if not inspect.ismethod(attr): |
|
2341 | 2340 | continue |
|
2342 | 2341 | filename = inspect.getabsfile(attr) |
|
2343 | 2342 | if filename and 'fakemodule' not in filename.lower(): |
|
2344 | 2343 | # change the attribute to be the edit target instead |
|
2345 | 2344 | data = attr |
|
2346 | 2345 | break |
|
2347 | 2346 | |
|
2348 | 2347 | datafile = 1 |
|
2349 | 2348 | except TypeError: |
|
2350 | 2349 | filename = make_filename(args) |
|
2351 | 2350 | datafile = 1 |
|
2352 | 2351 | warn('Could not find file where `%s` is defined.\n' |
|
2353 | 2352 | 'Opening a file named `%s`' % (args,filename)) |
|
2354 | 2353 | # Now, make sure we can actually read the source (if it was in |
|
2355 | 2354 | # a temp file it's gone by now). |
|
2356 | 2355 | if datafile: |
|
2357 | 2356 | try: |
|
2358 | 2357 | if lineno is None: |
|
2359 | 2358 | lineno = inspect.getsourcelines(data)[1] |
|
2360 | 2359 | except IOError: |
|
2361 | 2360 | filename = make_filename(args) |
|
2362 | 2361 | if filename is None: |
|
2363 | 2362 | warn('The file `%s` where `%s` was defined cannot ' |
|
2364 | 2363 | 'be read.' % (filename,data)) |
|
2365 | 2364 | return |
|
2366 | 2365 | use_temp = False |
|
2367 | 2366 | |
|
2368 | 2367 | if use_temp: |
|
2369 | 2368 | filename = self.shell.mktempfile(data) |
|
2370 | 2369 | print 'IPython will make a temporary file named:',filename |
|
2371 | 2370 | |
|
2372 | 2371 | # do actual editing here |
|
2373 | 2372 | print 'Editing...', |
|
2374 | 2373 | sys.stdout.flush() |
|
2375 | 2374 | try: |
|
2376 | 2375 | # Quote filenames that may have spaces in them |
|
2377 | 2376 | if ' ' in filename: |
|
2378 | 2377 | filename = "%s" % filename |
|
2379 | 2378 | self.shell.hooks.editor(filename,lineno) |
|
2380 | 2379 | except TryNext: |
|
2381 | 2380 | warn('Could not open editor') |
|
2382 | 2381 | return |
|
2383 | 2382 | |
|
2384 | 2383 | # XXX TODO: should this be generalized for all string vars? |
|
2385 | 2384 | # For now, this is special-cased to blocks created by cpaste |
|
2386 | 2385 | if args.strip() == 'pasted_block': |
|
2387 | 2386 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2388 | 2387 | |
|
2389 | 2388 | if 'x' in opts: # -x prevents actual execution |
|
2390 | 2389 | |
|
2391 | 2390 | else: |
|
2392 | 2391 | print 'done. Executing edited code...' |
|
2393 | 2392 | if opts_raw: |
|
2394 | 2393 | self.shell.run_cell(file_read(filename), |
|
2395 | 2394 | store_history=False) |
|
2396 | 2395 | else: |
|
2397 | 2396 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2398 | 2397 | self.shell.user_ns) |
|
2399 | 2398 | |
|
2400 | 2399 | |
|
2401 | 2400 | if use_temp: |
|
2402 | 2401 | try: |
|
2403 | 2402 | return open(filename).read() |
|
2404 | 2403 | except IOError,msg: |
|
2405 | 2404 | if msg.filename == filename: |
|
2406 | 2405 | warn('File not found. Did you forget to save?') |
|
2407 | 2406 | return |
|
2408 | 2407 | else: |
|
2409 | 2408 | self.shell.showtraceback() |
|
2410 | 2409 | |
|
2411 | 2410 | def magic_xmode(self,parameter_s = ''): |
|
2412 | 2411 | """Switch modes for the exception handlers. |
|
2413 | 2412 | |
|
2414 | 2413 | Valid modes: Plain, Context and Verbose. |
|
2415 | 2414 | |
|
2416 | 2415 | If called without arguments, acts as a toggle.""" |
|
2417 | 2416 | |
|
2418 | 2417 | def xmode_switch_err(name): |
|
2419 | 2418 | warn('Error changing %s exception modes.\n%s' % |
|
2420 | 2419 | (name,sys.exc_info()[1])) |
|
2421 | 2420 | |
|
2422 | 2421 | shell = self.shell |
|
2423 | 2422 | new_mode = parameter_s.strip().capitalize() |
|
2424 | 2423 | try: |
|
2425 | 2424 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2426 | 2425 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2427 | 2426 | except: |
|
2428 | 2427 | xmode_switch_err('user') |
|
2429 | 2428 | |
|
2430 | 2429 | def magic_colors(self,parameter_s = ''): |
|
2431 | 2430 | """Switch color scheme for prompts, info system and exception handlers. |
|
2432 | 2431 | |
|
2433 | 2432 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2434 | 2433 | |
|
2435 | 2434 | Color scheme names are not case-sensitive. |
|
2436 | 2435 | |
|
2437 | 2436 | Examples |
|
2438 | 2437 | -------- |
|
2439 | 2438 | To get a plain black and white terminal:: |
|
2440 | 2439 | |
|
2441 | 2440 | %colors nocolor |
|
2442 | 2441 | """ |
|
2443 | 2442 | |
|
2444 | 2443 | def color_switch_err(name): |
|
2445 | 2444 | warn('Error changing %s color schemes.\n%s' % |
|
2446 | 2445 | (name,sys.exc_info()[1])) |
|
2447 | 2446 | |
|
2448 | 2447 | |
|
2449 | 2448 | new_scheme = parameter_s.strip() |
|
2450 | 2449 | if not new_scheme: |
|
2451 | 2450 | raise UsageError( |
|
2452 | 2451 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2453 | 2452 | return |
|
2454 | 2453 | # local shortcut |
|
2455 | 2454 | shell = self.shell |
|
2456 | 2455 | |
|
2457 | 2456 | import IPython.utils.rlineimpl as readline |
|
2458 | 2457 | |
|
2459 | 2458 | if not readline.have_readline and sys.platform == "win32": |
|
2460 | 2459 | msg = """\ |
|
2461 | 2460 | Proper color support under MS Windows requires the pyreadline library. |
|
2462 | 2461 | You can find it at: |
|
2463 | 2462 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2464 | 2463 | Gary's readline needs the ctypes module, from: |
|
2465 | 2464 | http://starship.python.net/crew/theller/ctypes |
|
2466 | 2465 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2467 | 2466 | |
|
2468 | 2467 | Defaulting color scheme to 'NoColor'""" |
|
2469 | 2468 | new_scheme = 'NoColor' |
|
2470 | 2469 | warn(msg) |
|
2471 | 2470 | |
|
2472 | 2471 | # readline option is 0 |
|
2473 | 2472 | if not shell.has_readline: |
|
2474 | 2473 | new_scheme = 'NoColor' |
|
2475 | 2474 | |
|
2476 | 2475 | # Set prompt colors |
|
2477 | 2476 | try: |
|
2478 | 2477 | shell.displayhook.set_colors(new_scheme) |
|
2479 | 2478 | except: |
|
2480 | 2479 | color_switch_err('prompt') |
|
2481 | 2480 | else: |
|
2482 | 2481 | shell.colors = \ |
|
2483 | 2482 | shell.displayhook.color_table.active_scheme_name |
|
2484 | 2483 | # Set exception colors |
|
2485 | 2484 | try: |
|
2486 | 2485 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2487 | 2486 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2488 | 2487 | except: |
|
2489 | 2488 | color_switch_err('exception') |
|
2490 | 2489 | |
|
2491 | 2490 | # Set info (for 'object?') colors |
|
2492 | 2491 | if shell.color_info: |
|
2493 | 2492 | try: |
|
2494 | 2493 | shell.inspector.set_active_scheme(new_scheme) |
|
2495 | 2494 | except: |
|
2496 | 2495 | color_switch_err('object inspector') |
|
2497 | 2496 | else: |
|
2498 | 2497 | shell.inspector.set_active_scheme('NoColor') |
|
2499 | 2498 | |
|
2500 | 2499 | def magic_pprint(self, parameter_s=''): |
|
2501 | 2500 | """Toggle pretty printing on/off.""" |
|
2502 | 2501 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
2503 | 2502 | ptformatter.pprint = bool(1 - ptformatter.pprint) |
|
2504 | 2503 | print 'Pretty printing has been turned', \ |
|
2505 | 2504 | ['OFF','ON'][ptformatter.pprint] |
|
2506 | 2505 | |
|
2507 | 2506 | #...................................................................... |
|
2508 | 2507 | # Functions to implement unix shell-type things |
|
2509 | 2508 | |
|
2510 | 2509 | @testdec.skip_doctest |
|
2511 | 2510 | def magic_alias(self, parameter_s = ''): |
|
2512 | 2511 | """Define an alias for a system command. |
|
2513 | 2512 | |
|
2514 | 2513 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2515 | 2514 | |
|
2516 | 2515 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2517 | 2516 | params' (from your underlying operating system). |
|
2518 | 2517 | |
|
2519 | 2518 | Aliases have lower precedence than magic functions and Python normal |
|
2520 | 2519 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2521 | 2520 | alias can not be executed until 'del foo' removes the Python variable. |
|
2522 | 2521 | |
|
2523 | 2522 | You can use the %l specifier in an alias definition to represent the |
|
2524 | 2523 | whole line when the alias is called. For example: |
|
2525 | 2524 | |
|
2526 | 2525 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2527 | 2526 | In [3]: bracket hello world |
|
2528 | 2527 | Input in brackets: <hello world> |
|
2529 | 2528 | |
|
2530 | 2529 | You can also define aliases with parameters using %s specifiers (one |
|
2531 | 2530 | per parameter): |
|
2532 | 2531 | |
|
2533 | 2532 | In [1]: alias parts echo first %s second %s |
|
2534 | 2533 | In [2]: %parts A B |
|
2535 | 2534 | first A second B |
|
2536 | 2535 | In [3]: %parts A |
|
2537 | 2536 | Incorrect number of arguments: 2 expected. |
|
2538 | 2537 | parts is an alias to: 'echo first %s second %s' |
|
2539 | 2538 | |
|
2540 | 2539 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2541 | 2540 | the other in your aliases. |
|
2542 | 2541 | |
|
2543 | 2542 | Aliases expand Python variables just like system calls using ! or !! |
|
2544 | 2543 | do: all expressions prefixed with '$' get expanded. For details of |
|
2545 | 2544 | the semantic rules, see PEP-215: |
|
2546 | 2545 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2547 | 2546 | IPython for variable expansion. If you want to access a true shell |
|
2548 | 2547 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2549 | 2548 | |
|
2550 | 2549 | In [6]: alias show echo |
|
2551 | 2550 | In [7]: PATH='A Python string' |
|
2552 | 2551 | In [8]: show $PATH |
|
2553 | 2552 | A Python string |
|
2554 | 2553 | In [9]: show $$PATH |
|
2555 | 2554 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2556 | 2555 | |
|
2557 | 2556 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2558 | 2557 | and %rehashx functions, which automatically create aliases for the |
|
2559 | 2558 | contents of your $PATH. |
|
2560 | 2559 | |
|
2561 | 2560 | If called with no parameters, %alias prints the current alias table.""" |
|
2562 | 2561 | |
|
2563 | 2562 | par = parameter_s.strip() |
|
2564 | 2563 | if not par: |
|
2565 | 2564 | stored = self.db.get('stored_aliases', {} ) |
|
2566 | 2565 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2567 | 2566 | # for k, v in stored: |
|
2568 | 2567 | # atab.append(k, v[0]) |
|
2569 | 2568 | |
|
2570 | 2569 | print "Total number of aliases:", len(aliases) |
|
2571 | 2570 | sys.stdout.flush() |
|
2572 | 2571 | return aliases |
|
2573 | 2572 | |
|
2574 | 2573 | # Now try to define a new one |
|
2575 | 2574 | try: |
|
2576 | 2575 | alias,cmd = par.split(None, 1) |
|
2577 | 2576 | except: |
|
2578 | 2577 | print oinspect.getdoc(self.magic_alias) |
|
2579 | 2578 | else: |
|
2580 | 2579 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2581 | 2580 | # end magic_alias |
|
2582 | 2581 | |
|
2583 | 2582 | def magic_unalias(self, parameter_s = ''): |
|
2584 | 2583 | """Remove an alias""" |
|
2585 | 2584 | |
|
2586 | 2585 | aname = parameter_s.strip() |
|
2587 | 2586 | self.shell.alias_manager.undefine_alias(aname) |
|
2588 | 2587 | stored = self.db.get('stored_aliases', {} ) |
|
2589 | 2588 | if aname in stored: |
|
2590 | 2589 | print "Removing %stored alias",aname |
|
2591 | 2590 | del stored[aname] |
|
2592 | 2591 | self.db['stored_aliases'] = stored |
|
2593 | 2592 | |
|
2594 | 2593 | def magic_rehashx(self, parameter_s = ''): |
|
2595 | 2594 | """Update the alias table with all executable files in $PATH. |
|
2596 | 2595 | |
|
2597 | 2596 | This version explicitly checks that every entry in $PATH is a file |
|
2598 | 2597 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2599 | 2598 | |
|
2600 | 2599 | Under Windows, it checks executability as a match agains a |
|
2601 | 2600 | '|'-separated string of extensions, stored in the IPython config |
|
2602 | 2601 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2603 | 2602 | |
|
2604 | 2603 | This function also resets the root module cache of module completer, |
|
2605 | 2604 | used on slow filesystems. |
|
2606 | 2605 | """ |
|
2607 | 2606 | from IPython.core.alias import InvalidAliasError |
|
2608 | 2607 | |
|
2609 | 2608 | # for the benefit of module completer in ipy_completers.py |
|
2610 | 2609 | del self.db['rootmodules'] |
|
2611 | 2610 | |
|
2612 | 2611 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2613 | 2612 | os.environ.get('PATH','').split(os.pathsep)] |
|
2614 | 2613 | path = filter(os.path.isdir,path) |
|
2615 | 2614 | |
|
2616 | 2615 | syscmdlist = [] |
|
2617 | 2616 | # Now define isexec in a cross platform manner. |
|
2618 | 2617 | if os.name == 'posix': |
|
2619 | 2618 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2620 | 2619 | os.access(fname,os.X_OK) |
|
2621 | 2620 | else: |
|
2622 | 2621 | try: |
|
2623 | 2622 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2624 | 2623 | except KeyError: |
|
2625 | 2624 | winext = 'exe|com|bat|py' |
|
2626 | 2625 | if 'py' not in winext: |
|
2627 | 2626 | winext += '|py' |
|
2628 | 2627 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2629 | 2628 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2630 | 2629 | savedir = os.getcwd() |
|
2631 | 2630 | |
|
2632 | 2631 | # Now walk the paths looking for executables to alias. |
|
2633 | 2632 | try: |
|
2634 | 2633 | # write the whole loop for posix/Windows so we don't have an if in |
|
2635 | 2634 | # the innermost part |
|
2636 | 2635 | if os.name == 'posix': |
|
2637 | 2636 | for pdir in path: |
|
2638 | 2637 | os.chdir(pdir) |
|
2639 | 2638 | for ff in os.listdir(pdir): |
|
2640 | 2639 | if isexec(ff): |
|
2641 | 2640 | try: |
|
2642 | 2641 | # Removes dots from the name since ipython |
|
2643 | 2642 | # will assume names with dots to be python. |
|
2644 | 2643 | self.shell.alias_manager.define_alias( |
|
2645 | 2644 | ff.replace('.',''), ff) |
|
2646 | 2645 | except InvalidAliasError: |
|
2647 | 2646 | pass |
|
2648 | 2647 | else: |
|
2649 | 2648 | syscmdlist.append(ff) |
|
2650 | 2649 | else: |
|
2651 | 2650 | no_alias = self.shell.alias_manager.no_alias |
|
2652 | 2651 | for pdir in path: |
|
2653 | 2652 | os.chdir(pdir) |
|
2654 | 2653 | for ff in os.listdir(pdir): |
|
2655 | 2654 | base, ext = os.path.splitext(ff) |
|
2656 | 2655 | if isexec(ff) and base.lower() not in no_alias: |
|
2657 | 2656 | if ext.lower() == '.exe': |
|
2658 | 2657 | ff = base |
|
2659 | 2658 | try: |
|
2660 | 2659 | # Removes dots from the name since ipython |
|
2661 | 2660 | # will assume names with dots to be python. |
|
2662 | 2661 | self.shell.alias_manager.define_alias( |
|
2663 | 2662 | base.lower().replace('.',''), ff) |
|
2664 | 2663 | except InvalidAliasError: |
|
2665 | 2664 | pass |
|
2666 | 2665 | syscmdlist.append(ff) |
|
2667 | 2666 | db = self.db |
|
2668 | 2667 | db['syscmdlist'] = syscmdlist |
|
2669 | 2668 | finally: |
|
2670 | 2669 | os.chdir(savedir) |
|
2671 | 2670 | |
|
2672 | 2671 | @testdec.skip_doctest |
|
2673 | 2672 | def magic_pwd(self, parameter_s = ''): |
|
2674 | 2673 | """Return the current working directory path. |
|
2675 | 2674 | |
|
2676 | 2675 | Examples |
|
2677 | 2676 | -------- |
|
2678 | 2677 | :: |
|
2679 | 2678 | |
|
2680 | 2679 | In [9]: pwd |
|
2681 | 2680 | Out[9]: '/home/tsuser/sprint/ipython' |
|
2682 | 2681 | """ |
|
2683 | 2682 | return os.getcwd() |
|
2684 | 2683 | |
|
2685 | 2684 | @testdec.skip_doctest |
|
2686 | 2685 | def magic_cd(self, parameter_s=''): |
|
2687 | 2686 | """Change the current working directory. |
|
2688 | 2687 | |
|
2689 | 2688 | This command automatically maintains an internal list of directories |
|
2690 | 2689 | you visit during your IPython session, in the variable _dh. The |
|
2691 | 2690 | command %dhist shows this history nicely formatted. You can also |
|
2692 | 2691 | do 'cd -<tab>' to see directory history conveniently. |
|
2693 | 2692 | |
|
2694 | 2693 | Usage: |
|
2695 | 2694 | |
|
2696 | 2695 | cd 'dir': changes to directory 'dir'. |
|
2697 | 2696 | |
|
2698 | 2697 | cd -: changes to the last visited directory. |
|
2699 | 2698 | |
|
2700 | 2699 | cd -<n>: changes to the n-th directory in the directory history. |
|
2701 | 2700 | |
|
2702 | 2701 | cd --foo: change to directory that matches 'foo' in history |
|
2703 | 2702 | |
|
2704 | 2703 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2705 | 2704 | (note: cd <bookmark_name> is enough if there is no |
|
2706 | 2705 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2707 | 2706 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2708 | 2707 | |
|
2709 | 2708 | Options: |
|
2710 | 2709 | |
|
2711 | 2710 | -q: quiet. Do not print the working directory after the cd command is |
|
2712 | 2711 | executed. By default IPython's cd command does print this directory, |
|
2713 | 2712 | since the default prompts do not display path information. |
|
2714 | 2713 | |
|
2715 | 2714 | Note that !cd doesn't work for this purpose because the shell where |
|
2716 | 2715 | !command runs is immediately discarded after executing 'command'. |
|
2717 | 2716 | |
|
2718 | 2717 | Examples |
|
2719 | 2718 | -------- |
|
2720 | 2719 | :: |
|
2721 | 2720 | |
|
2722 | 2721 | In [10]: cd parent/child |
|
2723 | 2722 | /home/tsuser/parent/child |
|
2724 | 2723 | """ |
|
2725 | 2724 | |
|
2726 | 2725 | parameter_s = parameter_s.strip() |
|
2727 | 2726 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2728 | 2727 | |
|
2729 | 2728 | oldcwd = os.getcwd() |
|
2730 | 2729 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2731 | 2730 | # jump in directory history by number |
|
2732 | 2731 | if numcd: |
|
2733 | 2732 | nn = int(numcd.group(2)) |
|
2734 | 2733 | try: |
|
2735 | 2734 | ps = self.shell.user_ns['_dh'][nn] |
|
2736 | 2735 | except IndexError: |
|
2737 | 2736 | print 'The requested directory does not exist in history.' |
|
2738 | 2737 | return |
|
2739 | 2738 | else: |
|
2740 | 2739 | opts = {} |
|
2741 | 2740 | elif parameter_s.startswith('--'): |
|
2742 | 2741 | ps = None |
|
2743 | 2742 | fallback = None |
|
2744 | 2743 | pat = parameter_s[2:] |
|
2745 | 2744 | dh = self.shell.user_ns['_dh'] |
|
2746 | 2745 | # first search only by basename (last component) |
|
2747 | 2746 | for ent in reversed(dh): |
|
2748 | 2747 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2749 | 2748 | ps = ent |
|
2750 | 2749 | break |
|
2751 | 2750 | |
|
2752 | 2751 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2753 | 2752 | fallback = ent |
|
2754 | 2753 | |
|
2755 | 2754 | # if we have no last part match, pick the first full path match |
|
2756 | 2755 | if ps is None: |
|
2757 | 2756 | ps = fallback |
|
2758 | 2757 | |
|
2759 | 2758 | if ps is None: |
|
2760 | 2759 | print "No matching entry in directory history" |
|
2761 | 2760 | return |
|
2762 | 2761 | else: |
|
2763 | 2762 | opts = {} |
|
2764 | 2763 | |
|
2765 | 2764 | |
|
2766 | 2765 | else: |
|
2767 | 2766 | #turn all non-space-escaping backslashes to slashes, |
|
2768 | 2767 | # for c:\windows\directory\names\ |
|
2769 | 2768 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2770 | 2769 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2771 | 2770 | # jump to previous |
|
2772 | 2771 | if ps == '-': |
|
2773 | 2772 | try: |
|
2774 | 2773 | ps = self.shell.user_ns['_dh'][-2] |
|
2775 | 2774 | except IndexError: |
|
2776 | 2775 | raise UsageError('%cd -: No previous directory to change to.') |
|
2777 | 2776 | # jump to bookmark if needed |
|
2778 | 2777 | else: |
|
2779 | 2778 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2780 | 2779 | bkms = self.db.get('bookmarks', {}) |
|
2781 | 2780 | |
|
2782 | 2781 | if bkms.has_key(ps): |
|
2783 | 2782 | target = bkms[ps] |
|
2784 | 2783 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2785 | 2784 | ps = target |
|
2786 | 2785 | else: |
|
2787 | 2786 | if opts.has_key('b'): |
|
2788 | 2787 | raise UsageError("Bookmark '%s' not found. " |
|
2789 | 2788 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2790 | 2789 | |
|
2791 | 2790 | # at this point ps should point to the target dir |
|
2792 | 2791 | if ps: |
|
2793 | 2792 | try: |
|
2794 | 2793 | os.chdir(os.path.expanduser(ps)) |
|
2795 | 2794 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2796 | 2795 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2797 | 2796 | except OSError: |
|
2798 | 2797 | print sys.exc_info()[1] |
|
2799 | 2798 | else: |
|
2800 | 2799 | cwd = os.getcwd() |
|
2801 | 2800 | dhist = self.shell.user_ns['_dh'] |
|
2802 | 2801 | if oldcwd != cwd: |
|
2803 | 2802 | dhist.append(cwd) |
|
2804 | 2803 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2805 | 2804 | |
|
2806 | 2805 | else: |
|
2807 | 2806 | os.chdir(self.shell.home_dir) |
|
2808 | 2807 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2809 | 2808 | set_term_title('IPython: ' + '~') |
|
2810 | 2809 | cwd = os.getcwd() |
|
2811 | 2810 | dhist = self.shell.user_ns['_dh'] |
|
2812 | 2811 | |
|
2813 | 2812 | if oldcwd != cwd: |
|
2814 | 2813 | dhist.append(cwd) |
|
2815 | 2814 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2816 | 2815 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2817 | 2816 | print self.shell.user_ns['_dh'][-1] |
|
2818 | 2817 | |
|
2819 | 2818 | |
|
2820 | 2819 | def magic_env(self, parameter_s=''): |
|
2821 | 2820 | """List environment variables.""" |
|
2822 | 2821 | |
|
2823 | 2822 | return os.environ.data |
|
2824 | 2823 | |
|
2825 | 2824 | def magic_pushd(self, parameter_s=''): |
|
2826 | 2825 | """Place the current dir on stack and change directory. |
|
2827 | 2826 | |
|
2828 | 2827 | Usage:\\ |
|
2829 | 2828 | %pushd ['dirname'] |
|
2830 | 2829 | """ |
|
2831 | 2830 | |
|
2832 | 2831 | dir_s = self.shell.dir_stack |
|
2833 | 2832 | tgt = os.path.expanduser(parameter_s) |
|
2834 | 2833 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2835 | 2834 | if tgt: |
|
2836 | 2835 | self.magic_cd(parameter_s) |
|
2837 | 2836 | dir_s.insert(0,cwd) |
|
2838 | 2837 | return self.magic_dirs() |
|
2839 | 2838 | |
|
2840 | 2839 | def magic_popd(self, parameter_s=''): |
|
2841 | 2840 | """Change to directory popped off the top of the stack. |
|
2842 | 2841 | """ |
|
2843 | 2842 | if not self.shell.dir_stack: |
|
2844 | 2843 | raise UsageError("%popd on empty stack") |
|
2845 | 2844 | top = self.shell.dir_stack.pop(0) |
|
2846 | 2845 | self.magic_cd(top) |
|
2847 | 2846 | print "popd ->",top |
|
2848 | 2847 | |
|
2849 | 2848 | def magic_dirs(self, parameter_s=''): |
|
2850 | 2849 | """Return the current directory stack.""" |
|
2851 | 2850 | |
|
2852 | 2851 | return self.shell.dir_stack |
|
2853 | 2852 | |
|
2854 | 2853 | def magic_dhist(self, parameter_s=''): |
|
2855 | 2854 | """Print your history of visited directories. |
|
2856 | 2855 | |
|
2857 | 2856 | %dhist -> print full history\\ |
|
2858 | 2857 | %dhist n -> print last n entries only\\ |
|
2859 | 2858 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2860 | 2859 | |
|
2861 | 2860 | This history is automatically maintained by the %cd command, and |
|
2862 | 2861 | always available as the global list variable _dh. You can use %cd -<n> |
|
2863 | 2862 | to go to directory number <n>. |
|
2864 | 2863 | |
|
2865 | 2864 | Note that most of time, you should view directory history by entering |
|
2866 | 2865 | cd -<TAB>. |
|
2867 | 2866 | |
|
2868 | 2867 | """ |
|
2869 | 2868 | |
|
2870 | 2869 | dh = self.shell.user_ns['_dh'] |
|
2871 | 2870 | if parameter_s: |
|
2872 | 2871 | try: |
|
2873 | 2872 | args = map(int,parameter_s.split()) |
|
2874 | 2873 | except: |
|
2875 | 2874 | self.arg_err(Magic.magic_dhist) |
|
2876 | 2875 | return |
|
2877 | 2876 | if len(args) == 1: |
|
2878 | 2877 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2879 | 2878 | elif len(args) == 2: |
|
2880 | 2879 | ini,fin = args |
|
2881 | 2880 | else: |
|
2882 | 2881 | self.arg_err(Magic.magic_dhist) |
|
2883 | 2882 | return |
|
2884 | 2883 | else: |
|
2885 | 2884 | ini,fin = 0,len(dh) |
|
2886 | 2885 | nlprint(dh, |
|
2887 | 2886 | header = 'Directory history (kept in _dh)', |
|
2888 | 2887 | start=ini,stop=fin) |
|
2889 | 2888 | |
|
2890 | 2889 | @testdec.skip_doctest |
|
2891 | 2890 | def magic_sc(self, parameter_s=''): |
|
2892 | 2891 | """Shell capture - execute a shell command and capture its output. |
|
2893 | 2892 | |
|
2894 | 2893 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2895 | 2894 | |
|
2896 | 2895 | You should use the form 'var = !command' instead. Example: |
|
2897 | 2896 | |
|
2898 | 2897 | "%sc -l myfiles = ls ~" should now be written as |
|
2899 | 2898 | |
|
2900 | 2899 | "myfiles = !ls ~" |
|
2901 | 2900 | |
|
2902 | 2901 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2903 | 2902 | below. |
|
2904 | 2903 | |
|
2905 | 2904 | -- |
|
2906 | 2905 | %sc [options] varname=command |
|
2907 | 2906 | |
|
2908 | 2907 | IPython will run the given command using commands.getoutput(), and |
|
2909 | 2908 | will then update the user's interactive namespace with a variable |
|
2910 | 2909 | called varname, containing the value of the call. Your command can |
|
2911 | 2910 | contain shell wildcards, pipes, etc. |
|
2912 | 2911 | |
|
2913 | 2912 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2914 | 2913 | supply must follow Python's standard conventions for valid names. |
|
2915 | 2914 | |
|
2916 | 2915 | (A special format without variable name exists for internal use) |
|
2917 | 2916 | |
|
2918 | 2917 | Options: |
|
2919 | 2918 | |
|
2920 | 2919 | -l: list output. Split the output on newlines into a list before |
|
2921 | 2920 | assigning it to the given variable. By default the output is stored |
|
2922 | 2921 | as a single string. |
|
2923 | 2922 | |
|
2924 | 2923 | -v: verbose. Print the contents of the variable. |
|
2925 | 2924 | |
|
2926 | 2925 | In most cases you should not need to split as a list, because the |
|
2927 | 2926 | returned value is a special type of string which can automatically |
|
2928 | 2927 | provide its contents either as a list (split on newlines) or as a |
|
2929 | 2928 | space-separated string. These are convenient, respectively, either |
|
2930 | 2929 | for sequential processing or to be passed to a shell command. |
|
2931 | 2930 | |
|
2932 | 2931 | For example: |
|
2933 | 2932 | |
|
2934 | 2933 | # all-random |
|
2935 | 2934 | |
|
2936 | 2935 | # Capture into variable a |
|
2937 | 2936 | In [1]: sc a=ls *py |
|
2938 | 2937 | |
|
2939 | 2938 | # a is a string with embedded newlines |
|
2940 | 2939 | In [2]: a |
|
2941 | 2940 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2942 | 2941 | |
|
2943 | 2942 | # which can be seen as a list: |
|
2944 | 2943 | In [3]: a.l |
|
2945 | 2944 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2946 | 2945 | |
|
2947 | 2946 | # or as a whitespace-separated string: |
|
2948 | 2947 | In [4]: a.s |
|
2949 | 2948 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2950 | 2949 | |
|
2951 | 2950 | # a.s is useful to pass as a single command line: |
|
2952 | 2951 | In [5]: !wc -l $a.s |
|
2953 | 2952 | 146 setup.py |
|
2954 | 2953 | 130 win32_manual_post_install.py |
|
2955 | 2954 | 276 total |
|
2956 | 2955 | |
|
2957 | 2956 | # while the list form is useful to loop over: |
|
2958 | 2957 | In [6]: for f in a.l: |
|
2959 | 2958 | ...: !wc -l $f |
|
2960 | 2959 | ...: |
|
2961 | 2960 | 146 setup.py |
|
2962 | 2961 | 130 win32_manual_post_install.py |
|
2963 | 2962 | |
|
2964 | 2963 | Similiarly, the lists returned by the -l option are also special, in |
|
2965 | 2964 | the sense that you can equally invoke the .s attribute on them to |
|
2966 | 2965 | automatically get a whitespace-separated string from their contents: |
|
2967 | 2966 | |
|
2968 | 2967 | In [7]: sc -l b=ls *py |
|
2969 | 2968 | |
|
2970 | 2969 | In [8]: b |
|
2971 | 2970 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2972 | 2971 | |
|
2973 | 2972 | In [9]: b.s |
|
2974 | 2973 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2975 | 2974 | |
|
2976 | 2975 | In summary, both the lists and strings used for ouptut capture have |
|
2977 | 2976 | the following special attributes: |
|
2978 | 2977 | |
|
2979 | 2978 | .l (or .list) : value as list. |
|
2980 | 2979 | .n (or .nlstr): value as newline-separated string. |
|
2981 | 2980 | .s (or .spstr): value as space-separated string. |
|
2982 | 2981 | """ |
|
2983 | 2982 | |
|
2984 | 2983 | opts,args = self.parse_options(parameter_s,'lv') |
|
2985 | 2984 | # Try to get a variable name and command to run |
|
2986 | 2985 | try: |
|
2987 | 2986 | # the variable name must be obtained from the parse_options |
|
2988 | 2987 | # output, which uses shlex.split to strip options out. |
|
2989 | 2988 | var,_ = args.split('=',1) |
|
2990 | 2989 | var = var.strip() |
|
2991 | 2990 | # But the the command has to be extracted from the original input |
|
2992 | 2991 | # parameter_s, not on what parse_options returns, to avoid the |
|
2993 | 2992 | # quote stripping which shlex.split performs on it. |
|
2994 | 2993 | _,cmd = parameter_s.split('=',1) |
|
2995 | 2994 | except ValueError: |
|
2996 | 2995 | var,cmd = '','' |
|
2997 | 2996 | # If all looks ok, proceed |
|
2998 | 2997 | split = 'l' in opts |
|
2999 | 2998 | out = self.shell.getoutput(cmd, split=split) |
|
3000 | 2999 | if opts.has_key('v'): |
|
3001 | 3000 | print '%s ==\n%s' % (var,pformat(out)) |
|
3002 | 3001 | if var: |
|
3003 | 3002 | self.shell.user_ns.update({var:out}) |
|
3004 | 3003 | else: |
|
3005 | 3004 | return out |
|
3006 | 3005 | |
|
3007 | 3006 | def magic_sx(self, parameter_s=''): |
|
3008 | 3007 | """Shell execute - run a shell command and capture its output. |
|
3009 | 3008 | |
|
3010 | 3009 | %sx command |
|
3011 | 3010 | |
|
3012 | 3011 | IPython will run the given command using commands.getoutput(), and |
|
3013 | 3012 | return the result formatted as a list (split on '\\n'). Since the |
|
3014 | 3013 | output is _returned_, it will be stored in ipython's regular output |
|
3015 | 3014 | cache Out[N] and in the '_N' automatic variables. |
|
3016 | 3015 | |
|
3017 | 3016 | Notes: |
|
3018 | 3017 | |
|
3019 | 3018 | 1) If an input line begins with '!!', then %sx is automatically |
|
3020 | 3019 | invoked. That is, while: |
|
3021 | 3020 | !ls |
|
3022 | 3021 | causes ipython to simply issue system('ls'), typing |
|
3023 | 3022 | !!ls |
|
3024 | 3023 | is a shorthand equivalent to: |
|
3025 | 3024 | %sx ls |
|
3026 | 3025 | |
|
3027 | 3026 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
3028 | 3027 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
3029 | 3028 | to process line-oriented shell output via further python commands. |
|
3030 | 3029 | %sc is meant to provide much finer control, but requires more |
|
3031 | 3030 | typing. |
|
3032 | 3031 | |
|
3033 | 3032 | 3) Just like %sc -l, this is a list with special attributes: |
|
3034 | 3033 | |
|
3035 | 3034 | .l (or .list) : value as list. |
|
3036 | 3035 | .n (or .nlstr): value as newline-separated string. |
|
3037 | 3036 | .s (or .spstr): value as whitespace-separated string. |
|
3038 | 3037 | |
|
3039 | 3038 | This is very useful when trying to use such lists as arguments to |
|
3040 | 3039 | system commands.""" |
|
3041 | 3040 | |
|
3042 | 3041 | if parameter_s: |
|
3043 | 3042 | return self.shell.getoutput(parameter_s) |
|
3044 | 3043 | |
|
3045 | 3044 | |
|
3046 | 3045 | def magic_bookmark(self, parameter_s=''): |
|
3047 | 3046 | """Manage IPython's bookmark system. |
|
3048 | 3047 | |
|
3049 | 3048 | %bookmark <name> - set bookmark to current dir |
|
3050 | 3049 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3051 | 3050 | %bookmark -l - list all bookmarks |
|
3052 | 3051 | %bookmark -d <name> - remove bookmark |
|
3053 | 3052 | %bookmark -r - remove all bookmarks |
|
3054 | 3053 | |
|
3055 | 3054 | You can later on access a bookmarked folder with: |
|
3056 | 3055 | %cd -b <name> |
|
3057 | 3056 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3058 | 3057 | there is such a bookmark defined. |
|
3059 | 3058 | |
|
3060 | 3059 | Your bookmarks persist through IPython sessions, but they are |
|
3061 | 3060 | associated with each profile.""" |
|
3062 | 3061 | |
|
3063 | 3062 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3064 | 3063 | if len(args) > 2: |
|
3065 | 3064 | raise UsageError("%bookmark: too many arguments") |
|
3066 | 3065 | |
|
3067 | 3066 | bkms = self.db.get('bookmarks',{}) |
|
3068 | 3067 | |
|
3069 | 3068 | if opts.has_key('d'): |
|
3070 | 3069 | try: |
|
3071 | 3070 | todel = args[0] |
|
3072 | 3071 | except IndexError: |
|
3073 | 3072 | raise UsageError( |
|
3074 | 3073 | "%bookmark -d: must provide a bookmark to delete") |
|
3075 | 3074 | else: |
|
3076 | 3075 | try: |
|
3077 | 3076 | del bkms[todel] |
|
3078 | 3077 | except KeyError: |
|
3079 | 3078 | raise UsageError( |
|
3080 | 3079 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3081 | 3080 | |
|
3082 | 3081 | elif opts.has_key('r'): |
|
3083 | 3082 | bkms = {} |
|
3084 | 3083 | elif opts.has_key('l'): |
|
3085 | 3084 | bks = bkms.keys() |
|
3086 | 3085 | bks.sort() |
|
3087 | 3086 | if bks: |
|
3088 | 3087 | size = max(map(len,bks)) |
|
3089 | 3088 | else: |
|
3090 | 3089 | size = 0 |
|
3091 | 3090 | fmt = '%-'+str(size)+'s -> %s' |
|
3092 | 3091 | print 'Current bookmarks:' |
|
3093 | 3092 | for bk in bks: |
|
3094 | 3093 | print fmt % (bk,bkms[bk]) |
|
3095 | 3094 | else: |
|
3096 | 3095 | if not args: |
|
3097 | 3096 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3098 | 3097 | elif len(args)==1: |
|
3099 | 3098 | bkms[args[0]] = os.getcwd() |
|
3100 | 3099 | elif len(args)==2: |
|
3101 | 3100 | bkms[args[0]] = args[1] |
|
3102 | 3101 | self.db['bookmarks'] = bkms |
|
3103 | 3102 | |
|
3104 | 3103 | def magic_pycat(self, parameter_s=''): |
|
3105 | 3104 | """Show a syntax-highlighted file through a pager. |
|
3106 | 3105 | |
|
3107 | 3106 | This magic is similar to the cat utility, but it will assume the file |
|
3108 | 3107 | to be Python source and will show it with syntax highlighting. """ |
|
3109 | 3108 | |
|
3110 | 3109 | try: |
|
3111 | 3110 | filename = get_py_filename(parameter_s) |
|
3112 | 3111 | cont = file_read(filename) |
|
3113 | 3112 | except IOError: |
|
3114 | 3113 | try: |
|
3115 | 3114 | cont = eval(parameter_s,self.user_ns) |
|
3116 | 3115 | except NameError: |
|
3117 | 3116 | cont = None |
|
3118 | 3117 | if cont is None: |
|
3119 | 3118 | print "Error: no such file or variable" |
|
3120 | 3119 | return |
|
3121 | 3120 | |
|
3122 | 3121 | page.page(self.shell.pycolorize(cont)) |
|
3123 | 3122 | |
|
3124 | 3123 | def _rerun_pasted(self): |
|
3125 | 3124 | """ Rerun a previously pasted command. |
|
3126 | 3125 | """ |
|
3127 | 3126 | b = self.user_ns.get('pasted_block', None) |
|
3128 | 3127 | if b is None: |
|
3129 | 3128 | raise UsageError('No previous pasted block available') |
|
3130 | 3129 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3131 | 3130 | exec b in self.user_ns |
|
3132 | 3131 | |
|
3133 | 3132 | def _get_pasted_lines(self, sentinel): |
|
3134 | 3133 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3135 | 3134 | """ |
|
3136 | 3135 | from IPython.core import interactiveshell |
|
3137 | 3136 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3138 | 3137 | while True: |
|
3139 | 3138 | l = interactiveshell.raw_input_original(':') |
|
3140 | 3139 | if l == sentinel: |
|
3141 | 3140 | return |
|
3142 | 3141 | else: |
|
3143 | 3142 | yield l |
|
3144 | 3143 | |
|
3145 | 3144 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3146 | 3145 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3147 | 3146 | code. |
|
3148 | 3147 | """ |
|
3149 | 3148 | # Regular expressions that declare text we strip from the input: |
|
3150 | 3149 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3151 | 3150 | r'^\s*(\s?>)+', # Python input prompt |
|
3152 | 3151 | r'^\s*\.{3,}', # Continuation prompts |
|
3153 | 3152 | r'^\++', |
|
3154 | 3153 | ] |
|
3155 | 3154 | |
|
3156 | 3155 | strip_from_start = map(re.compile,strip_re) |
|
3157 | 3156 | |
|
3158 | 3157 | lines = [] |
|
3159 | 3158 | for l in raw_lines: |
|
3160 | 3159 | for pat in strip_from_start: |
|
3161 | 3160 | l = pat.sub('',l) |
|
3162 | 3161 | lines.append(l) |
|
3163 | 3162 | |
|
3164 | 3163 | block = "\n".join(lines) + '\n' |
|
3165 | 3164 | #print "block:\n",block |
|
3166 | 3165 | return block |
|
3167 | 3166 | |
|
3168 | 3167 | def _execute_block(self, block, par): |
|
3169 | 3168 | """ Execute a block, or store it in a variable, per the user's request. |
|
3170 | 3169 | """ |
|
3171 | 3170 | if not par: |
|
3172 | 3171 | b = textwrap.dedent(block) |
|
3173 | 3172 | self.user_ns['pasted_block'] = b |
|
3174 | 3173 | exec b in self.user_ns |
|
3175 | 3174 | else: |
|
3176 | 3175 | self.user_ns[par] = SList(block.splitlines()) |
|
3177 | 3176 | print "Block assigned to '%s'" % par |
|
3178 | 3177 | |
|
3179 | 3178 | def magic_quickref(self,arg): |
|
3180 | 3179 | """ Show a quick reference sheet """ |
|
3181 | 3180 | import IPython.core.usage |
|
3182 | 3181 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3183 | 3182 | |
|
3184 | 3183 | page.page(qr) |
|
3185 | 3184 | |
|
3186 | 3185 | def magic_doctest_mode(self,parameter_s=''): |
|
3187 | 3186 | """Toggle doctest mode on and off. |
|
3188 | 3187 | |
|
3189 | 3188 | This mode is intended to make IPython behave as much as possible like a |
|
3190 | 3189 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3191 | 3190 | and output look. This makes it easy to copy and paste parts of a |
|
3192 | 3191 | session into doctests. It does so by: |
|
3193 | 3192 | |
|
3194 | 3193 | - Changing the prompts to the classic ``>>>`` ones. |
|
3195 | 3194 | - Changing the exception reporting mode to 'Plain'. |
|
3196 | 3195 | - Disabling pretty-printing of output. |
|
3197 | 3196 | |
|
3198 | 3197 | Note that IPython also supports the pasting of code snippets that have |
|
3199 | 3198 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3200 | 3199 | doctests from files or docstrings (even if they have leading |
|
3201 | 3200 | whitespace), and the code will execute correctly. You can then use |
|
3202 | 3201 | '%history -t' to see the translated history; this will give you the |
|
3203 | 3202 | input after removal of all the leading prompts and whitespace, which |
|
3204 | 3203 | can be pasted back into an editor. |
|
3205 | 3204 | |
|
3206 | 3205 | With these features, you can switch into this mode easily whenever you |
|
3207 | 3206 | need to do testing and changes to doctests, without having to leave |
|
3208 | 3207 | your existing IPython session. |
|
3209 | 3208 | """ |
|
3210 | 3209 | |
|
3211 | 3210 | from IPython.utils.ipstruct import Struct |
|
3212 | 3211 | |
|
3213 | 3212 | # Shorthands |
|
3214 | 3213 | shell = self.shell |
|
3215 | 3214 | oc = shell.displayhook |
|
3216 | 3215 | meta = shell.meta |
|
3217 | 3216 | disp_formatter = self.shell.display_formatter |
|
3218 | 3217 | ptformatter = disp_formatter.formatters['text/plain'] |
|
3219 | 3218 | # dstore is a data store kept in the instance metadata bag to track any |
|
3220 | 3219 | # changes we make, so we can undo them later. |
|
3221 | 3220 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3222 | 3221 | save_dstore = dstore.setdefault |
|
3223 | 3222 | |
|
3224 | 3223 | # save a few values we'll need to recover later |
|
3225 | 3224 | mode = save_dstore('mode',False) |
|
3226 | 3225 | save_dstore('rc_pprint',ptformatter.pprint) |
|
3227 | 3226 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3228 | 3227 | save_dstore('rc_separate_out',shell.separate_out) |
|
3229 | 3228 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3230 | 3229 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3231 | 3230 | save_dstore('rc_separate_in',shell.separate_in) |
|
3232 | 3231 | save_dstore('rc_plain_text_only',disp_formatter.plain_text_only) |
|
3233 | 3232 | |
|
3234 | 3233 | if mode == False: |
|
3235 | 3234 | # turn on |
|
3236 | 3235 | oc.prompt1.p_template = '>>> ' |
|
3237 | 3236 | oc.prompt2.p_template = '... ' |
|
3238 | 3237 | oc.prompt_out.p_template = '' |
|
3239 | 3238 | |
|
3240 | 3239 | # Prompt separators like plain python |
|
3241 | 3240 | oc.input_sep = oc.prompt1.sep = '' |
|
3242 | 3241 | oc.output_sep = '' |
|
3243 | 3242 | oc.output_sep2 = '' |
|
3244 | 3243 | |
|
3245 | 3244 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3246 | 3245 | oc.prompt_out.pad_left = False |
|
3247 | 3246 | |
|
3248 | 3247 | ptformatter.pprint = False |
|
3249 | 3248 | disp_formatter.plain_text_only = True |
|
3250 | 3249 | |
|
3251 | 3250 | shell.magic_xmode('Plain') |
|
3252 | 3251 | else: |
|
3253 | 3252 | # turn off |
|
3254 | 3253 | oc.prompt1.p_template = shell.prompt_in1 |
|
3255 | 3254 | oc.prompt2.p_template = shell.prompt_in2 |
|
3256 | 3255 | oc.prompt_out.p_template = shell.prompt_out |
|
3257 | 3256 | |
|
3258 | 3257 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3259 | 3258 | |
|
3260 | 3259 | oc.output_sep = dstore.rc_separate_out |
|
3261 | 3260 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3262 | 3261 | |
|
3263 | 3262 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3264 | 3263 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3265 | 3264 | |
|
3266 | 3265 | ptformatter.pprint = dstore.rc_pprint |
|
3267 | 3266 | disp_formatter.plain_text_only = dstore.rc_plain_text_only |
|
3268 | 3267 | |
|
3269 | 3268 | shell.magic_xmode(dstore.xmode) |
|
3270 | 3269 | |
|
3271 | 3270 | # Store new mode and inform |
|
3272 | 3271 | dstore.mode = bool(1-int(mode)) |
|
3273 | 3272 | mode_label = ['OFF','ON'][dstore.mode] |
|
3274 | 3273 | print 'Doctest mode is:', mode_label |
|
3275 | 3274 | |
|
3276 | 3275 | def magic_gui(self, parameter_s=''): |
|
3277 | 3276 | """Enable or disable IPython GUI event loop integration. |
|
3278 | 3277 | |
|
3279 | 3278 | %gui [GUINAME] |
|
3280 | 3279 | |
|
3281 | 3280 | This magic replaces IPython's threaded shells that were activated |
|
3282 | 3281 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3283 | 3282 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3284 | 3283 | interrupts should work without any problems. The following toolkits |
|
3285 | 3284 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3286 | 3285 | |
|
3287 | 3286 | %gui wx # enable wxPython event loop integration |
|
3288 | 3287 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3289 | 3288 | %gui gtk # enable PyGTK event loop integration |
|
3290 | 3289 | %gui tk # enable Tk event loop integration |
|
3291 | 3290 | %gui # disable all event loop integration |
|
3292 | 3291 | |
|
3293 | 3292 | WARNING: after any of these has been called you can simply create |
|
3294 | 3293 | an application object, but DO NOT start the event loop yourself, as |
|
3295 | 3294 | we have already handled that. |
|
3296 | 3295 | """ |
|
3297 | 3296 | from IPython.lib.inputhook import enable_gui |
|
3298 | 3297 | opts, arg = self.parse_options(parameter_s, '') |
|
3299 | 3298 | if arg=='': arg = None |
|
3300 | 3299 | return enable_gui(arg) |
|
3301 | 3300 | |
|
3302 | 3301 | def magic_load_ext(self, module_str): |
|
3303 | 3302 | """Load an IPython extension by its module name.""" |
|
3304 | 3303 | return self.extension_manager.load_extension(module_str) |
|
3305 | 3304 | |
|
3306 | 3305 | def magic_unload_ext(self, module_str): |
|
3307 | 3306 | """Unload an IPython extension by its module name.""" |
|
3308 | 3307 | self.extension_manager.unload_extension(module_str) |
|
3309 | 3308 | |
|
3310 | 3309 | def magic_reload_ext(self, module_str): |
|
3311 | 3310 | """Reload an IPython extension by its module name.""" |
|
3312 | 3311 | self.extension_manager.reload_extension(module_str) |
|
3313 | 3312 | |
|
3314 | 3313 | @testdec.skip_doctest |
|
3315 | 3314 | def magic_install_profiles(self, s): |
|
3316 | 3315 | """Install the default IPython profiles into the .ipython dir. |
|
3317 | 3316 | |
|
3318 | 3317 | If the default profiles have already been installed, they will not |
|
3319 | 3318 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3320 | 3319 | option:: |
|
3321 | 3320 | |
|
3322 | 3321 | In [1]: %install_profiles -o |
|
3323 | 3322 | """ |
|
3324 | 3323 | if '-o' in s: |
|
3325 | 3324 | overwrite = True |
|
3326 | 3325 | else: |
|
3327 | 3326 | overwrite = False |
|
3328 | 3327 | from IPython.config import profile |
|
3329 | 3328 | profile_dir = os.path.split(profile.__file__)[0] |
|
3330 | 3329 | ipython_dir = self.ipython_dir |
|
3331 | 3330 | files = os.listdir(profile_dir) |
|
3332 | 3331 | |
|
3333 | 3332 | to_install = [] |
|
3334 | 3333 | for f in files: |
|
3335 | 3334 | if f.startswith('ipython_config'): |
|
3336 | 3335 | src = os.path.join(profile_dir, f) |
|
3337 | 3336 | dst = os.path.join(ipython_dir, f) |
|
3338 | 3337 | if (not os.path.isfile(dst)) or overwrite: |
|
3339 | 3338 | to_install.append((f, src, dst)) |
|
3340 | 3339 | if len(to_install)>0: |
|
3341 | 3340 | print "Installing profiles to: ", ipython_dir |
|
3342 | 3341 | for (f, src, dst) in to_install: |
|
3343 | 3342 | shutil.copy(src, dst) |
|
3344 | 3343 | print " %s" % f |
|
3345 | 3344 | |
|
3346 | 3345 | def magic_install_default_config(self, s): |
|
3347 | 3346 | """Install IPython's default config file into the .ipython dir. |
|
3348 | 3347 | |
|
3349 | 3348 | If the default config file (:file:`ipython_config.py`) is already |
|
3350 | 3349 | installed, it will not be overwritten. You can force overwriting |
|
3351 | 3350 | by using the ``-o`` option:: |
|
3352 | 3351 | |
|
3353 | 3352 | In [1]: %install_default_config |
|
3354 | 3353 | """ |
|
3355 | 3354 | if '-o' in s: |
|
3356 | 3355 | overwrite = True |
|
3357 | 3356 | else: |
|
3358 | 3357 | overwrite = False |
|
3359 | 3358 | from IPython.config import default |
|
3360 | 3359 | config_dir = os.path.split(default.__file__)[0] |
|
3361 | 3360 | ipython_dir = self.ipython_dir |
|
3362 | 3361 | default_config_file_name = 'ipython_config.py' |
|
3363 | 3362 | src = os.path.join(config_dir, default_config_file_name) |
|
3364 | 3363 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3365 | 3364 | if (not os.path.isfile(dst)) or overwrite: |
|
3366 | 3365 | shutil.copy(src, dst) |
|
3367 | 3366 | print "Installing default config file: %s" % dst |
|
3368 | 3367 | |
|
3369 | 3368 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3370 | 3369 | # handling and modify slightly %run |
|
3371 | 3370 | |
|
3372 | 3371 | @testdec.skip_doctest |
|
3373 | 3372 | def _pylab_magic_run(self, parameter_s=''): |
|
3374 | 3373 | Magic.magic_run(self, parameter_s, |
|
3375 | 3374 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3376 | 3375 | |
|
3377 | 3376 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3378 | 3377 | |
|
3379 | 3378 | @testdec.skip_doctest |
|
3380 | 3379 | def magic_pylab(self, s): |
|
3381 | 3380 | """Load numpy and matplotlib to work interactively. |
|
3382 | 3381 | |
|
3383 | 3382 | %pylab [GUINAME] |
|
3384 | 3383 | |
|
3385 | 3384 | This function lets you activate pylab (matplotlib, numpy and |
|
3386 | 3385 | interactive support) at any point during an IPython session. |
|
3387 | 3386 | |
|
3388 | 3387 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3389 | 3388 | pylab and mlab, as well as all names from numpy and pylab. |
|
3390 | 3389 | |
|
3391 | 3390 | Parameters |
|
3392 | 3391 | ---------- |
|
3393 | 3392 | guiname : optional |
|
3394 | 3393 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk', 'osx' or |
|
3395 | 3394 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3396 | 3395 | otherwise matplotlib's default (which you can override in your |
|
3397 | 3396 | matplotlib config file) is used. |
|
3398 | 3397 | |
|
3399 | 3398 | Examples |
|
3400 | 3399 | -------- |
|
3401 | 3400 | In this case, where the MPL default is TkAgg: |
|
3402 | 3401 | In [2]: %pylab |
|
3403 | 3402 | |
|
3404 | 3403 | Welcome to pylab, a matplotlib-based Python environment. |
|
3405 | 3404 | Backend in use: TkAgg |
|
3406 | 3405 | For more information, type 'help(pylab)'. |
|
3407 | 3406 | |
|
3408 | 3407 | But you can explicitly request a different backend: |
|
3409 | 3408 | In [3]: %pylab qt |
|
3410 | 3409 | |
|
3411 | 3410 | Welcome to pylab, a matplotlib-based Python environment. |
|
3412 | 3411 | Backend in use: Qt4Agg |
|
3413 | 3412 | For more information, type 'help(pylab)'. |
|
3414 | 3413 | """ |
|
3415 | 3414 | self.shell.enable_pylab(s) |
|
3416 | 3415 | |
|
3417 | 3416 | def magic_tb(self, s): |
|
3418 | 3417 | """Print the last traceback with the currently active exception mode. |
|
3419 | 3418 | |
|
3420 | 3419 | See %xmode for changing exception reporting modes.""" |
|
3421 | 3420 | self.shell.showtraceback() |
|
3422 | 3421 | |
|
3423 | 3422 | @testdec.skip_doctest |
|
3424 | 3423 | def magic_precision(self, s=''): |
|
3425 | 3424 | """Set floating point precision for pretty printing. |
|
3426 | 3425 | |
|
3427 | 3426 | Can set either integer precision or a format string. |
|
3428 | 3427 | |
|
3429 | 3428 | If numpy has been imported and precision is an int, |
|
3430 | 3429 | numpy display precision will also be set, via ``numpy.set_printoptions``. |
|
3431 | 3430 | |
|
3432 | 3431 | If no argument is given, defaults will be restored. |
|
3433 | 3432 | |
|
3434 | 3433 | Examples |
|
3435 | 3434 | -------- |
|
3436 | 3435 | :: |
|
3437 | 3436 | |
|
3438 | 3437 | In [1]: from math import pi |
|
3439 | 3438 | |
|
3440 | 3439 | In [2]: %precision 3 |
|
3441 | 3440 | Out[2]: '%.3f' |
|
3442 | 3441 | |
|
3443 | 3442 | In [3]: pi |
|
3444 | 3443 | Out[3]: 3.142 |
|
3445 | 3444 | |
|
3446 | 3445 | In [4]: %precision %i |
|
3447 | 3446 | Out[4]: '%i' |
|
3448 | 3447 | |
|
3449 | 3448 | In [5]: pi |
|
3450 | 3449 | Out[5]: 3 |
|
3451 | 3450 | |
|
3452 | 3451 | In [6]: %precision %e |
|
3453 | 3452 | Out[6]: '%e' |
|
3454 | 3453 | |
|
3455 | 3454 | In [7]: pi**10 |
|
3456 | 3455 | Out[7]: 9.364805e+04 |
|
3457 | 3456 | |
|
3458 | 3457 | In [8]: %precision |
|
3459 | 3458 | Out[8]: '%r' |
|
3460 | 3459 | |
|
3461 | 3460 | In [9]: pi**10 |
|
3462 | 3461 | Out[9]: 93648.047476082982 |
|
3463 | 3462 | |
|
3464 | 3463 | """ |
|
3465 | 3464 | |
|
3466 | 3465 | ptformatter = self.shell.display_formatter.formatters['text/plain'] |
|
3467 | 3466 | ptformatter.float_precision = s |
|
3468 | 3467 | return ptformatter.float_format |
|
3469 | 3468 | |
|
3470 | 3469 | # end Magic |
@@ -1,891 +1,891 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """Tools for inspecting Python objects. |
|
3 | 3 | |
|
4 | 4 | Uses syntax highlighting for presenting the various information elements. |
|
5 | 5 | |
|
6 | 6 | Similar in spirit to the inspect module, but all calls take a name argument to |
|
7 | 7 | reference the name under which an object is being read. |
|
8 | 8 | """ |
|
9 | 9 | |
|
10 | 10 | #***************************************************************************** |
|
11 | 11 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
12 | 12 | # |
|
13 | 13 | # Distributed under the terms of the BSD License. The full license is in |
|
14 | 14 | # the file COPYING, distributed as part of this software. |
|
15 | 15 | #***************************************************************************** |
|
16 | 16 | |
|
17 | 17 | __all__ = ['Inspector','InspectColors'] |
|
18 | 18 | |
|
19 | 19 | # stdlib modules |
|
20 | 20 | import __builtin__ |
|
21 | 21 | import StringIO |
|
22 | 22 | import inspect |
|
23 | 23 | import linecache |
|
24 | 24 | import os |
|
25 | 25 | import sys |
|
26 | 26 | import types |
|
27 | 27 | from collections import namedtuple |
|
28 | 28 | from itertools import izip_longest |
|
29 | 29 | |
|
30 | 30 | # IPython's own |
|
31 | 31 | from IPython.core import page |
|
32 | 32 | from IPython.external.Itpl import itpl |
|
33 | 33 | from IPython.utils import PyColorize |
|
34 |
|
|
|
34 | from IPython.utils import io | |
|
35 | 35 | from IPython.utils.text import indent |
|
36 | 36 | from IPython.utils.wildcard import list_namespace |
|
37 | 37 | from IPython.utils.coloransi import * |
|
38 | 38 | |
|
39 | 39 | #**************************************************************************** |
|
40 | 40 | # Builtin color schemes |
|
41 | 41 | |
|
42 | 42 | Colors = TermColors # just a shorthand |
|
43 | 43 | |
|
44 | 44 | # Build a few color schemes |
|
45 | 45 | NoColor = ColorScheme( |
|
46 | 46 | 'NoColor',{ |
|
47 | 47 | 'header' : Colors.NoColor, |
|
48 | 48 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) |
|
49 | 49 | } ) |
|
50 | 50 | |
|
51 | 51 | LinuxColors = ColorScheme( |
|
52 | 52 | 'Linux',{ |
|
53 | 53 | 'header' : Colors.LightRed, |
|
54 | 54 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
55 | 55 | } ) |
|
56 | 56 | |
|
57 | 57 | LightBGColors = ColorScheme( |
|
58 | 58 | 'LightBG',{ |
|
59 | 59 | 'header' : Colors.Red, |
|
60 | 60 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
61 | 61 | } ) |
|
62 | 62 | |
|
63 | 63 | # Build table of color schemes (needed by the parser) |
|
64 | 64 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], |
|
65 | 65 | 'Linux') |
|
66 | 66 | |
|
67 | 67 | #**************************************************************************** |
|
68 | 68 | # Auxiliary functions and objects |
|
69 | 69 | |
|
70 | 70 | # See the messaging spec for the definition of all these fields. This list |
|
71 | 71 | # effectively defines the order of display |
|
72 | 72 | info_fields = ['type_name', 'base_class', 'string_form', 'namespace', |
|
73 | 73 | 'length', 'file', 'definition', 'docstring', 'source', |
|
74 | 74 | 'init_definition', 'class_docstring', 'init_docstring', |
|
75 | 75 | 'call_def', 'call_docstring', |
|
76 | 76 | # These won't be printed but will be used to determine how to |
|
77 | 77 | # format the object |
|
78 | 78 | 'ismagic', 'isalias', 'argspec', 'found', 'name', |
|
79 | 79 | ] |
|
80 | 80 | |
|
81 | 81 | |
|
82 | 82 | def object_info(**kw): |
|
83 | 83 | """Make an object info dict with all fields present.""" |
|
84 | 84 | infodict = dict(izip_longest(info_fields, [None])) |
|
85 | 85 | infodict.update(kw) |
|
86 | 86 | return infodict |
|
87 | 87 | |
|
88 | 88 | |
|
89 | 89 | def getdoc(obj): |
|
90 | 90 | """Stable wrapper around inspect.getdoc. |
|
91 | 91 | |
|
92 | 92 | This can't crash because of attribute problems. |
|
93 | 93 | |
|
94 | 94 | It also attempts to call a getdoc() method on the given object. This |
|
95 | 95 | allows objects which provide their docstrings via non-standard mechanisms |
|
96 | 96 | (like Pyro proxies) to still be inspected by ipython's ? system.""" |
|
97 | 97 | |
|
98 | 98 | ds = None # default return value |
|
99 | 99 | try: |
|
100 | 100 | ds = inspect.getdoc(obj) |
|
101 | 101 | except: |
|
102 | 102 | # Harden against an inspect failure, which can occur with |
|
103 | 103 | # SWIG-wrapped extensions. |
|
104 | 104 | pass |
|
105 | 105 | # Allow objects to offer customized documentation via a getdoc method: |
|
106 | 106 | try: |
|
107 | 107 | ds2 = obj.getdoc() |
|
108 | 108 | except: |
|
109 | 109 | pass |
|
110 | 110 | else: |
|
111 | 111 | # if we get extra info, we add it to the normal docstring. |
|
112 | 112 | if ds is None: |
|
113 | 113 | ds = ds2 |
|
114 | 114 | else: |
|
115 | 115 | ds = '%s\n%s' % (ds,ds2) |
|
116 | 116 | return ds |
|
117 | 117 | |
|
118 | 118 | |
|
119 | 119 | def getsource(obj,is_binary=False): |
|
120 | 120 | """Wrapper around inspect.getsource. |
|
121 | 121 | |
|
122 | 122 | This can be modified by other projects to provide customized source |
|
123 | 123 | extraction. |
|
124 | 124 | |
|
125 | 125 | Inputs: |
|
126 | 126 | |
|
127 | 127 | - obj: an object whose source code we will attempt to extract. |
|
128 | 128 | |
|
129 | 129 | Optional inputs: |
|
130 | 130 | |
|
131 | 131 | - is_binary: whether the object is known to come from a binary source. |
|
132 | 132 | This implementation will skip returning any output for binary objects, but |
|
133 | 133 | custom extractors may know how to meaningfully process them.""" |
|
134 | 134 | |
|
135 | 135 | if is_binary: |
|
136 | 136 | return None |
|
137 | 137 | else: |
|
138 | 138 | try: |
|
139 | 139 | src = inspect.getsource(obj) |
|
140 | 140 | except TypeError: |
|
141 | 141 | if hasattr(obj,'__class__'): |
|
142 | 142 | src = inspect.getsource(obj.__class__) |
|
143 | 143 | return src |
|
144 | 144 | |
|
145 | 145 | def getargspec(obj): |
|
146 | 146 | """Get the names and default values of a function's arguments. |
|
147 | 147 | |
|
148 | 148 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
149 | 149 | 'args' is a list of the argument names (it may contain nested lists). |
|
150 | 150 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
151 | 151 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
152 | 152 | |
|
153 | 153 | Modified version of inspect.getargspec from the Python Standard |
|
154 | 154 | Library.""" |
|
155 | 155 | |
|
156 | 156 | if inspect.isfunction(obj): |
|
157 | 157 | func_obj = obj |
|
158 | 158 | elif inspect.ismethod(obj): |
|
159 | 159 | func_obj = obj.im_func |
|
160 | 160 | elif hasattr(obj, '__call__'): |
|
161 | 161 | func_obj = obj.__call__ |
|
162 | 162 | else: |
|
163 | 163 | raise TypeError('arg is not a Python function') |
|
164 | 164 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
165 | 165 | return args, varargs, varkw, func_obj.func_defaults |
|
166 | 166 | |
|
167 | 167 | |
|
168 | 168 | def format_argspec(argspec): |
|
169 | 169 | """Format argspect, convenience wrapper around inspect's. |
|
170 | 170 | |
|
171 | 171 | This takes a dict instead of ordered arguments and calls |
|
172 | 172 | inspect.format_argspec with the arguments in the necessary order. |
|
173 | 173 | """ |
|
174 | 174 | return inspect.formatargspec(argspec['args'], argspec['varargs'], |
|
175 | 175 | argspec['varkw'], argspec['defaults']) |
|
176 | 176 | |
|
177 | 177 | |
|
178 | 178 | def call_tip(oinfo, format_call=True): |
|
179 | 179 | """Extract call tip data from an oinfo dict. |
|
180 | 180 | |
|
181 | 181 | Parameters |
|
182 | 182 | ---------- |
|
183 | 183 | oinfo : dict |
|
184 | 184 | |
|
185 | 185 | format_call : bool, optional |
|
186 | 186 | If True, the call line is formatted and returned as a string. If not, a |
|
187 | 187 | tuple of (name, argspec) is returned. |
|
188 | 188 | |
|
189 | 189 | Returns |
|
190 | 190 | ------- |
|
191 | 191 | call_info : None, str or (str, dict) tuple. |
|
192 | 192 | When format_call is True, the whole call information is formattted as a |
|
193 | 193 | single string. Otherwise, the object's name and its argspec dict are |
|
194 | 194 | returned. If no call information is available, None is returned. |
|
195 | 195 | |
|
196 | 196 | docstring : str or None |
|
197 | 197 | The most relevant docstring for calling purposes is returned, if |
|
198 | 198 | available. The priority is: call docstring for callable instances, then |
|
199 | 199 | constructor docstring for classes, then main object's docstring otherwise |
|
200 | 200 | (regular functions). |
|
201 | 201 | """ |
|
202 | 202 | # Get call definition |
|
203 | 203 | argspec = oinfo['argspec'] |
|
204 | 204 | if argspec is None: |
|
205 | 205 | call_line = None |
|
206 | 206 | else: |
|
207 | 207 | # Callable objects will have 'self' as their first argument, prune |
|
208 | 208 | # it out if it's there for clarity (since users do *not* pass an |
|
209 | 209 | # extra first argument explicitly). |
|
210 | 210 | try: |
|
211 | 211 | has_self = argspec['args'][0] == 'self' |
|
212 | 212 | except (KeyError, IndexError): |
|
213 | 213 | pass |
|
214 | 214 | else: |
|
215 | 215 | if has_self: |
|
216 | 216 | argspec['args'] = argspec['args'][1:] |
|
217 | 217 | |
|
218 | 218 | call_line = oinfo['name']+format_argspec(argspec) |
|
219 | 219 | |
|
220 | 220 | # Now get docstring. |
|
221 | 221 | # The priority is: call docstring, constructor docstring, main one. |
|
222 | 222 | doc = oinfo['call_docstring'] |
|
223 | 223 | if doc is None: |
|
224 | 224 | doc = oinfo['init_docstring'] |
|
225 | 225 | if doc is None: |
|
226 | 226 | doc = oinfo['docstring'] |
|
227 | 227 | |
|
228 | 228 | return call_line, doc |
|
229 | 229 | |
|
230 | 230 | #**************************************************************************** |
|
231 | 231 | # Class definitions |
|
232 | 232 | |
|
233 | 233 | class myStringIO(StringIO.StringIO): |
|
234 | 234 | """Adds a writeln method to normal StringIO.""" |
|
235 | 235 | def writeln(self,*arg,**kw): |
|
236 | 236 | """Does a write() and then a write('\n')""" |
|
237 | 237 | self.write(*arg,**kw) |
|
238 | 238 | self.write('\n') |
|
239 | 239 | |
|
240 | 240 | |
|
241 | 241 | class Inspector: |
|
242 | 242 | def __init__(self, color_table=InspectColors, |
|
243 | 243 | code_color_table=PyColorize.ANSICodeColors, |
|
244 | 244 | scheme='NoColor', |
|
245 | 245 | str_detail_level=0): |
|
246 | 246 | self.color_table = color_table |
|
247 | 247 | self.parser = PyColorize.Parser(code_color_table,out='str') |
|
248 | 248 | self.format = self.parser.format |
|
249 | 249 | self.str_detail_level = str_detail_level |
|
250 | 250 | self.set_active_scheme(scheme) |
|
251 | 251 | |
|
252 | 252 | def _getdef(self,obj,oname=''): |
|
253 | 253 | """Return the definition header for any callable object. |
|
254 | 254 | |
|
255 | 255 | If any exception is generated, None is returned instead and the |
|
256 | 256 | exception is suppressed.""" |
|
257 | 257 | |
|
258 | 258 | try: |
|
259 | 259 | # We need a plain string here, NOT unicode! |
|
260 | 260 | hdef = oname + inspect.formatargspec(*getargspec(obj)) |
|
261 | 261 | return hdef.encode('ascii') |
|
262 | 262 | except: |
|
263 | 263 | return None |
|
264 | 264 | |
|
265 | 265 | def __head(self,h): |
|
266 | 266 | """Return a header string with proper colors.""" |
|
267 | 267 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
268 | 268 | self.color_table.active_colors.normal) |
|
269 | 269 | |
|
270 | 270 | def set_active_scheme(self,scheme): |
|
271 | 271 | self.color_table.set_active_scheme(scheme) |
|
272 | 272 | self.parser.color_table.set_active_scheme(scheme) |
|
273 | 273 | |
|
274 | 274 | def noinfo(self,msg,oname): |
|
275 | 275 | """Generic message when no information is found.""" |
|
276 | 276 | print 'No %s found' % msg, |
|
277 | 277 | if oname: |
|
278 | 278 | print 'for %s' % oname |
|
279 | 279 | else: |
|
280 | 280 | |
|
281 | 281 | |
|
282 | 282 | def pdef(self,obj,oname=''): |
|
283 | 283 | """Print the definition header for any callable object. |
|
284 | 284 | |
|
285 | 285 | If the object is a class, print the constructor information.""" |
|
286 | 286 | |
|
287 | 287 | if not callable(obj): |
|
288 | 288 | print 'Object is not callable.' |
|
289 | 289 | return |
|
290 | 290 | |
|
291 | 291 | header = '' |
|
292 | 292 | |
|
293 | 293 | if inspect.isclass(obj): |
|
294 | 294 | header = self.__head('Class constructor information:\n') |
|
295 | 295 | obj = obj.__init__ |
|
296 | 296 | elif type(obj) is types.InstanceType: |
|
297 | 297 | obj = obj.__call__ |
|
298 | 298 | |
|
299 | 299 | output = self._getdef(obj,oname) |
|
300 | 300 | if output is None: |
|
301 | 301 | self.noinfo('definition header',oname) |
|
302 | 302 | else: |
|
303 |
print >> |
|
|
303 | print >>io.stdout, header,self.format(output), | |
|
304 | 304 | |
|
305 | 305 | def pdoc(self,obj,oname='',formatter = None): |
|
306 | 306 | """Print the docstring for any object. |
|
307 | 307 | |
|
308 | 308 | Optional: |
|
309 | 309 | -formatter: a function to run the docstring through for specially |
|
310 | 310 | formatted docstrings.""" |
|
311 | 311 | |
|
312 | 312 | head = self.__head # so that itpl can find it even if private |
|
313 | 313 | ds = getdoc(obj) |
|
314 | 314 | if formatter: |
|
315 | 315 | ds = formatter(ds) |
|
316 | 316 | if inspect.isclass(obj): |
|
317 | 317 | init_ds = getdoc(obj.__init__) |
|
318 | 318 | output = itpl('$head("Class Docstring:")\n' |
|
319 | 319 | '$indent(ds)\n' |
|
320 | 320 | '$head("Constructor Docstring"):\n' |
|
321 | 321 | '$indent(init_ds)') |
|
322 | 322 | elif (type(obj) is types.InstanceType or isinstance(obj,object)) \ |
|
323 | 323 | and hasattr(obj,'__call__'): |
|
324 | 324 | call_ds = getdoc(obj.__call__) |
|
325 | 325 | if call_ds: |
|
326 | 326 | output = itpl('$head("Class Docstring:")\n$indent(ds)\n' |
|
327 | 327 | '$head("Calling Docstring:")\n$indent(call_ds)') |
|
328 | 328 | else: |
|
329 | 329 | output = ds |
|
330 | 330 | else: |
|
331 | 331 | output = ds |
|
332 | 332 | if output is None: |
|
333 | 333 | self.noinfo('documentation',oname) |
|
334 | 334 | return |
|
335 | 335 | page.page(output) |
|
336 | 336 | |
|
337 | 337 | def psource(self,obj,oname=''): |
|
338 | 338 | """Print the source code for an object.""" |
|
339 | 339 | |
|
340 | 340 | # Flush the source cache because inspect can return out-of-date source |
|
341 | 341 | linecache.checkcache() |
|
342 | 342 | try: |
|
343 | 343 | src = getsource(obj) |
|
344 | 344 | except: |
|
345 | 345 | self.noinfo('source',oname) |
|
346 | 346 | else: |
|
347 | 347 | page.page(self.format(src)) |
|
348 | 348 | |
|
349 | 349 | def pfile(self,obj,oname=''): |
|
350 | 350 | """Show the whole file where an object was defined.""" |
|
351 | 351 | |
|
352 | 352 | try: |
|
353 | 353 | try: |
|
354 | 354 | lineno = inspect.getsourcelines(obj)[1] |
|
355 | 355 | except TypeError: |
|
356 | 356 | # For instances, try the class object like getsource() does |
|
357 | 357 | if hasattr(obj,'__class__'): |
|
358 | 358 | lineno = inspect.getsourcelines(obj.__class__)[1] |
|
359 | 359 | # Adjust the inspected object so getabsfile() below works |
|
360 | 360 | obj = obj.__class__ |
|
361 | 361 | except: |
|
362 | 362 | self.noinfo('file',oname) |
|
363 | 363 | return |
|
364 | 364 | |
|
365 | 365 | # We only reach this point if object was successfully queried |
|
366 | 366 | |
|
367 | 367 | # run contents of file through pager starting at line |
|
368 | 368 | # where the object is defined |
|
369 | 369 | ofile = inspect.getabsfile(obj) |
|
370 | 370 | |
|
371 | 371 | if (ofile.endswith('.so') or ofile.endswith('.dll')): |
|
372 | 372 | print 'File %r is binary, not printing.' % ofile |
|
373 | 373 | elif not os.path.isfile(ofile): |
|
374 | 374 | print 'File %r does not exist, not printing.' % ofile |
|
375 | 375 | else: |
|
376 | 376 | # Print only text files, not extension binaries. Note that |
|
377 | 377 | # getsourcelines returns lineno with 1-offset and page() uses |
|
378 | 378 | # 0-offset, so we must adjust. |
|
379 | 379 | page.page(self.format(open(ofile).read()),lineno-1) |
|
380 | 380 | |
|
381 | 381 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): |
|
382 | 382 | """Show detailed information about an object. |
|
383 | 383 | |
|
384 | 384 | Optional arguments: |
|
385 | 385 | |
|
386 | 386 | - oname: name of the variable pointing to the object. |
|
387 | 387 | |
|
388 | 388 | - formatter: special formatter for docstrings (see pdoc) |
|
389 | 389 | |
|
390 | 390 | - info: a structure with some information fields which may have been |
|
391 | 391 | precomputed already. |
|
392 | 392 | |
|
393 | 393 | - detail_level: if set to 1, more information is given. |
|
394 | 394 | """ |
|
395 | 395 | |
|
396 | 396 | obj_type = type(obj) |
|
397 | 397 | |
|
398 | 398 | header = self.__head |
|
399 | 399 | if info is None: |
|
400 | 400 | ismagic = 0 |
|
401 | 401 | isalias = 0 |
|
402 | 402 | ospace = '' |
|
403 | 403 | else: |
|
404 | 404 | ismagic = info.ismagic |
|
405 | 405 | isalias = info.isalias |
|
406 | 406 | ospace = info.namespace |
|
407 | 407 | # Get docstring, special-casing aliases: |
|
408 | 408 | if isalias: |
|
409 | 409 | if not callable(obj): |
|
410 | 410 | try: |
|
411 | 411 | ds = "Alias to the system command:\n %s" % obj[1] |
|
412 | 412 | except: |
|
413 | 413 | ds = "Alias: " + str(obj) |
|
414 | 414 | else: |
|
415 | 415 | ds = "Alias to " + str(obj) |
|
416 | 416 | if obj.__doc__: |
|
417 | 417 | ds += "\nDocstring:\n" + obj.__doc__ |
|
418 | 418 | else: |
|
419 | 419 | ds = getdoc(obj) |
|
420 | 420 | if ds is None: |
|
421 | 421 | ds = '<no docstring>' |
|
422 | 422 | if formatter is not None: |
|
423 | 423 | ds = formatter(ds) |
|
424 | 424 | |
|
425 | 425 | # store output in a list which gets joined with \n at the end. |
|
426 | 426 | out = myStringIO() |
|
427 | 427 | |
|
428 | 428 | string_max = 200 # max size of strings to show (snipped if longer) |
|
429 | 429 | shalf = int((string_max -5)/2) |
|
430 | 430 | |
|
431 | 431 | if ismagic: |
|
432 | 432 | obj_type_name = 'Magic function' |
|
433 | 433 | elif isalias: |
|
434 | 434 | obj_type_name = 'System alias' |
|
435 | 435 | else: |
|
436 | 436 | obj_type_name = obj_type.__name__ |
|
437 | 437 | out.writeln(header('Type:\t\t')+obj_type_name) |
|
438 | 438 | |
|
439 | 439 | try: |
|
440 | 440 | bclass = obj.__class__ |
|
441 | 441 | out.writeln(header('Base Class:\t')+str(bclass)) |
|
442 | 442 | except: pass |
|
443 | 443 | |
|
444 | 444 | # String form, but snip if too long in ? form (full in ??) |
|
445 | 445 | if detail_level >= self.str_detail_level: |
|
446 | 446 | try: |
|
447 | 447 | ostr = str(obj) |
|
448 | 448 | str_head = 'String Form:' |
|
449 | 449 | if not detail_level and len(ostr)>string_max: |
|
450 | 450 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
451 | 451 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
452 | 452 | join(q.strip() for q in ostr.split("\n")) |
|
453 | 453 | if ostr.find('\n') > -1: |
|
454 | 454 | # Print multi-line strings starting at the next line. |
|
455 | 455 | str_sep = '\n' |
|
456 | 456 | else: |
|
457 | 457 | str_sep = '\t' |
|
458 | 458 | out.writeln("%s%s%s" % (header(str_head),str_sep,ostr)) |
|
459 | 459 | except: |
|
460 | 460 | pass |
|
461 | 461 | |
|
462 | 462 | if ospace: |
|
463 | 463 | out.writeln(header('Namespace:\t')+ospace) |
|
464 | 464 | |
|
465 | 465 | # Length (for strings and lists) |
|
466 | 466 | try: |
|
467 | 467 | length = str(len(obj)) |
|
468 | 468 | out.writeln(header('Length:\t\t')+length) |
|
469 | 469 | except: pass |
|
470 | 470 | |
|
471 | 471 | # Filename where object was defined |
|
472 | 472 | binary_file = False |
|
473 | 473 | try: |
|
474 | 474 | try: |
|
475 | 475 | fname = inspect.getabsfile(obj) |
|
476 | 476 | except TypeError: |
|
477 | 477 | # For an instance, the file that matters is where its class was |
|
478 | 478 | # declared. |
|
479 | 479 | if hasattr(obj,'__class__'): |
|
480 | 480 | fname = inspect.getabsfile(obj.__class__) |
|
481 | 481 | if fname.endswith('<string>'): |
|
482 | 482 | fname = 'Dynamically generated function. No source code available.' |
|
483 | 483 | if (fname.endswith('.so') or fname.endswith('.dll')): |
|
484 | 484 | binary_file = True |
|
485 | 485 | out.writeln(header('File:\t\t')+fname) |
|
486 | 486 | except: |
|
487 | 487 | # if anything goes wrong, we don't want to show source, so it's as |
|
488 | 488 | # if the file was binary |
|
489 | 489 | binary_file = True |
|
490 | 490 | |
|
491 | 491 | # reconstruct the function definition and print it: |
|
492 | 492 | defln = self._getdef(obj,oname) |
|
493 | 493 | if defln: |
|
494 | 494 | out.write(header('Definition:\t')+self.format(defln)) |
|
495 | 495 | |
|
496 | 496 | # Docstrings only in detail 0 mode, since source contains them (we |
|
497 | 497 | # avoid repetitions). If source fails, we add them back, see below. |
|
498 | 498 | if ds and detail_level == 0: |
|
499 | 499 | out.writeln(header('Docstring:\n') + indent(ds)) |
|
500 | 500 | |
|
501 | 501 | # Original source code for any callable |
|
502 | 502 | if detail_level: |
|
503 | 503 | # Flush the source cache because inspect can return out-of-date |
|
504 | 504 | # source |
|
505 | 505 | linecache.checkcache() |
|
506 | 506 | source_success = False |
|
507 | 507 | try: |
|
508 | 508 | try: |
|
509 | 509 | src = getsource(obj,binary_file) |
|
510 | 510 | except TypeError: |
|
511 | 511 | if hasattr(obj,'__class__'): |
|
512 | 512 | src = getsource(obj.__class__,binary_file) |
|
513 | 513 | if src is not None: |
|
514 | 514 | source = self.format(src) |
|
515 | 515 | out.write(header('Source:\n')+source.rstrip()+'\n') |
|
516 | 516 | source_success = True |
|
517 | 517 | except Exception, msg: |
|
518 | 518 | pass |
|
519 | 519 | |
|
520 | 520 | if ds and not source_success: |
|
521 | 521 | out.writeln(header('Docstring [source file open failed]:\n') |
|
522 | 522 | + indent(ds)) |
|
523 | 523 | |
|
524 | 524 | # Constructor docstring for classes |
|
525 | 525 | if inspect.isclass(obj): |
|
526 | 526 | # reconstruct the function definition and print it: |
|
527 | 527 | try: |
|
528 | 528 | obj_init = obj.__init__ |
|
529 | 529 | except AttributeError: |
|
530 | 530 | init_def = init_ds = None |
|
531 | 531 | else: |
|
532 | 532 | init_def = self._getdef(obj_init,oname) |
|
533 | 533 | init_ds = getdoc(obj_init) |
|
534 | 534 | # Skip Python's auto-generated docstrings |
|
535 | 535 | if init_ds and \ |
|
536 | 536 | init_ds.startswith('x.__init__(...) initializes'): |
|
537 | 537 | init_ds = None |
|
538 | 538 | |
|
539 | 539 | if init_def or init_ds: |
|
540 | 540 | out.writeln(header('Constructor information:')) |
|
541 | 541 | if init_def: |
|
542 | 542 | out.write(header('Definition:\t')+ self.format(init_def)) |
|
543 | 543 | if init_ds: |
|
544 | 544 | out.writeln(header('Docstring:\n') + indent(init_ds)) |
|
545 | 545 | # and class docstring for instances: |
|
546 | 546 | elif obj_type is types.InstanceType or \ |
|
547 | 547 | isinstance(obj,object): |
|
548 | 548 | |
|
549 | 549 | # First, check whether the instance docstring is identical to the |
|
550 | 550 | # class one, and print it separately if they don't coincide. In |
|
551 | 551 | # most cases they will, but it's nice to print all the info for |
|
552 | 552 | # objects which use instance-customized docstrings. |
|
553 | 553 | if ds: |
|
554 | 554 | try: |
|
555 | 555 | cls = getattr(obj,'__class__') |
|
556 | 556 | except: |
|
557 | 557 | class_ds = None |
|
558 | 558 | else: |
|
559 | 559 | class_ds = getdoc(cls) |
|
560 | 560 | # Skip Python's auto-generated docstrings |
|
561 | 561 | if class_ds and \ |
|
562 | 562 | (class_ds.startswith('function(code, globals[,') or \ |
|
563 | 563 | class_ds.startswith('instancemethod(function, instance,') or \ |
|
564 | 564 | class_ds.startswith('module(name[,') ): |
|
565 | 565 | class_ds = None |
|
566 | 566 | if class_ds and ds != class_ds: |
|
567 | 567 | out.writeln(header('Class Docstring:\n') + |
|
568 | 568 | indent(class_ds)) |
|
569 | 569 | |
|
570 | 570 | # Next, try to show constructor docstrings |
|
571 | 571 | try: |
|
572 | 572 | init_ds = getdoc(obj.__init__) |
|
573 | 573 | # Skip Python's auto-generated docstrings |
|
574 | 574 | if init_ds and \ |
|
575 | 575 | init_ds.startswith('x.__init__(...) initializes'): |
|
576 | 576 | init_ds = None |
|
577 | 577 | except AttributeError: |
|
578 | 578 | init_ds = None |
|
579 | 579 | if init_ds: |
|
580 | 580 | out.writeln(header('Constructor Docstring:\n') + |
|
581 | 581 | indent(init_ds)) |
|
582 | 582 | |
|
583 | 583 | # Call form docstring for callable instances |
|
584 | 584 | if hasattr(obj,'__call__'): |
|
585 | 585 | #out.writeln(header('Callable:\t')+'Yes') |
|
586 | 586 | call_def = self._getdef(obj.__call__,oname) |
|
587 | 587 | #if call_def is None: |
|
588 | 588 | # out.writeln(header('Call def:\t')+ |
|
589 | 589 | # 'Calling definition not available.') |
|
590 | 590 | if call_def is not None: |
|
591 | 591 | out.writeln(header('Call def:\t')+self.format(call_def)) |
|
592 | 592 | call_ds = getdoc(obj.__call__) |
|
593 | 593 | # Skip Python's auto-generated docstrings |
|
594 | 594 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): |
|
595 | 595 | call_ds = None |
|
596 | 596 | if call_ds: |
|
597 | 597 | out.writeln(header('Call docstring:\n') + indent(call_ds)) |
|
598 | 598 | |
|
599 | 599 | # Finally send to printer/pager |
|
600 | 600 | output = out.getvalue() |
|
601 | 601 | if output: |
|
602 | 602 | page.page(output) |
|
603 | 603 | # end pinfo |
|
604 | 604 | |
|
605 | 605 | def info(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
606 | 606 | """Compute a dict with detailed information about an object. |
|
607 | 607 | |
|
608 | 608 | Optional arguments: |
|
609 | 609 | |
|
610 | 610 | - oname: name of the variable pointing to the object. |
|
611 | 611 | |
|
612 | 612 | - formatter: special formatter for docstrings (see pdoc) |
|
613 | 613 | |
|
614 | 614 | - info: a structure with some information fields which may have been |
|
615 | 615 | precomputed already. |
|
616 | 616 | |
|
617 | 617 | - detail_level: if set to 1, more information is given. |
|
618 | 618 | """ |
|
619 | 619 | |
|
620 | 620 | obj_type = type(obj) |
|
621 | 621 | |
|
622 | 622 | header = self.__head |
|
623 | 623 | if info is None: |
|
624 | 624 | ismagic = 0 |
|
625 | 625 | isalias = 0 |
|
626 | 626 | ospace = '' |
|
627 | 627 | else: |
|
628 | 628 | ismagic = info.ismagic |
|
629 | 629 | isalias = info.isalias |
|
630 | 630 | ospace = info.namespace |
|
631 | 631 | |
|
632 | 632 | # Get docstring, special-casing aliases: |
|
633 | 633 | if isalias: |
|
634 | 634 | if not callable(obj): |
|
635 | 635 | try: |
|
636 | 636 | ds = "Alias to the system command:\n %s" % obj[1] |
|
637 | 637 | except: |
|
638 | 638 | ds = "Alias: " + str(obj) |
|
639 | 639 | else: |
|
640 | 640 | ds = "Alias to " + str(obj) |
|
641 | 641 | if obj.__doc__: |
|
642 | 642 | ds += "\nDocstring:\n" + obj.__doc__ |
|
643 | 643 | else: |
|
644 | 644 | ds = getdoc(obj) |
|
645 | 645 | if ds is None: |
|
646 | 646 | ds = '<no docstring>' |
|
647 | 647 | if formatter is not None: |
|
648 | 648 | ds = formatter(ds) |
|
649 | 649 | |
|
650 | 650 | # store output in a dict, we initialize it here and fill it as we go |
|
651 | 651 | out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic) |
|
652 | 652 | |
|
653 | 653 | string_max = 200 # max size of strings to show (snipped if longer) |
|
654 | 654 | shalf = int((string_max -5)/2) |
|
655 | 655 | |
|
656 | 656 | if ismagic: |
|
657 | 657 | obj_type_name = 'Magic function' |
|
658 | 658 | elif isalias: |
|
659 | 659 | obj_type_name = 'System alias' |
|
660 | 660 | else: |
|
661 | 661 | obj_type_name = obj_type.__name__ |
|
662 | 662 | out['type_name'] = obj_type_name |
|
663 | 663 | |
|
664 | 664 | try: |
|
665 | 665 | bclass = obj.__class__ |
|
666 | 666 | out['base_class'] = str(bclass) |
|
667 | 667 | except: pass |
|
668 | 668 | |
|
669 | 669 | # String form, but snip if too long in ? form (full in ??) |
|
670 | 670 | if detail_level >= self.str_detail_level: |
|
671 | 671 | try: |
|
672 | 672 | ostr = str(obj) |
|
673 | 673 | str_head = 'string_form' |
|
674 | 674 | if not detail_level and len(ostr)>string_max: |
|
675 | 675 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
676 | 676 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
677 | 677 | join(q.strip() for q in ostr.split("\n")) |
|
678 | 678 | if ostr.find('\n') > -1: |
|
679 | 679 | # Print multi-line strings starting at the next line. |
|
680 | 680 | str_sep = '\n' |
|
681 | 681 | else: |
|
682 | 682 | str_sep = '\t' |
|
683 | 683 | out[str_head] = ostr |
|
684 | 684 | except: |
|
685 | 685 | pass |
|
686 | 686 | |
|
687 | 687 | if ospace: |
|
688 | 688 | out['namespace'] = ospace |
|
689 | 689 | |
|
690 | 690 | # Length (for strings and lists) |
|
691 | 691 | try: |
|
692 | 692 | out['length'] = str(len(obj)) |
|
693 | 693 | except: pass |
|
694 | 694 | |
|
695 | 695 | # Filename where object was defined |
|
696 | 696 | binary_file = False |
|
697 | 697 | try: |
|
698 | 698 | try: |
|
699 | 699 | fname = inspect.getabsfile(obj) |
|
700 | 700 | except TypeError: |
|
701 | 701 | # For an instance, the file that matters is where its class was |
|
702 | 702 | # declared. |
|
703 | 703 | if hasattr(obj,'__class__'): |
|
704 | 704 | fname = inspect.getabsfile(obj.__class__) |
|
705 | 705 | if fname.endswith('<string>'): |
|
706 | 706 | fname = 'Dynamically generated function. No source code available.' |
|
707 | 707 | if (fname.endswith('.so') or fname.endswith('.dll')): |
|
708 | 708 | binary_file = True |
|
709 | 709 | out['file'] = fname |
|
710 | 710 | except: |
|
711 | 711 | # if anything goes wrong, we don't want to show source, so it's as |
|
712 | 712 | # if the file was binary |
|
713 | 713 | binary_file = True |
|
714 | 714 | |
|
715 | 715 | # reconstruct the function definition and print it: |
|
716 | 716 | defln = self._getdef(obj, oname) |
|
717 | 717 | if defln: |
|
718 | 718 | out['definition'] = self.format(defln) |
|
719 | 719 | |
|
720 | 720 | # Docstrings only in detail 0 mode, since source contains them (we |
|
721 | 721 | # avoid repetitions). If source fails, we add them back, see below. |
|
722 | 722 | if ds and detail_level == 0: |
|
723 | 723 | out['docstring'] = ds |
|
724 | 724 | |
|
725 | 725 | # Original source code for any callable |
|
726 | 726 | if detail_level: |
|
727 | 727 | # Flush the source cache because inspect can return out-of-date |
|
728 | 728 | # source |
|
729 | 729 | linecache.checkcache() |
|
730 | 730 | source_success = False |
|
731 | 731 | try: |
|
732 | 732 | try: |
|
733 | 733 | src = getsource(obj,binary_file) |
|
734 | 734 | except TypeError: |
|
735 | 735 | if hasattr(obj,'__class__'): |
|
736 | 736 | src = getsource(obj.__class__,binary_file) |
|
737 | 737 | if src is not None: |
|
738 | 738 | source = self.format(src) |
|
739 | 739 | out['source'] = source.rstrip() |
|
740 | 740 | source_success = True |
|
741 | 741 | except Exception, msg: |
|
742 | 742 | pass |
|
743 | 743 | |
|
744 | 744 | # Constructor docstring for classes |
|
745 | 745 | if inspect.isclass(obj): |
|
746 | 746 | # reconstruct the function definition and print it: |
|
747 | 747 | try: |
|
748 | 748 | obj_init = obj.__init__ |
|
749 | 749 | except AttributeError: |
|
750 | 750 | init_def = init_ds = None |
|
751 | 751 | else: |
|
752 | 752 | init_def = self._getdef(obj_init,oname) |
|
753 | 753 | init_ds = getdoc(obj_init) |
|
754 | 754 | # Skip Python's auto-generated docstrings |
|
755 | 755 | if init_ds and \ |
|
756 | 756 | init_ds.startswith('x.__init__(...) initializes'): |
|
757 | 757 | init_ds = None |
|
758 | 758 | |
|
759 | 759 | if init_def or init_ds: |
|
760 | 760 | if init_def: |
|
761 | 761 | out['init_definition'] = self.format(init_def) |
|
762 | 762 | if init_ds: |
|
763 | 763 | out['init_docstring'] = init_ds |
|
764 | 764 | |
|
765 | 765 | # and class docstring for instances: |
|
766 | 766 | elif obj_type is types.InstanceType or \ |
|
767 | 767 | isinstance(obj, object): |
|
768 | 768 | # First, check whether the instance docstring is identical to the |
|
769 | 769 | # class one, and print it separately if they don't coincide. In |
|
770 | 770 | # most cases they will, but it's nice to print all the info for |
|
771 | 771 | # objects which use instance-customized docstrings. |
|
772 | 772 | if ds: |
|
773 | 773 | try: |
|
774 | 774 | cls = getattr(obj,'__class__') |
|
775 | 775 | except: |
|
776 | 776 | class_ds = None |
|
777 | 777 | else: |
|
778 | 778 | class_ds = getdoc(cls) |
|
779 | 779 | # Skip Python's auto-generated docstrings |
|
780 | 780 | if class_ds and \ |
|
781 | 781 | (class_ds.startswith('function(code, globals[,') or \ |
|
782 | 782 | class_ds.startswith('instancemethod(function, instance,') or \ |
|
783 | 783 | class_ds.startswith('module(name[,') ): |
|
784 | 784 | class_ds = None |
|
785 | 785 | if class_ds and ds != class_ds: |
|
786 | 786 | out['class_docstring'] = class_ds |
|
787 | 787 | |
|
788 | 788 | # Next, try to show constructor docstrings |
|
789 | 789 | try: |
|
790 | 790 | init_ds = getdoc(obj.__init__) |
|
791 | 791 | # Skip Python's auto-generated docstrings |
|
792 | 792 | if init_ds and \ |
|
793 | 793 | init_ds.startswith('x.__init__(...) initializes'): |
|
794 | 794 | init_ds = None |
|
795 | 795 | except AttributeError: |
|
796 | 796 | init_ds = None |
|
797 | 797 | if init_ds: |
|
798 | 798 | out['init_docstring'] = init_ds |
|
799 | 799 | |
|
800 | 800 | # Call form docstring for callable instances |
|
801 | 801 | if hasattr(obj, '__call__'): |
|
802 | 802 | call_def = self._getdef(obj.__call__, oname) |
|
803 | 803 | if call_def is not None: |
|
804 | 804 | out['call_def'] = self.format(call_def) |
|
805 | 805 | call_ds = getdoc(obj.__call__) |
|
806 | 806 | # Skip Python's auto-generated docstrings |
|
807 | 807 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): |
|
808 | 808 | call_ds = None |
|
809 | 809 | if call_ds: |
|
810 | 810 | out['call_docstring'] = call_ds |
|
811 | 811 | |
|
812 | 812 | # Compute the object's argspec as a callable. The key is to decide |
|
813 | 813 | # whether to pull it from the object itself, from its __init__ or |
|
814 | 814 | # from its __call__ method. |
|
815 | 815 | |
|
816 | 816 | if inspect.isclass(obj): |
|
817 | 817 | callable_obj = obj.__init__ |
|
818 | 818 | elif callable(obj): |
|
819 | 819 | callable_obj = obj |
|
820 | 820 | else: |
|
821 | 821 | callable_obj = None |
|
822 | 822 | |
|
823 | 823 | if callable_obj: |
|
824 | 824 | try: |
|
825 | 825 | args, varargs, varkw, defaults = getargspec(callable_obj) |
|
826 | 826 | except (TypeError, AttributeError): |
|
827 | 827 | # For extensions/builtins we can't retrieve the argspec |
|
828 | 828 | pass |
|
829 | 829 | else: |
|
830 | 830 | out['argspec'] = dict(args=args, varargs=varargs, |
|
831 | 831 | varkw=varkw, defaults=defaults) |
|
832 | 832 | |
|
833 | 833 | return object_info(**out) |
|
834 | 834 | |
|
835 | 835 | |
|
836 | 836 | def psearch(self,pattern,ns_table,ns_search=[], |
|
837 | 837 | ignore_case=False,show_all=False): |
|
838 | 838 | """Search namespaces with wildcards for objects. |
|
839 | 839 | |
|
840 | 840 | Arguments: |
|
841 | 841 | |
|
842 | 842 | - pattern: string containing shell-like wildcards to use in namespace |
|
843 | 843 | searches and optionally a type specification to narrow the search to |
|
844 | 844 | objects of that type. |
|
845 | 845 | |
|
846 | 846 | - ns_table: dict of name->namespaces for search. |
|
847 | 847 | |
|
848 | 848 | Optional arguments: |
|
849 | 849 | |
|
850 | 850 | - ns_search: list of namespace names to include in search. |
|
851 | 851 | |
|
852 | 852 | - ignore_case(False): make the search case-insensitive. |
|
853 | 853 | |
|
854 | 854 | - show_all(False): show all names, including those starting with |
|
855 | 855 | underscores. |
|
856 | 856 | """ |
|
857 | 857 | #print 'ps pattern:<%r>' % pattern # dbg |
|
858 | 858 | |
|
859 | 859 | # defaults |
|
860 | 860 | type_pattern = 'all' |
|
861 | 861 | filter = '' |
|
862 | 862 | |
|
863 | 863 | cmds = pattern.split() |
|
864 | 864 | len_cmds = len(cmds) |
|
865 | 865 | if len_cmds == 1: |
|
866 | 866 | # Only filter pattern given |
|
867 | 867 | filter = cmds[0] |
|
868 | 868 | elif len_cmds == 2: |
|
869 | 869 | # Both filter and type specified |
|
870 | 870 | filter,type_pattern = cmds |
|
871 | 871 | else: |
|
872 | 872 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
873 | 873 | pattern) |
|
874 | 874 | |
|
875 | 875 | # filter search namespaces |
|
876 | 876 | for name in ns_search: |
|
877 | 877 | if name not in ns_table: |
|
878 | 878 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
879 | 879 | (name,ns_table.keys())) |
|
880 | 880 | |
|
881 | 881 | #print 'type_pattern:',type_pattern # dbg |
|
882 | 882 | search_result = [] |
|
883 | 883 | for ns_name in ns_search: |
|
884 | 884 | ns = ns_table[ns_name] |
|
885 | 885 | tmp_res = list(list_namespace(ns,type_pattern,filter, |
|
886 | 886 | ignore_case=ignore_case, |
|
887 | 887 | show_all=show_all)) |
|
888 | 888 | search_result.extend(tmp_res) |
|
889 | 889 | search_result.sort() |
|
890 | 890 | |
|
891 | 891 | page.page('\n'.join(search_result)) |
@@ -1,327 +1,327 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | Paging capabilities for IPython.core |
|
5 | 5 | |
|
6 | 6 | Authors: |
|
7 | 7 | |
|
8 | 8 | * Brian Granger |
|
9 | 9 | * Fernando Perez |
|
10 | 10 | |
|
11 | 11 | Notes |
|
12 | 12 | ----- |
|
13 | 13 | |
|
14 | 14 | For now this uses ipapi, so it can't be in IPython.utils. If we can get |
|
15 | 15 | rid of that dependency, we could move it there. |
|
16 | 16 | ----- |
|
17 | 17 | """ |
|
18 | 18 | |
|
19 | 19 | #----------------------------------------------------------------------------- |
|
20 | 20 | # Copyright (C) 2008-2009 The IPython Development Team |
|
21 | 21 | # |
|
22 | 22 | # Distributed under the terms of the BSD License. The full license is in |
|
23 | 23 | # the file COPYING, distributed as part of this software. |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | # Imports |
|
28 | 28 | #----------------------------------------------------------------------------- |
|
29 | 29 | |
|
30 | 30 | import os |
|
31 | 31 | import re |
|
32 | 32 | import sys |
|
33 | 33 | import tempfile |
|
34 | 34 | |
|
35 | 35 | from IPython.core import ipapi |
|
36 | 36 | from IPython.core.error import TryNext |
|
37 | 37 | from IPython.utils.cursesimport import use_curses |
|
38 | 38 | from IPython.utils.data import chop |
|
39 |
|
|
|
39 | from IPython.utils import io | |
|
40 | 40 | from IPython.utils.process import system |
|
41 | 41 | from IPython.utils.terminal import get_terminal_size |
|
42 | 42 | |
|
43 | 43 | |
|
44 | 44 | #----------------------------------------------------------------------------- |
|
45 | 45 | # Classes and functions |
|
46 | 46 | #----------------------------------------------------------------------------- |
|
47 | 47 | |
|
48 | 48 | esc_re = re.compile(r"(\x1b[^m]+m)") |
|
49 | 49 | |
|
50 | 50 | def page_dumb(strng, start=0, screen_lines=25): |
|
51 | 51 | """Very dumb 'pager' in Python, for when nothing else works. |
|
52 | 52 | |
|
53 | 53 | Only moves forward, same interface as page(), except for pager_cmd and |
|
54 | 54 | mode.""" |
|
55 | 55 | |
|
56 | 56 | out_ln = strng.splitlines()[start:] |
|
57 | 57 | screens = chop(out_ln,screen_lines-1) |
|
58 | 58 | if len(screens) == 1: |
|
59 |
print >> |
|
|
59 | print >>io.stdout, os.linesep.join(screens[0]) | |
|
60 | 60 | else: |
|
61 | 61 | last_escape = "" |
|
62 | 62 | for scr in screens[0:-1]: |
|
63 | 63 | hunk = os.linesep.join(scr) |
|
64 |
print >> |
|
|
64 | print >>io.stdout, last_escape + hunk | |
|
65 | 65 | if not page_more(): |
|
66 | 66 | return |
|
67 | 67 | esc_list = esc_re.findall(hunk) |
|
68 | 68 | if len(esc_list) > 0: |
|
69 | 69 | last_escape = esc_list[-1] |
|
70 |
print >> |
|
|
70 | print >>io.stdout, last_escape + os.linesep.join(screens[-1]) | |
|
71 | 71 | |
|
72 | 72 | |
|
73 | 73 | def page(strng, start=0, screen_lines=0, pager_cmd=None): |
|
74 | 74 | """Print a string, piping through a pager after a certain length. |
|
75 | 75 | |
|
76 | 76 | The screen_lines parameter specifies the number of *usable* lines of your |
|
77 | 77 | terminal screen (total lines minus lines you need to reserve to show other |
|
78 | 78 | information). |
|
79 | 79 | |
|
80 | 80 | If you set screen_lines to a number <=0, page() will try to auto-determine |
|
81 | 81 | your screen size and will only use up to (screen_size+screen_lines) for |
|
82 | 82 | printing, paging after that. That is, if you want auto-detection but need |
|
83 | 83 | to reserve the bottom 3 lines of the screen, use screen_lines = -3, and for |
|
84 | 84 | auto-detection without any lines reserved simply use screen_lines = 0. |
|
85 | 85 | |
|
86 | 86 | If a string won't fit in the allowed lines, it is sent through the |
|
87 | 87 | specified pager command. If none given, look for PAGER in the environment, |
|
88 | 88 | and ultimately default to less. |
|
89 | 89 | |
|
90 | 90 | If no system pager works, the string is sent through a 'dumb pager' |
|
91 | 91 | written in python, very simplistic. |
|
92 | 92 | """ |
|
93 | 93 | |
|
94 | 94 | # Some routines may auto-compute start offsets incorrectly and pass a |
|
95 | 95 | # negative value. Offset to 0 for robustness. |
|
96 | 96 | start = max(0, start) |
|
97 | 97 | |
|
98 | 98 | # first, try the hook |
|
99 | 99 | ip = ipapi.get() |
|
100 | 100 | if ip: |
|
101 | 101 | try: |
|
102 | 102 | ip.hooks.show_in_pager(strng) |
|
103 | 103 | return |
|
104 | 104 | except TryNext: |
|
105 | 105 | pass |
|
106 | 106 | |
|
107 | 107 | # Ugly kludge, but calling curses.initscr() flat out crashes in emacs |
|
108 | 108 | TERM = os.environ.get('TERM','dumb') |
|
109 | 109 | if TERM in ['dumb','emacs'] and os.name != 'nt': |
|
110 | 110 | print strng |
|
111 | 111 | return |
|
112 | 112 | # chop off the topmost part of the string we don't want to see |
|
113 | 113 | str_lines = strng.splitlines()[start:] |
|
114 | 114 | str_toprint = os.linesep.join(str_lines) |
|
115 | 115 | num_newlines = len(str_lines) |
|
116 | 116 | len_str = len(str_toprint) |
|
117 | 117 | |
|
118 | 118 | # Dumb heuristics to guesstimate number of on-screen lines the string |
|
119 | 119 | # takes. Very basic, but good enough for docstrings in reasonable |
|
120 | 120 | # terminals. If someone later feels like refining it, it's not hard. |
|
121 | 121 | numlines = max(num_newlines,int(len_str/80)+1) |
|
122 | 122 | |
|
123 | 123 | screen_lines_def = get_terminal_size()[1] |
|
124 | 124 | |
|
125 | 125 | # auto-determine screen size |
|
126 | 126 | if screen_lines <= 0: |
|
127 | 127 | if (TERM=='xterm' or TERM=='xterm-color') and sys.platform != 'sunos5': |
|
128 | 128 | local_use_curses = use_curses |
|
129 | 129 | else: |
|
130 | 130 | # curses causes problems on many terminals other than xterm, and |
|
131 | 131 | # some termios calls lock up on Sun OS5. |
|
132 | 132 | local_use_curses = False |
|
133 | 133 | if local_use_curses: |
|
134 | 134 | import termios |
|
135 | 135 | import curses |
|
136 | 136 | # There is a bug in curses, where *sometimes* it fails to properly |
|
137 | 137 | # initialize, and then after the endwin() call is made, the |
|
138 | 138 | # terminal is left in an unusable state. Rather than trying to |
|
139 | 139 | # check everytime for this (by requesting and comparing termios |
|
140 | 140 | # flags each time), we just save the initial terminal state and |
|
141 | 141 | # unconditionally reset it every time. It's cheaper than making |
|
142 | 142 | # the checks. |
|
143 | 143 | term_flags = termios.tcgetattr(sys.stdout) |
|
144 | 144 | |
|
145 | 145 | # Curses modifies the stdout buffer size by default, which messes |
|
146 | 146 | # up Python's normal stdout buffering. This would manifest itself |
|
147 | 147 | # to IPython users as delayed printing on stdout after having used |
|
148 | 148 | # the pager. |
|
149 | 149 | # |
|
150 | 150 | # We can prevent this by manually setting the NCURSES_NO_SETBUF |
|
151 | 151 | # environment variable. For more details, see: |
|
152 | 152 | # http://bugs.python.org/issue10144 |
|
153 | 153 | NCURSES_NO_SETBUF = os.environ.get('NCURSES_NO_SETBUF', None) |
|
154 | 154 | os.environ['NCURSES_NO_SETBUF'] = '' |
|
155 | 155 | |
|
156 | 156 | # Proceed with curses initialization |
|
157 | 157 | scr = curses.initscr() |
|
158 | 158 | screen_lines_real,screen_cols = scr.getmaxyx() |
|
159 | 159 | curses.endwin() |
|
160 | 160 | |
|
161 | 161 | # Restore environment |
|
162 | 162 | if NCURSES_NO_SETBUF is None: |
|
163 | 163 | del os.environ['NCURSES_NO_SETBUF'] |
|
164 | 164 | else: |
|
165 | 165 | os.environ['NCURSES_NO_SETBUF'] = NCURSES_NO_SETBUF |
|
166 | 166 | |
|
167 | 167 | # Restore terminal state in case endwin() didn't. |
|
168 | 168 | termios.tcsetattr(sys.stdout,termios.TCSANOW,term_flags) |
|
169 | 169 | # Now we have what we needed: the screen size in rows/columns |
|
170 | 170 | screen_lines += screen_lines_real |
|
171 | 171 | #print '***Screen size:',screen_lines_real,'lines x',\ |
|
172 | 172 | #screen_cols,'columns.' # dbg |
|
173 | 173 | else: |
|
174 | 174 | screen_lines += screen_lines_def |
|
175 | 175 | |
|
176 | 176 | #print 'numlines',numlines,'screenlines',screen_lines # dbg |
|
177 | 177 | if numlines <= screen_lines : |
|
178 | 178 | #print '*** normal print' # dbg |
|
179 |
print >> |
|
|
179 | print >>io.stdout, str_toprint | |
|
180 | 180 | else: |
|
181 | 181 | # Try to open pager and default to internal one if that fails. |
|
182 | 182 | # All failure modes are tagged as 'retval=1', to match the return |
|
183 | 183 | # value of a failed system command. If any intermediate attempt |
|
184 | 184 | # sets retval to 1, at the end we resort to our own page_dumb() pager. |
|
185 | 185 | pager_cmd = get_pager_cmd(pager_cmd) |
|
186 | 186 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
187 | 187 | if os.name == 'nt': |
|
188 | 188 | if pager_cmd.startswith('type'): |
|
189 | 189 | # The default WinXP 'type' command is failing on complex strings. |
|
190 | 190 | retval = 1 |
|
191 | 191 | else: |
|
192 | 192 | tmpname = tempfile.mktemp('.txt') |
|
193 | 193 | tmpfile = file(tmpname,'wt') |
|
194 | 194 | tmpfile.write(strng) |
|
195 | 195 | tmpfile.close() |
|
196 | 196 | cmd = "%s < %s" % (pager_cmd,tmpname) |
|
197 | 197 | if os.system(cmd): |
|
198 | 198 | retval = 1 |
|
199 | 199 | else: |
|
200 | 200 | retval = None |
|
201 | 201 | os.remove(tmpname) |
|
202 | 202 | else: |
|
203 | 203 | try: |
|
204 | 204 | retval = None |
|
205 | 205 | # if I use popen4, things hang. No idea why. |
|
206 | 206 | #pager,shell_out = os.popen4(pager_cmd) |
|
207 | 207 | pager = os.popen(pager_cmd,'w') |
|
208 | 208 | pager.write(strng) |
|
209 | 209 | pager.close() |
|
210 | 210 | retval = pager.close() # success returns None |
|
211 | 211 | except IOError,msg: # broken pipe when user quits |
|
212 | 212 | if msg.args == (32,'Broken pipe'): |
|
213 | 213 | retval = None |
|
214 | 214 | else: |
|
215 | 215 | retval = 1 |
|
216 | 216 | except OSError: |
|
217 | 217 | # Other strange problems, sometimes seen in Win2k/cygwin |
|
218 | 218 | retval = 1 |
|
219 | 219 | if retval is not None: |
|
220 | 220 | page_dumb(strng,screen_lines=screen_lines) |
|
221 | 221 | |
|
222 | 222 | |
|
223 | 223 | def page_file(fname, start=0, pager_cmd=None): |
|
224 | 224 | """Page a file, using an optional pager command and starting line. |
|
225 | 225 | """ |
|
226 | 226 | |
|
227 | 227 | pager_cmd = get_pager_cmd(pager_cmd) |
|
228 | 228 | pager_cmd += ' ' + get_pager_start(pager_cmd,start) |
|
229 | 229 | |
|
230 | 230 | try: |
|
231 | 231 | if os.environ['TERM'] in ['emacs','dumb']: |
|
232 | 232 | raise EnvironmentError |
|
233 | 233 | system(pager_cmd + ' ' + fname) |
|
234 | 234 | except: |
|
235 | 235 | try: |
|
236 | 236 | if start > 0: |
|
237 | 237 | start -= 1 |
|
238 | 238 | page(open(fname).read(),start) |
|
239 | 239 | except: |
|
240 | 240 | print 'Unable to show file',`fname` |
|
241 | 241 | |
|
242 | 242 | |
|
243 | 243 | def get_pager_cmd(pager_cmd=None): |
|
244 | 244 | """Return a pager command. |
|
245 | 245 | |
|
246 | 246 | Makes some attempts at finding an OS-correct one. |
|
247 | 247 | """ |
|
248 | 248 | if os.name == 'posix': |
|
249 | 249 | default_pager_cmd = 'less -r' # -r for color control sequences |
|
250 | 250 | elif os.name in ['nt','dos']: |
|
251 | 251 | default_pager_cmd = 'type' |
|
252 | 252 | |
|
253 | 253 | if pager_cmd is None: |
|
254 | 254 | try: |
|
255 | 255 | pager_cmd = os.environ['PAGER'] |
|
256 | 256 | except: |
|
257 | 257 | pager_cmd = default_pager_cmd |
|
258 | 258 | return pager_cmd |
|
259 | 259 | |
|
260 | 260 | |
|
261 | 261 | def get_pager_start(pager, start): |
|
262 | 262 | """Return the string for paging files with an offset. |
|
263 | 263 | |
|
264 | 264 | This is the '+N' argument which less and more (under Unix) accept. |
|
265 | 265 | """ |
|
266 | 266 | |
|
267 | 267 | if pager in ['less','more']: |
|
268 | 268 | if start: |
|
269 | 269 | start_string = '+' + str(start) |
|
270 | 270 | else: |
|
271 | 271 | start_string = '' |
|
272 | 272 | else: |
|
273 | 273 | start_string = '' |
|
274 | 274 | return start_string |
|
275 | 275 | |
|
276 | 276 | |
|
277 | 277 | # (X)emacs on win32 doesn't like to be bypassed with msvcrt.getch() |
|
278 | 278 | if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs': |
|
279 | 279 | import msvcrt |
|
280 | 280 | def page_more(): |
|
281 | 281 | """ Smart pausing between pages |
|
282 | 282 | |
|
283 | 283 | @return: True if need print more lines, False if quit |
|
284 | 284 | """ |
|
285 |
|
|
|
285 | io.stdout.write('---Return to continue, q to quit--- ') | |
|
286 | 286 | ans = msvcrt.getch() |
|
287 | 287 | if ans in ("q", "Q"): |
|
288 | 288 | result = False |
|
289 | 289 | else: |
|
290 | 290 | result = True |
|
291 |
|
|
|
291 | io.stdout.write("\b"*37 + " "*37 + "\b"*37) | |
|
292 | 292 | return result |
|
293 | 293 | else: |
|
294 | 294 | def page_more(): |
|
295 | 295 | ans = raw_input('---Return to continue, q to quit--- ') |
|
296 | 296 | if ans.lower().startswith('q'): |
|
297 | 297 | return False |
|
298 | 298 | else: |
|
299 | 299 | return True |
|
300 | 300 | |
|
301 | 301 | |
|
302 | 302 | def snip_print(str,width = 75,print_full = 0,header = ''): |
|
303 | 303 | """Print a string snipping the midsection to fit in width. |
|
304 | 304 | |
|
305 | 305 | print_full: mode control: |
|
306 | 306 | - 0: only snip long strings |
|
307 | 307 | - 1: send to page() directly. |
|
308 | 308 | - 2: snip long strings and ask for full length viewing with page() |
|
309 | 309 | Return 1 if snipping was necessary, 0 otherwise.""" |
|
310 | 310 | |
|
311 | 311 | if print_full == 1: |
|
312 | 312 | page(header+str) |
|
313 | 313 | return 0 |
|
314 | 314 | |
|
315 | 315 | print header, |
|
316 | 316 | if len(str) < width: |
|
317 | 317 | print str |
|
318 | 318 | snip = 0 |
|
319 | 319 | else: |
|
320 | 320 | whalf = int((width -5)/2) |
|
321 | 321 | print str[:whalf] + ' <...> ' + str[-whalf:] |
|
322 | 322 | snip = 1 |
|
323 | 323 | if snip and print_full == 2: |
|
324 | 324 | if raw_input(header+' Snipped. View (y/n)? [N]').lower() == 'y': |
|
325 | 325 | page(str) |
|
326 | 326 | return snip |
|
327 | 327 |
@@ -1,1014 +1,1013 b'' | |||
|
1 | 1 | #!/usr/bin/env python |
|
2 | 2 | # encoding: utf-8 |
|
3 | 3 | """ |
|
4 | 4 | Prefiltering components. |
|
5 | 5 | |
|
6 | 6 | Prefilters transform user input before it is exec'd by Python. These |
|
7 | 7 | transforms are used to implement additional syntax such as !ls and %magic. |
|
8 | 8 | |
|
9 | 9 | Authors: |
|
10 | 10 | |
|
11 | 11 | * Brian Granger |
|
12 | 12 | * Fernando Perez |
|
13 | 13 | * Dan Milstein |
|
14 | 14 | * Ville Vainio |
|
15 | 15 | """ |
|
16 | 16 | |
|
17 | 17 | #----------------------------------------------------------------------------- |
|
18 | 18 | # Copyright (C) 2008-2009 The IPython Development Team |
|
19 | 19 | # |
|
20 | 20 | # Distributed under the terms of the BSD License. The full license is in |
|
21 | 21 | # the file COPYING, distributed as part of this software. |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | # Imports |
|
26 | 26 | #----------------------------------------------------------------------------- |
|
27 | 27 | |
|
28 | 28 | import __builtin__ |
|
29 | 29 | import codeop |
|
30 | 30 | import re |
|
31 | 31 | |
|
32 | 32 | from IPython.core.alias import AliasManager |
|
33 | 33 | from IPython.core.autocall import IPyAutocall |
|
34 | 34 | from IPython.config.configurable import Configurable |
|
35 | 35 | from IPython.core.macro import Macro |
|
36 | 36 | from IPython.core.splitinput import split_user_input |
|
37 | 37 | from IPython.core import page |
|
38 | 38 | |
|
39 | 39 | from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance |
|
40 | import IPython.utils.io | |
|
41 | 40 | from IPython.utils.text import make_quoted_expr |
|
42 | 41 | from IPython.utils.autoattr import auto_attr |
|
43 | 42 | |
|
44 | 43 | #----------------------------------------------------------------------------- |
|
45 | 44 | # Global utilities, errors and constants |
|
46 | 45 | #----------------------------------------------------------------------------- |
|
47 | 46 | |
|
48 | 47 | # Warning, these cannot be changed unless various regular expressions |
|
49 | 48 | # are updated in a number of places. Not great, but at least we told you. |
|
50 | 49 | ESC_SHELL = '!' |
|
51 | 50 | ESC_SH_CAP = '!!' |
|
52 | 51 | ESC_HELP = '?' |
|
53 | 52 | ESC_MAGIC = '%' |
|
54 | 53 | ESC_QUOTE = ',' |
|
55 | 54 | ESC_QUOTE2 = ';' |
|
56 | 55 | ESC_PAREN = '/' |
|
57 | 56 | |
|
58 | 57 | |
|
59 | 58 | class PrefilterError(Exception): |
|
60 | 59 | pass |
|
61 | 60 | |
|
62 | 61 | |
|
63 | 62 | # RegExp to identify potential function names |
|
64 | 63 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
65 | 64 | |
|
66 | 65 | # RegExp to exclude strings with this start from autocalling. In |
|
67 | 66 | # particular, all binary operators should be excluded, so that if foo is |
|
68 | 67 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
69 | 68 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
70 | 69 | # routine explicitely does so, to catch direct calls and rebindings of |
|
71 | 70 | # existing names. |
|
72 | 71 | |
|
73 | 72 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
74 | 73 | # it affects the rest of the group in square brackets. |
|
75 | 74 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
76 | 75 | r'|^is |^not |^in |^and |^or ') |
|
77 | 76 | |
|
78 | 77 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
79 | 78 | # (experimental). For this to work, the line_split regexp would need |
|
80 | 79 | # to be modified so it wouldn't break things at '['. That line is |
|
81 | 80 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
82 | 81 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
83 | 82 | |
|
84 | 83 | |
|
85 | 84 | # Handler Check Utilities |
|
86 | 85 | def is_shadowed(identifier, ip): |
|
87 | 86 | """Is the given identifier defined in one of the namespaces which shadow |
|
88 | 87 | the alias and magic namespaces? Note that an identifier is different |
|
89 | 88 | than ifun, because it can not contain a '.' character.""" |
|
90 | 89 | # This is much safer than calling ofind, which can change state |
|
91 | 90 | return (identifier in ip.user_ns \ |
|
92 | 91 | or identifier in ip.internal_ns \ |
|
93 | 92 | or identifier in ip.ns_table['builtin']) |
|
94 | 93 | |
|
95 | 94 | |
|
96 | 95 | #----------------------------------------------------------------------------- |
|
97 | 96 | # The LineInfo class used throughout |
|
98 | 97 | #----------------------------------------------------------------------------- |
|
99 | 98 | |
|
100 | 99 | |
|
101 | 100 | class LineInfo(object): |
|
102 | 101 | """A single line of input and associated info. |
|
103 | 102 | |
|
104 | 103 | Includes the following as properties: |
|
105 | 104 | |
|
106 | 105 | line |
|
107 | 106 | The original, raw line |
|
108 | 107 | |
|
109 | 108 | continue_prompt |
|
110 | 109 | Is this line a continuation in a sequence of multiline input? |
|
111 | 110 | |
|
112 | 111 | pre |
|
113 | 112 | The initial esc character or whitespace. |
|
114 | 113 | |
|
115 | 114 | pre_char |
|
116 | 115 | The escape character(s) in pre or the empty string if there isn't one. |
|
117 | 116 | Note that '!!' is a possible value for pre_char. Otherwise it will |
|
118 | 117 | always be a single character. |
|
119 | 118 | |
|
120 | 119 | pre_whitespace |
|
121 | 120 | The leading whitespace from pre if it exists. If there is a pre_char, |
|
122 | 121 | this is just ''. |
|
123 | 122 | |
|
124 | 123 | ifun |
|
125 | 124 | The 'function part', which is basically the maximal initial sequence |
|
126 | 125 | of valid python identifiers and the '.' character. This is what is |
|
127 | 126 | checked for alias and magic transformations, used for auto-calling, |
|
128 | 127 | etc. |
|
129 | 128 | |
|
130 | 129 | the_rest |
|
131 | 130 | Everything else on the line. |
|
132 | 131 | """ |
|
133 | 132 | def __init__(self, line, continue_prompt): |
|
134 | 133 | self.line = line |
|
135 | 134 | self.continue_prompt = continue_prompt |
|
136 | 135 | self.pre, self.ifun, self.the_rest = split_user_input(line) |
|
137 | 136 | |
|
138 | 137 | self.pre_char = self.pre.strip() |
|
139 | 138 | if self.pre_char: |
|
140 | 139 | self.pre_whitespace = '' # No whitespace allowd before esc chars |
|
141 | 140 | else: |
|
142 | 141 | self.pre_whitespace = self.pre |
|
143 | 142 | |
|
144 | 143 | self._oinfo = None |
|
145 | 144 | |
|
146 | 145 | def ofind(self, ip): |
|
147 | 146 | """Do a full, attribute-walking lookup of the ifun in the various |
|
148 | 147 | namespaces for the given IPython InteractiveShell instance. |
|
149 | 148 | |
|
150 | 149 | Return a dict with keys: found,obj,ospace,ismagic |
|
151 | 150 | |
|
152 | 151 | Note: can cause state changes because of calling getattr, but should |
|
153 | 152 | only be run if autocall is on and if the line hasn't matched any |
|
154 | 153 | other, less dangerous handlers. |
|
155 | 154 | |
|
156 | 155 | Does cache the results of the call, so can be called multiple times |
|
157 | 156 | without worrying about *further* damaging state. |
|
158 | 157 | """ |
|
159 | 158 | if not self._oinfo: |
|
160 | 159 | # ip.shell._ofind is actually on the Magic class! |
|
161 | 160 | self._oinfo = ip.shell._ofind(self.ifun) |
|
162 | 161 | return self._oinfo |
|
163 | 162 | |
|
164 | 163 | def __str__(self): |
|
165 | 164 | return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest) |
|
166 | 165 | |
|
167 | 166 | |
|
168 | 167 | #----------------------------------------------------------------------------- |
|
169 | 168 | # Main Prefilter manager |
|
170 | 169 | #----------------------------------------------------------------------------- |
|
171 | 170 | |
|
172 | 171 | |
|
173 | 172 | class PrefilterManager(Configurable): |
|
174 | 173 | """Main prefilter component. |
|
175 | 174 | |
|
176 | 175 | The IPython prefilter is run on all user input before it is run. The |
|
177 | 176 | prefilter consumes lines of input and produces transformed lines of |
|
178 | 177 | input. |
|
179 | 178 | |
|
180 | 179 | The iplementation consists of two phases: |
|
181 | 180 | |
|
182 | 181 | 1. Transformers |
|
183 | 182 | 2. Checkers and handlers |
|
184 | 183 | |
|
185 | 184 | Over time, we plan on deprecating the checkers and handlers and doing |
|
186 | 185 | everything in the transformers. |
|
187 | 186 | |
|
188 | 187 | The transformers are instances of :class:`PrefilterTransformer` and have |
|
189 | 188 | a single method :meth:`transform` that takes a line and returns a |
|
190 | 189 | transformed line. The transformation can be accomplished using any |
|
191 | 190 | tool, but our current ones use regular expressions for speed. We also |
|
192 | 191 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. |
|
193 | 192 | |
|
194 | 193 | After all the transformers have been run, the line is fed to the checkers, |
|
195 | 194 | which are instances of :class:`PrefilterChecker`. The line is passed to |
|
196 | 195 | the :meth:`check` method, which either returns `None` or a |
|
197 | 196 | :class:`PrefilterHandler` instance. If `None` is returned, the other |
|
198 | 197 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, |
|
199 | 198 | the line is passed to the :meth:`handle` method of the returned |
|
200 | 199 | handler and no further checkers are tried. |
|
201 | 200 | |
|
202 | 201 | Both transformers and checkers have a `priority` attribute, that determines |
|
203 | 202 | the order in which they are called. Smaller priorities are tried first. |
|
204 | 203 | |
|
205 | 204 | Both transformers and checkers also have `enabled` attribute, which is |
|
206 | 205 | a boolean that determines if the instance is used. |
|
207 | 206 | |
|
208 | 207 | Users or developers can change the priority or enabled attribute of |
|
209 | 208 | transformers or checkers, but they must call the :meth:`sort_checkers` |
|
210 | 209 | or :meth:`sort_transformers` method after changing the priority. |
|
211 | 210 | """ |
|
212 | 211 | |
|
213 | 212 | multi_line_specials = CBool(True, config=True) |
|
214 | 213 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
215 | 214 | |
|
216 | 215 | def __init__(self, shell=None, config=None): |
|
217 | 216 | super(PrefilterManager, self).__init__(shell=shell, config=config) |
|
218 | 217 | self.shell = shell |
|
219 | 218 | self.init_transformers() |
|
220 | 219 | self.init_handlers() |
|
221 | 220 | self.init_checkers() |
|
222 | 221 | |
|
223 | 222 | #------------------------------------------------------------------------- |
|
224 | 223 | # API for managing transformers |
|
225 | 224 | #------------------------------------------------------------------------- |
|
226 | 225 | |
|
227 | 226 | def init_transformers(self): |
|
228 | 227 | """Create the default transformers.""" |
|
229 | 228 | self._transformers = [] |
|
230 | 229 | for transformer_cls in _default_transformers: |
|
231 | 230 | transformer_cls( |
|
232 | 231 | shell=self.shell, prefilter_manager=self, config=self.config |
|
233 | 232 | ) |
|
234 | 233 | |
|
235 | 234 | def sort_transformers(self): |
|
236 | 235 | """Sort the transformers by priority. |
|
237 | 236 | |
|
238 | 237 | This must be called after the priority of a transformer is changed. |
|
239 | 238 | The :meth:`register_transformer` method calls this automatically. |
|
240 | 239 | """ |
|
241 | 240 | self._transformers.sort(key=lambda x: x.priority) |
|
242 | 241 | |
|
243 | 242 | @property |
|
244 | 243 | def transformers(self): |
|
245 | 244 | """Return a list of checkers, sorted by priority.""" |
|
246 | 245 | return self._transformers |
|
247 | 246 | |
|
248 | 247 | def register_transformer(self, transformer): |
|
249 | 248 | """Register a transformer instance.""" |
|
250 | 249 | if transformer not in self._transformers: |
|
251 | 250 | self._transformers.append(transformer) |
|
252 | 251 | self.sort_transformers() |
|
253 | 252 | |
|
254 | 253 | def unregister_transformer(self, transformer): |
|
255 | 254 | """Unregister a transformer instance.""" |
|
256 | 255 | if transformer in self._transformers: |
|
257 | 256 | self._transformers.remove(transformer) |
|
258 | 257 | |
|
259 | 258 | #------------------------------------------------------------------------- |
|
260 | 259 | # API for managing checkers |
|
261 | 260 | #------------------------------------------------------------------------- |
|
262 | 261 | |
|
263 | 262 | def init_checkers(self): |
|
264 | 263 | """Create the default checkers.""" |
|
265 | 264 | self._checkers = [] |
|
266 | 265 | for checker in _default_checkers: |
|
267 | 266 | checker( |
|
268 | 267 | shell=self.shell, prefilter_manager=self, config=self.config |
|
269 | 268 | ) |
|
270 | 269 | |
|
271 | 270 | def sort_checkers(self): |
|
272 | 271 | """Sort the checkers by priority. |
|
273 | 272 | |
|
274 | 273 | This must be called after the priority of a checker is changed. |
|
275 | 274 | The :meth:`register_checker` method calls this automatically. |
|
276 | 275 | """ |
|
277 | 276 | self._checkers.sort(key=lambda x: x.priority) |
|
278 | 277 | |
|
279 | 278 | @property |
|
280 | 279 | def checkers(self): |
|
281 | 280 | """Return a list of checkers, sorted by priority.""" |
|
282 | 281 | return self._checkers |
|
283 | 282 | |
|
284 | 283 | def register_checker(self, checker): |
|
285 | 284 | """Register a checker instance.""" |
|
286 | 285 | if checker not in self._checkers: |
|
287 | 286 | self._checkers.append(checker) |
|
288 | 287 | self.sort_checkers() |
|
289 | 288 | |
|
290 | 289 | def unregister_checker(self, checker): |
|
291 | 290 | """Unregister a checker instance.""" |
|
292 | 291 | if checker in self._checkers: |
|
293 | 292 | self._checkers.remove(checker) |
|
294 | 293 | |
|
295 | 294 | #------------------------------------------------------------------------- |
|
296 | 295 | # API for managing checkers |
|
297 | 296 | #------------------------------------------------------------------------- |
|
298 | 297 | |
|
299 | 298 | def init_handlers(self): |
|
300 | 299 | """Create the default handlers.""" |
|
301 | 300 | self._handlers = {} |
|
302 | 301 | self._esc_handlers = {} |
|
303 | 302 | for handler in _default_handlers: |
|
304 | 303 | handler( |
|
305 | 304 | shell=self.shell, prefilter_manager=self, config=self.config |
|
306 | 305 | ) |
|
307 | 306 | |
|
308 | 307 | @property |
|
309 | 308 | def handlers(self): |
|
310 | 309 | """Return a dict of all the handlers.""" |
|
311 | 310 | return self._handlers |
|
312 | 311 | |
|
313 | 312 | def register_handler(self, name, handler, esc_strings): |
|
314 | 313 | """Register a handler instance by name with esc_strings.""" |
|
315 | 314 | self._handlers[name] = handler |
|
316 | 315 | for esc_str in esc_strings: |
|
317 | 316 | self._esc_handlers[esc_str] = handler |
|
318 | 317 | |
|
319 | 318 | def unregister_handler(self, name, handler, esc_strings): |
|
320 | 319 | """Unregister a handler instance by name with esc_strings.""" |
|
321 | 320 | try: |
|
322 | 321 | del self._handlers[name] |
|
323 | 322 | except KeyError: |
|
324 | 323 | pass |
|
325 | 324 | for esc_str in esc_strings: |
|
326 | 325 | h = self._esc_handlers.get(esc_str) |
|
327 | 326 | if h is handler: |
|
328 | 327 | del self._esc_handlers[esc_str] |
|
329 | 328 | |
|
330 | 329 | def get_handler_by_name(self, name): |
|
331 | 330 | """Get a handler by its name.""" |
|
332 | 331 | return self._handlers.get(name) |
|
333 | 332 | |
|
334 | 333 | def get_handler_by_esc(self, esc_str): |
|
335 | 334 | """Get a handler by its escape string.""" |
|
336 | 335 | return self._esc_handlers.get(esc_str) |
|
337 | 336 | |
|
338 | 337 | #------------------------------------------------------------------------- |
|
339 | 338 | # Main prefiltering API |
|
340 | 339 | #------------------------------------------------------------------------- |
|
341 | 340 | |
|
342 | 341 | def prefilter_line_info(self, line_info): |
|
343 | 342 | """Prefilter a line that has been converted to a LineInfo object. |
|
344 | 343 | |
|
345 | 344 | This implements the checker/handler part of the prefilter pipe. |
|
346 | 345 | """ |
|
347 | 346 | # print "prefilter_line_info: ", line_info |
|
348 | 347 | handler = self.find_handler(line_info) |
|
349 | 348 | return handler.handle(line_info) |
|
350 | 349 | |
|
351 | 350 | def find_handler(self, line_info): |
|
352 | 351 | """Find a handler for the line_info by trying checkers.""" |
|
353 | 352 | for checker in self.checkers: |
|
354 | 353 | if checker.enabled: |
|
355 | 354 | handler = checker.check(line_info) |
|
356 | 355 | if handler: |
|
357 | 356 | return handler |
|
358 | 357 | return self.get_handler_by_name('normal') |
|
359 | 358 | |
|
360 | 359 | def transform_line(self, line, continue_prompt): |
|
361 | 360 | """Calls the enabled transformers in order of increasing priority.""" |
|
362 | 361 | for transformer in self.transformers: |
|
363 | 362 | if transformer.enabled: |
|
364 | 363 | line = transformer.transform(line, continue_prompt) |
|
365 | 364 | return line |
|
366 | 365 | |
|
367 | 366 | def prefilter_line(self, line, continue_prompt=False): |
|
368 | 367 | """Prefilter a single input line as text. |
|
369 | 368 | |
|
370 | 369 | This method prefilters a single line of text by calling the |
|
371 | 370 | transformers and then the checkers/handlers. |
|
372 | 371 | """ |
|
373 | 372 | |
|
374 | 373 | # print "prefilter_line: ", line, continue_prompt |
|
375 | 374 | # All handlers *must* return a value, even if it's blank (''). |
|
376 | 375 | |
|
377 | 376 | # save the line away in case we crash, so the post-mortem handler can |
|
378 | 377 | # record it |
|
379 | 378 | self.shell._last_input_line = line |
|
380 | 379 | |
|
381 | 380 | if not line: |
|
382 | 381 | # Return immediately on purely empty lines, so that if the user |
|
383 | 382 | # previously typed some whitespace that started a continuation |
|
384 | 383 | # prompt, he can break out of that loop with just an empty line. |
|
385 | 384 | # This is how the default python prompt works. |
|
386 | 385 | return '' |
|
387 | 386 | |
|
388 | 387 | # At this point, we invoke our transformers. |
|
389 | 388 | if not continue_prompt or (continue_prompt and self.multi_line_specials): |
|
390 | 389 | line = self.transform_line(line, continue_prompt) |
|
391 | 390 | |
|
392 | 391 | # Now we compute line_info for the checkers and handlers |
|
393 | 392 | line_info = LineInfo(line, continue_prompt) |
|
394 | 393 | |
|
395 | 394 | # the input history needs to track even empty lines |
|
396 | 395 | stripped = line.strip() |
|
397 | 396 | |
|
398 | 397 | normal_handler = self.get_handler_by_name('normal') |
|
399 | 398 | if not stripped: |
|
400 | 399 | if not continue_prompt: |
|
401 | 400 | self.shell.displayhook.prompt_count -= 1 |
|
402 | 401 | |
|
403 | 402 | return normal_handler.handle(line_info) |
|
404 | 403 | |
|
405 | 404 | # special handlers are only allowed for single line statements |
|
406 | 405 | if continue_prompt and not self.multi_line_specials: |
|
407 | 406 | return normal_handler.handle(line_info) |
|
408 | 407 | |
|
409 | 408 | prefiltered = self.prefilter_line_info(line_info) |
|
410 | 409 | # print "prefiltered line: %r" % prefiltered |
|
411 | 410 | return prefiltered |
|
412 | 411 | |
|
413 | 412 | def prefilter_lines(self, lines, continue_prompt=False): |
|
414 | 413 | """Prefilter multiple input lines of text. |
|
415 | 414 | |
|
416 | 415 | This is the main entry point for prefiltering multiple lines of |
|
417 | 416 | input. This simply calls :meth:`prefilter_line` for each line of |
|
418 | 417 | input. |
|
419 | 418 | |
|
420 | 419 | This covers cases where there are multiple lines in the user entry, |
|
421 | 420 | which is the case when the user goes back to a multiline history |
|
422 | 421 | entry and presses enter. |
|
423 | 422 | """ |
|
424 | 423 | llines = lines.rstrip('\n').split('\n') |
|
425 | 424 | # We can get multiple lines in one shot, where multiline input 'blends' |
|
426 | 425 | # into one line, in cases like recalling from the readline history |
|
427 | 426 | # buffer. We need to make sure that in such cases, we correctly |
|
428 | 427 | # communicate downstream which line is first and which are continuation |
|
429 | 428 | # ones. |
|
430 | 429 | if len(llines) > 1: |
|
431 | 430 | out = '\n'.join([self.prefilter_line(line, lnum>0) |
|
432 | 431 | for lnum, line in enumerate(llines) ]) |
|
433 | 432 | else: |
|
434 | 433 | out = self.prefilter_line(llines[0], continue_prompt) |
|
435 | 434 | |
|
436 | 435 | return out |
|
437 | 436 | |
|
438 | 437 | #----------------------------------------------------------------------------- |
|
439 | 438 | # Prefilter transformers |
|
440 | 439 | #----------------------------------------------------------------------------- |
|
441 | 440 | |
|
442 | 441 | |
|
443 | 442 | class PrefilterTransformer(Configurable): |
|
444 | 443 | """Transform a line of user input.""" |
|
445 | 444 | |
|
446 | 445 | priority = Int(100, config=True) |
|
447 | 446 | # Transformers don't currently use shell or prefilter_manager, but as we |
|
448 | 447 | # move away from checkers and handlers, they will need them. |
|
449 | 448 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
450 | 449 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
451 | 450 | enabled = Bool(True, config=True) |
|
452 | 451 | |
|
453 | 452 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
454 | 453 | super(PrefilterTransformer, self).__init__( |
|
455 | 454 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
456 | 455 | ) |
|
457 | 456 | self.prefilter_manager.register_transformer(self) |
|
458 | 457 | |
|
459 | 458 | def transform(self, line, continue_prompt): |
|
460 | 459 | """Transform a line, returning the new one.""" |
|
461 | 460 | return None |
|
462 | 461 | |
|
463 | 462 | def __repr__(self): |
|
464 | 463 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
465 | 464 | self.__class__.__name__, self.priority, self.enabled) |
|
466 | 465 | |
|
467 | 466 | |
|
468 | 467 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
469 | 468 | r'\s*=\s*!(?P<cmd>.*)') |
|
470 | 469 | |
|
471 | 470 | |
|
472 | 471 | class AssignSystemTransformer(PrefilterTransformer): |
|
473 | 472 | """Handle the `files = !ls` syntax.""" |
|
474 | 473 | |
|
475 | 474 | priority = Int(100, config=True) |
|
476 | 475 | |
|
477 | 476 | def transform(self, line, continue_prompt): |
|
478 | 477 | m = _assign_system_re.match(line) |
|
479 | 478 | if m is not None: |
|
480 | 479 | cmd = m.group('cmd') |
|
481 | 480 | lhs = m.group('lhs') |
|
482 | 481 | expr = make_quoted_expr("sc =%s" % cmd) |
|
483 | 482 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
484 | 483 | return new_line |
|
485 | 484 | return line |
|
486 | 485 | |
|
487 | 486 | |
|
488 | 487 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
489 | 488 | r'\s*=\s*%(?P<cmd>.*)') |
|
490 | 489 | |
|
491 | 490 | class AssignMagicTransformer(PrefilterTransformer): |
|
492 | 491 | """Handle the `a = %who` syntax.""" |
|
493 | 492 | |
|
494 | 493 | priority = Int(200, config=True) |
|
495 | 494 | |
|
496 | 495 | def transform(self, line, continue_prompt): |
|
497 | 496 | m = _assign_magic_re.match(line) |
|
498 | 497 | if m is not None: |
|
499 | 498 | cmd = m.group('cmd') |
|
500 | 499 | lhs = m.group('lhs') |
|
501 | 500 | expr = make_quoted_expr(cmd) |
|
502 | 501 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
503 | 502 | return new_line |
|
504 | 503 | return line |
|
505 | 504 | |
|
506 | 505 | |
|
507 | 506 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') |
|
508 | 507 | |
|
509 | 508 | class PyPromptTransformer(PrefilterTransformer): |
|
510 | 509 | """Handle inputs that start with '>>> ' syntax.""" |
|
511 | 510 | |
|
512 | 511 | priority = Int(50, config=True) |
|
513 | 512 | |
|
514 | 513 | def transform(self, line, continue_prompt): |
|
515 | 514 | |
|
516 | 515 | if not line or line.isspace() or line.strip() == '...': |
|
517 | 516 | # This allows us to recognize multiple input prompts separated by |
|
518 | 517 | # blank lines and pasted in a single chunk, very common when |
|
519 | 518 | # pasting doctests or long tutorial passages. |
|
520 | 519 | return '' |
|
521 | 520 | m = _classic_prompt_re.match(line) |
|
522 | 521 | if m: |
|
523 | 522 | return line[len(m.group(0)):] |
|
524 | 523 | else: |
|
525 | 524 | return line |
|
526 | 525 | |
|
527 | 526 | |
|
528 | 527 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') |
|
529 | 528 | |
|
530 | 529 | class IPyPromptTransformer(PrefilterTransformer): |
|
531 | 530 | """Handle inputs that start classic IPython prompt syntax.""" |
|
532 | 531 | |
|
533 | 532 | priority = Int(50, config=True) |
|
534 | 533 | |
|
535 | 534 | def transform(self, line, continue_prompt): |
|
536 | 535 | |
|
537 | 536 | if not line or line.isspace() or line.strip() == '...': |
|
538 | 537 | # This allows us to recognize multiple input prompts separated by |
|
539 | 538 | # blank lines and pasted in a single chunk, very common when |
|
540 | 539 | # pasting doctests or long tutorial passages. |
|
541 | 540 | return '' |
|
542 | 541 | m = _ipy_prompt_re.match(line) |
|
543 | 542 | if m: |
|
544 | 543 | return line[len(m.group(0)):] |
|
545 | 544 | else: |
|
546 | 545 | return line |
|
547 | 546 | |
|
548 | 547 | #----------------------------------------------------------------------------- |
|
549 | 548 | # Prefilter checkers |
|
550 | 549 | #----------------------------------------------------------------------------- |
|
551 | 550 | |
|
552 | 551 | |
|
553 | 552 | class PrefilterChecker(Configurable): |
|
554 | 553 | """Inspect an input line and return a handler for that line.""" |
|
555 | 554 | |
|
556 | 555 | priority = Int(100, config=True) |
|
557 | 556 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
558 | 557 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
559 | 558 | enabled = Bool(True, config=True) |
|
560 | 559 | |
|
561 | 560 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
562 | 561 | super(PrefilterChecker, self).__init__( |
|
563 | 562 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
564 | 563 | ) |
|
565 | 564 | self.prefilter_manager.register_checker(self) |
|
566 | 565 | |
|
567 | 566 | def check(self, line_info): |
|
568 | 567 | """Inspect line_info and return a handler instance or None.""" |
|
569 | 568 | return None |
|
570 | 569 | |
|
571 | 570 | def __repr__(self): |
|
572 | 571 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
573 | 572 | self.__class__.__name__, self.priority, self.enabled) |
|
574 | 573 | |
|
575 | 574 | |
|
576 | 575 | class EmacsChecker(PrefilterChecker): |
|
577 | 576 | |
|
578 | 577 | priority = Int(100, config=True) |
|
579 | 578 | enabled = Bool(False, config=True) |
|
580 | 579 | |
|
581 | 580 | def check(self, line_info): |
|
582 | 581 | "Emacs ipython-mode tags certain input lines." |
|
583 | 582 | if line_info.line.endswith('# PYTHON-MODE'): |
|
584 | 583 | return self.prefilter_manager.get_handler_by_name('emacs') |
|
585 | 584 | else: |
|
586 | 585 | return None |
|
587 | 586 | |
|
588 | 587 | |
|
589 | 588 | class ShellEscapeChecker(PrefilterChecker): |
|
590 | 589 | |
|
591 | 590 | priority = Int(200, config=True) |
|
592 | 591 | |
|
593 | 592 | def check(self, line_info): |
|
594 | 593 | if line_info.line.lstrip().startswith(ESC_SHELL): |
|
595 | 594 | return self.prefilter_manager.get_handler_by_name('shell') |
|
596 | 595 | |
|
597 | 596 | |
|
598 | 597 | class MacroChecker(PrefilterChecker): |
|
599 | 598 | |
|
600 | 599 | priority = Int(250, config=True) |
|
601 | 600 | |
|
602 | 601 | def check(self, line_info): |
|
603 | 602 | obj = self.shell.user_ns.get(line_info.ifun) |
|
604 | 603 | if isinstance(obj, Macro): |
|
605 | 604 | return self.prefilter_manager.get_handler_by_name('macro') |
|
606 | 605 | else: |
|
607 | 606 | return None |
|
608 | 607 | |
|
609 | 608 | |
|
610 | 609 | class IPyAutocallChecker(PrefilterChecker): |
|
611 | 610 | |
|
612 | 611 | priority = Int(300, config=True) |
|
613 | 612 | |
|
614 | 613 | def check(self, line_info): |
|
615 | 614 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
616 | 615 | obj = self.shell.user_ns.get(line_info.ifun, None) |
|
617 | 616 | if isinstance(obj, IPyAutocall): |
|
618 | 617 | obj.set_ip(self.shell) |
|
619 | 618 | return self.prefilter_manager.get_handler_by_name('auto') |
|
620 | 619 | else: |
|
621 | 620 | return None |
|
622 | 621 | |
|
623 | 622 | |
|
624 | 623 | class MultiLineMagicChecker(PrefilterChecker): |
|
625 | 624 | |
|
626 | 625 | priority = Int(400, config=True) |
|
627 | 626 | |
|
628 | 627 | def check(self, line_info): |
|
629 | 628 | "Allow ! and !! in multi-line statements if multi_line_specials is on" |
|
630 | 629 | # Note that this one of the only places we check the first character of |
|
631 | 630 | # ifun and *not* the pre_char. Also note that the below test matches |
|
632 | 631 | # both ! and !!. |
|
633 | 632 | if line_info.continue_prompt \ |
|
634 | 633 | and self.prefilter_manager.multi_line_specials: |
|
635 | 634 | if line_info.ifun.startswith(ESC_MAGIC): |
|
636 | 635 | return self.prefilter_manager.get_handler_by_name('magic') |
|
637 | 636 | else: |
|
638 | 637 | return None |
|
639 | 638 | |
|
640 | 639 | |
|
641 | 640 | class EscCharsChecker(PrefilterChecker): |
|
642 | 641 | |
|
643 | 642 | priority = Int(500, config=True) |
|
644 | 643 | |
|
645 | 644 | def check(self, line_info): |
|
646 | 645 | """Check for escape character and return either a handler to handle it, |
|
647 | 646 | or None if there is no escape char.""" |
|
648 | 647 | if line_info.line[-1] == ESC_HELP \ |
|
649 | 648 | and line_info.pre_char != ESC_SHELL \ |
|
650 | 649 | and line_info.pre_char != ESC_SH_CAP: |
|
651 | 650 | # the ? can be at the end, but *not* for either kind of shell escape, |
|
652 | 651 | # because a ? can be a vaild final char in a shell cmd |
|
653 | 652 | return self.prefilter_manager.get_handler_by_name('help') |
|
654 | 653 | else: |
|
655 | 654 | # This returns None like it should if no handler exists |
|
656 | 655 | return self.prefilter_manager.get_handler_by_esc(line_info.pre_char) |
|
657 | 656 | |
|
658 | 657 | |
|
659 | 658 | class AssignmentChecker(PrefilterChecker): |
|
660 | 659 | |
|
661 | 660 | priority = Int(600, config=True) |
|
662 | 661 | |
|
663 | 662 | def check(self, line_info): |
|
664 | 663 | """Check to see if user is assigning to a var for the first time, in |
|
665 | 664 | which case we want to avoid any sort of automagic / autocall games. |
|
666 | 665 | |
|
667 | 666 | This allows users to assign to either alias or magic names true python |
|
668 | 667 | variables (the magic/alias systems always take second seat to true |
|
669 | 668 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
670 | 669 | if line_info.the_rest: |
|
671 | 670 | if line_info.the_rest[0] in '=,': |
|
672 | 671 | return self.prefilter_manager.get_handler_by_name('normal') |
|
673 | 672 | else: |
|
674 | 673 | return None |
|
675 | 674 | |
|
676 | 675 | |
|
677 | 676 | class AutoMagicChecker(PrefilterChecker): |
|
678 | 677 | |
|
679 | 678 | priority = Int(700, config=True) |
|
680 | 679 | |
|
681 | 680 | def check(self, line_info): |
|
682 | 681 | """If the ifun is magic, and automagic is on, run it. Note: normal, |
|
683 | 682 | non-auto magic would already have been triggered via '%' in |
|
684 | 683 | check_esc_chars. This just checks for automagic. Also, before |
|
685 | 684 | triggering the magic handler, make sure that there is nothing in the |
|
686 | 685 | user namespace which could shadow it.""" |
|
687 | 686 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): |
|
688 | 687 | return None |
|
689 | 688 | |
|
690 | 689 | # We have a likely magic method. Make sure we should actually call it. |
|
691 | 690 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: |
|
692 | 691 | return None |
|
693 | 692 | |
|
694 | 693 | head = line_info.ifun.split('.',1)[0] |
|
695 | 694 | if is_shadowed(head, self.shell): |
|
696 | 695 | return None |
|
697 | 696 | |
|
698 | 697 | return self.prefilter_manager.get_handler_by_name('magic') |
|
699 | 698 | |
|
700 | 699 | |
|
701 | 700 | class AliasChecker(PrefilterChecker): |
|
702 | 701 | |
|
703 | 702 | priority = Int(800, config=True) |
|
704 | 703 | |
|
705 | 704 | def check(self, line_info): |
|
706 | 705 | "Check if the initital identifier on the line is an alias." |
|
707 | 706 | # Note: aliases can not contain '.' |
|
708 | 707 | head = line_info.ifun.split('.',1)[0] |
|
709 | 708 | if line_info.ifun not in self.shell.alias_manager \ |
|
710 | 709 | or head not in self.shell.alias_manager \ |
|
711 | 710 | or is_shadowed(head, self.shell): |
|
712 | 711 | return None |
|
713 | 712 | |
|
714 | 713 | return self.prefilter_manager.get_handler_by_name('alias') |
|
715 | 714 | |
|
716 | 715 | |
|
717 | 716 | class PythonOpsChecker(PrefilterChecker): |
|
718 | 717 | |
|
719 | 718 | priority = Int(900, config=True) |
|
720 | 719 | |
|
721 | 720 | def check(self, line_info): |
|
722 | 721 | """If the 'rest' of the line begins with a function call or pretty much |
|
723 | 722 | any python operator, we should simply execute the line (regardless of |
|
724 | 723 | whether or not there's a possible autocall expansion). This avoids |
|
725 | 724 | spurious (and very confusing) geattr() accesses.""" |
|
726 | 725 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': |
|
727 | 726 | return self.prefilter_manager.get_handler_by_name('normal') |
|
728 | 727 | else: |
|
729 | 728 | return None |
|
730 | 729 | |
|
731 | 730 | |
|
732 | 731 | class AutocallChecker(PrefilterChecker): |
|
733 | 732 | |
|
734 | 733 | priority = Int(1000, config=True) |
|
735 | 734 | |
|
736 | 735 | def check(self, line_info): |
|
737 | 736 | "Check if the initial word/function is callable and autocall is on." |
|
738 | 737 | if not self.shell.autocall: |
|
739 | 738 | return None |
|
740 | 739 | |
|
741 | 740 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr |
|
742 | 741 | if not oinfo['found']: |
|
743 | 742 | return None |
|
744 | 743 | |
|
745 | 744 | if callable(oinfo['obj']) \ |
|
746 | 745 | and (not re_exclude_auto.match(line_info.the_rest)) \ |
|
747 | 746 | and re_fun_name.match(line_info.ifun): |
|
748 | 747 | return self.prefilter_manager.get_handler_by_name('auto') |
|
749 | 748 | else: |
|
750 | 749 | return None |
|
751 | 750 | |
|
752 | 751 | |
|
753 | 752 | #----------------------------------------------------------------------------- |
|
754 | 753 | # Prefilter handlers |
|
755 | 754 | #----------------------------------------------------------------------------- |
|
756 | 755 | |
|
757 | 756 | |
|
758 | 757 | class PrefilterHandler(Configurable): |
|
759 | 758 | |
|
760 | 759 | handler_name = Str('normal') |
|
761 | 760 | esc_strings = List([]) |
|
762 | 761 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
763 | 762 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
764 | 763 | |
|
765 | 764 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
766 | 765 | super(PrefilterHandler, self).__init__( |
|
767 | 766 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
768 | 767 | ) |
|
769 | 768 | self.prefilter_manager.register_handler( |
|
770 | 769 | self.handler_name, |
|
771 | 770 | self, |
|
772 | 771 | self.esc_strings |
|
773 | 772 | ) |
|
774 | 773 | |
|
775 | 774 | def handle(self, line_info): |
|
776 | 775 | # print "normal: ", line_info |
|
777 | 776 | """Handle normal input lines. Use as a template for handlers.""" |
|
778 | 777 | |
|
779 | 778 | # With autoindent on, we need some way to exit the input loop, and I |
|
780 | 779 | # don't want to force the user to have to backspace all the way to |
|
781 | 780 | # clear the line. The rule will be in this case, that either two |
|
782 | 781 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
783 | 782 | # of a size different to the indent level, will exit the input loop. |
|
784 | 783 | line = line_info.line |
|
785 | 784 | continue_prompt = line_info.continue_prompt |
|
786 | 785 | |
|
787 | 786 | if (continue_prompt and |
|
788 | 787 | self.shell.autoindent and |
|
789 | 788 | line.isspace() and |
|
790 | 789 | 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2): |
|
791 | 790 | line = '' |
|
792 | 791 | |
|
793 | 792 | return line |
|
794 | 793 | |
|
795 | 794 | def __str__(self): |
|
796 | 795 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) |
|
797 | 796 | |
|
798 | 797 | |
|
799 | 798 | class AliasHandler(PrefilterHandler): |
|
800 | 799 | |
|
801 | 800 | handler_name = Str('alias') |
|
802 | 801 | |
|
803 | 802 | def handle(self, line_info): |
|
804 | 803 | """Handle alias input lines. """ |
|
805 | 804 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) |
|
806 | 805 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
807 | 806 | # aliases won't work in indented sections. |
|
808 | 807 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
809 | 808 | make_quoted_expr(transformed)) |
|
810 | 809 | |
|
811 | 810 | return line_out |
|
812 | 811 | |
|
813 | 812 | |
|
814 | 813 | class ShellEscapeHandler(PrefilterHandler): |
|
815 | 814 | |
|
816 | 815 | handler_name = Str('shell') |
|
817 | 816 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) |
|
818 | 817 | |
|
819 | 818 | def handle(self, line_info): |
|
820 | 819 | """Execute the line in a shell, empty return value""" |
|
821 | 820 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') |
|
822 | 821 | |
|
823 | 822 | line = line_info.line |
|
824 | 823 | if line.lstrip().startswith(ESC_SH_CAP): |
|
825 | 824 | # rewrite LineInfo's line, ifun and the_rest to properly hold the |
|
826 | 825 | # call to %sx and the actual command to be executed, so |
|
827 | 826 | # handle_magic can work correctly. Note that this works even if |
|
828 | 827 | # the line is indented, so it handles multi_line_specials |
|
829 | 828 | # properly. |
|
830 | 829 | new_rest = line.lstrip()[2:] |
|
831 | 830 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) |
|
832 | 831 | line_info.ifun = 'sx' |
|
833 | 832 | line_info.the_rest = new_rest |
|
834 | 833 | return magic_handler.handle(line_info) |
|
835 | 834 | else: |
|
836 | 835 | cmd = line.lstrip().lstrip(ESC_SHELL) |
|
837 | 836 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
838 | 837 | make_quoted_expr(cmd)) |
|
839 | 838 | return line_out |
|
840 | 839 | |
|
841 | 840 | |
|
842 | 841 | class MacroHandler(PrefilterHandler): |
|
843 | 842 | handler_name = Str("macro") |
|
844 | 843 | |
|
845 | 844 | def handle(self, line_info): |
|
846 | 845 | obj = self.shell.user_ns.get(line_info.ifun) |
|
847 | 846 | pre_space = line_info.pre_whitespace |
|
848 | 847 | line_sep = "\n" + pre_space |
|
849 | 848 | return pre_space + line_sep.join(obj.value.splitlines()) |
|
850 | 849 | |
|
851 | 850 | |
|
852 | 851 | class MagicHandler(PrefilterHandler): |
|
853 | 852 | |
|
854 | 853 | handler_name = Str('magic') |
|
855 | 854 | esc_strings = List([ESC_MAGIC]) |
|
856 | 855 | |
|
857 | 856 | def handle(self, line_info): |
|
858 | 857 | """Execute magic functions.""" |
|
859 | 858 | ifun = line_info.ifun |
|
860 | 859 | the_rest = line_info.the_rest |
|
861 | 860 | cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace, |
|
862 | 861 | make_quoted_expr(ifun + " " + the_rest)) |
|
863 | 862 | return cmd |
|
864 | 863 | |
|
865 | 864 | |
|
866 | 865 | class AutoHandler(PrefilterHandler): |
|
867 | 866 | |
|
868 | 867 | handler_name = Str('auto') |
|
869 | 868 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) |
|
870 | 869 | |
|
871 | 870 | def handle(self, line_info): |
|
872 | 871 | """Handle lines which can be auto-executed, quoting if requested.""" |
|
873 | 872 | line = line_info.line |
|
874 | 873 | ifun = line_info.ifun |
|
875 | 874 | the_rest = line_info.the_rest |
|
876 | 875 | pre = line_info.pre |
|
877 | 876 | continue_prompt = line_info.continue_prompt |
|
878 | 877 | obj = line_info.ofind(self)['obj'] |
|
879 | 878 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg |
|
880 | 879 | |
|
881 | 880 | # This should only be active for single-line input! |
|
882 | 881 | if continue_prompt: |
|
883 | 882 | return line |
|
884 | 883 | |
|
885 | 884 | force_auto = isinstance(obj, IPyAutocall) |
|
886 | 885 | auto_rewrite = getattr(obj, 'rewrite', True) |
|
887 | 886 | |
|
888 | 887 | if pre == ESC_QUOTE: |
|
889 | 888 | # Auto-quote splitting on whitespace |
|
890 | 889 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) |
|
891 | 890 | elif pre == ESC_QUOTE2: |
|
892 | 891 | # Auto-quote whole string |
|
893 | 892 | newcmd = '%s("%s")' % (ifun,the_rest) |
|
894 | 893 | elif pre == ESC_PAREN: |
|
895 | 894 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) |
|
896 | 895 | else: |
|
897 | 896 | # Auto-paren. |
|
898 | 897 | # We only apply it to argument-less calls if the autocall |
|
899 | 898 | # parameter is set to 2. We only need to check that autocall is < |
|
900 | 899 | # 2, since this function isn't called unless it's at least 1. |
|
901 | 900 | if not the_rest and (self.shell.autocall < 2) and not force_auto: |
|
902 | 901 | newcmd = '%s %s' % (ifun,the_rest) |
|
903 | 902 | auto_rewrite = False |
|
904 | 903 | else: |
|
905 | 904 | if not force_auto and the_rest.startswith('['): |
|
906 | 905 | if hasattr(obj,'__getitem__'): |
|
907 | 906 | # Don't autocall in this case: item access for an object |
|
908 | 907 | # which is BOTH callable and implements __getitem__. |
|
909 | 908 | newcmd = '%s %s' % (ifun,the_rest) |
|
910 | 909 | auto_rewrite = False |
|
911 | 910 | else: |
|
912 | 911 | # if the object doesn't support [] access, go ahead and |
|
913 | 912 | # autocall |
|
914 | 913 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) |
|
915 | 914 | elif the_rest.endswith(';'): |
|
916 | 915 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) |
|
917 | 916 | else: |
|
918 | 917 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) |
|
919 | 918 | |
|
920 | 919 | if auto_rewrite: |
|
921 | 920 | self.shell.auto_rewrite_input(newcmd) |
|
922 | 921 | |
|
923 | 922 | return newcmd |
|
924 | 923 | |
|
925 | 924 | |
|
926 | 925 | class HelpHandler(PrefilterHandler): |
|
927 | 926 | |
|
928 | 927 | handler_name = Str('help') |
|
929 | 928 | esc_strings = List([ESC_HELP]) |
|
930 | 929 | |
|
931 | 930 | def handle(self, line_info): |
|
932 | 931 | """Try to get some help for the object. |
|
933 | 932 | |
|
934 | 933 | obj? or ?obj -> basic information. |
|
935 | 934 | obj?? or ??obj -> more details. |
|
936 | 935 | """ |
|
937 | 936 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') |
|
938 | 937 | line = line_info.line |
|
939 | 938 | # We need to make sure that we don't process lines which would be |
|
940 | 939 | # otherwise valid python, such as "x=1 # what?" |
|
941 | 940 | try: |
|
942 | 941 | codeop.compile_command(line) |
|
943 | 942 | except SyntaxError: |
|
944 | 943 | # We should only handle as help stuff which is NOT valid syntax |
|
945 | 944 | if line[0]==ESC_HELP: |
|
946 | 945 | line = line[1:] |
|
947 | 946 | elif line[-1]==ESC_HELP: |
|
948 | 947 | line = line[:-1] |
|
949 | 948 | if line: |
|
950 | 949 | #print 'line:<%r>' % line # dbg |
|
951 | 950 | self.shell.magic_pinfo(line) |
|
952 | 951 | else: |
|
953 | 952 | self.shell.show_usage() |
|
954 | 953 | return '' # Empty string is needed here! |
|
955 | 954 | except: |
|
956 | 955 | raise |
|
957 | 956 | # Pass any other exceptions through to the normal handler |
|
958 | 957 | return normal_handler.handle(line_info) |
|
959 | 958 | else: |
|
960 | 959 | # If the code compiles ok, we should handle it normally |
|
961 | 960 | return normal_handler.handle(line_info) |
|
962 | 961 | |
|
963 | 962 | |
|
964 | 963 | class EmacsHandler(PrefilterHandler): |
|
965 | 964 | |
|
966 | 965 | handler_name = Str('emacs') |
|
967 | 966 | esc_strings = List([]) |
|
968 | 967 | |
|
969 | 968 | def handle(self, line_info): |
|
970 | 969 | """Handle input lines marked by python-mode.""" |
|
971 | 970 | |
|
972 | 971 | # Currently, nothing is done. Later more functionality can be added |
|
973 | 972 | # here if needed. |
|
974 | 973 | |
|
975 | 974 | # The input cache shouldn't be updated |
|
976 | 975 | return line_info.line |
|
977 | 976 | |
|
978 | 977 | |
|
979 | 978 | #----------------------------------------------------------------------------- |
|
980 | 979 | # Defaults |
|
981 | 980 | #----------------------------------------------------------------------------- |
|
982 | 981 | |
|
983 | 982 | |
|
984 | 983 | _default_transformers = [ |
|
985 | 984 | AssignSystemTransformer, |
|
986 | 985 | AssignMagicTransformer, |
|
987 | 986 | PyPromptTransformer, |
|
988 | 987 | IPyPromptTransformer, |
|
989 | 988 | ] |
|
990 | 989 | |
|
991 | 990 | _default_checkers = [ |
|
992 | 991 | EmacsChecker, |
|
993 | 992 | ShellEscapeChecker, |
|
994 | 993 | MacroChecker, |
|
995 | 994 | IPyAutocallChecker, |
|
996 | 995 | MultiLineMagicChecker, |
|
997 | 996 | EscCharsChecker, |
|
998 | 997 | AssignmentChecker, |
|
999 | 998 | AutoMagicChecker, |
|
1000 | 999 | AliasChecker, |
|
1001 | 1000 | PythonOpsChecker, |
|
1002 | 1001 | AutocallChecker |
|
1003 | 1002 | ] |
|
1004 | 1003 | |
|
1005 | 1004 | _default_handlers = [ |
|
1006 | 1005 | PrefilterHandler, |
|
1007 | 1006 | AliasHandler, |
|
1008 | 1007 | ShellEscapeHandler, |
|
1009 | 1008 | MacroHandler, |
|
1010 | 1009 | MagicHandler, |
|
1011 | 1010 | AutoHandler, |
|
1012 | 1011 | HelpHandler, |
|
1013 | 1012 | EmacsHandler |
|
1014 | 1013 | ] |
@@ -1,1243 +1,1243 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | ultratb.py -- Spice up your tracebacks! |
|
4 | 4 | |
|
5 | 5 | * ColorTB |
|
6 | 6 | I've always found it a bit hard to visually parse tracebacks in Python. The |
|
7 | 7 | ColorTB class is a solution to that problem. It colors the different parts of a |
|
8 | 8 | traceback in a manner similar to what you would expect from a syntax-highlighting |
|
9 | 9 | text editor. |
|
10 | 10 | |
|
11 | 11 | Installation instructions for ColorTB: |
|
12 | 12 | import sys,ultratb |
|
13 | 13 | sys.excepthook = ultratb.ColorTB() |
|
14 | 14 | |
|
15 | 15 | * VerboseTB |
|
16 | 16 | I've also included a port of Ka-Ping Yee's "cgitb.py" that produces all kinds |
|
17 | 17 | of useful info when a traceback occurs. Ping originally had it spit out HTML |
|
18 | 18 | and intended it for CGI programmers, but why should they have all the fun? I |
|
19 | 19 | altered it to spit out colored text to the terminal. It's a bit overwhelming, |
|
20 | 20 | but kind of neat, and maybe useful for long-running programs that you believe |
|
21 | 21 | are bug-free. If a crash *does* occur in that type of program you want details. |
|
22 | 22 | Give it a shot--you'll love it or you'll hate it. |
|
23 | 23 | |
|
24 | 24 | Note: |
|
25 | 25 | |
|
26 | 26 | The Verbose mode prints the variables currently visible where the exception |
|
27 | 27 | happened (shortening their strings if too long). This can potentially be |
|
28 | 28 | very slow, if you happen to have a huge data structure whose string |
|
29 | 29 | representation is complex to compute. Your computer may appear to freeze for |
|
30 | 30 | a while with cpu usage at 100%. If this occurs, you can cancel the traceback |
|
31 | 31 | with Ctrl-C (maybe hitting it more than once). |
|
32 | 32 | |
|
33 | 33 | If you encounter this kind of situation often, you may want to use the |
|
34 | 34 | Verbose_novars mode instead of the regular Verbose, which avoids formatting |
|
35 | 35 | variables (but otherwise includes the information and context given by |
|
36 | 36 | Verbose). |
|
37 | 37 | |
|
38 | 38 | |
|
39 | 39 | Installation instructions for ColorTB: |
|
40 | 40 | import sys,ultratb |
|
41 | 41 | sys.excepthook = ultratb.VerboseTB() |
|
42 | 42 | |
|
43 | 43 | Note: Much of the code in this module was lifted verbatim from the standard |
|
44 | 44 | library module 'traceback.py' and Ka-Ping Yee's 'cgitb.py'. |
|
45 | 45 | |
|
46 | 46 | * Color schemes |
|
47 | 47 | The colors are defined in the class TBTools through the use of the |
|
48 | 48 | ColorSchemeTable class. Currently the following exist: |
|
49 | 49 | |
|
50 | 50 | - NoColor: allows all of this module to be used in any terminal (the color |
|
51 | 51 | escapes are just dummy blank strings). |
|
52 | 52 | |
|
53 | 53 | - Linux: is meant to look good in a terminal like the Linux console (black |
|
54 | 54 | or very dark background). |
|
55 | 55 | |
|
56 | 56 | - LightBG: similar to Linux but swaps dark/light colors to be more readable |
|
57 | 57 | in light background terminals. |
|
58 | 58 | |
|
59 | 59 | You can implement other color schemes easily, the syntax is fairly |
|
60 | 60 | self-explanatory. Please send back new schemes you develop to the author for |
|
61 | 61 | possible inclusion in future releases. |
|
62 | 62 | """ |
|
63 | 63 | |
|
64 | 64 | #***************************************************************************** |
|
65 | 65 | # Copyright (C) 2001 Nathaniel Gray <n8gray@caltech.edu> |
|
66 | 66 | # Copyright (C) 2001-2004 Fernando Perez <fperez@colorado.edu> |
|
67 | 67 | # |
|
68 | 68 | # Distributed under the terms of the BSD License. The full license is in |
|
69 | 69 | # the file COPYING, distributed as part of this software. |
|
70 | 70 | #***************************************************************************** |
|
71 | 71 | |
|
72 | 72 | from __future__ import with_statement |
|
73 | 73 | |
|
74 | 74 | import inspect |
|
75 | 75 | import keyword |
|
76 | 76 | import linecache |
|
77 | 77 | import os |
|
78 | 78 | import pydoc |
|
79 | 79 | import re |
|
80 | 80 | import sys |
|
81 | 81 | import time |
|
82 | 82 | import tokenize |
|
83 | 83 | import traceback |
|
84 | 84 | import types |
|
85 | 85 | |
|
86 | 86 | # For purposes of monkeypatching inspect to fix a bug in it. |
|
87 | 87 | from inspect import getsourcefile, getfile, getmodule,\ |
|
88 | 88 | ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode |
|
89 | 89 | |
|
90 | 90 | # IPython's own modules |
|
91 | 91 | # Modified pdb which doesn't damage IPython's readline handling |
|
92 | 92 | from IPython.core import debugger, ipapi |
|
93 | 93 | from IPython.core.display_trap import DisplayTrap |
|
94 | 94 | from IPython.core.excolors import exception_colors |
|
95 | 95 | from IPython.utils import PyColorize |
|
96 | 96 | from IPython.utils import io |
|
97 | 97 | from IPython.utils.data import uniq_stable |
|
98 | 98 | from IPython.utils.warn import info, error |
|
99 | 99 | |
|
100 | 100 | # Globals |
|
101 | 101 | # amount of space to put line numbers before verbose tracebacks |
|
102 | 102 | INDENT_SIZE = 8 |
|
103 | 103 | |
|
104 | 104 | # Default color scheme. This is used, for example, by the traceback |
|
105 | 105 | # formatter. When running in an actual IPython instance, the user's rc.colors |
|
106 | 106 | # value is used, but havinga module global makes this functionality available |
|
107 | 107 | # to users of ultratb who are NOT running inside ipython. |
|
108 | 108 | DEFAULT_SCHEME = 'NoColor' |
|
109 | 109 | |
|
110 | 110 | #--------------------------------------------------------------------------- |
|
111 | 111 | # Code begins |
|
112 | 112 | |
|
113 | 113 | # Utility functions |
|
114 | 114 | def inspect_error(): |
|
115 | 115 | """Print a message about internal inspect errors. |
|
116 | 116 | |
|
117 | 117 | These are unfortunately quite common.""" |
|
118 | 118 | |
|
119 | 119 | error('Internal Python error in the inspect module.\n' |
|
120 | 120 | 'Below is the traceback from this internal error.\n') |
|
121 | 121 | |
|
122 | 122 | |
|
123 | 123 | def findsource(object): |
|
124 | 124 | """Return the entire source file and starting line number for an object. |
|
125 | 125 | |
|
126 | 126 | The argument may be a module, class, method, function, traceback, frame, |
|
127 | 127 | or code object. The source code is returned as a list of all the lines |
|
128 | 128 | in the file and the line number indexes a line in that list. An IOError |
|
129 | 129 | is raised if the source code cannot be retrieved. |
|
130 | 130 | |
|
131 | 131 | FIXED version with which we monkeypatch the stdlib to work around a bug.""" |
|
132 | 132 | |
|
133 | 133 | file = getsourcefile(object) or getfile(object) |
|
134 | 134 | # If the object is a frame, then trying to get the globals dict from its |
|
135 | 135 | # module won't work. Instead, the frame object itself has the globals |
|
136 | 136 | # dictionary. |
|
137 | 137 | globals_dict = None |
|
138 | 138 | if inspect.isframe(object): |
|
139 | 139 | # XXX: can this ever be false? |
|
140 | 140 | globals_dict = object.f_globals |
|
141 | 141 | else: |
|
142 | 142 | module = getmodule(object, file) |
|
143 | 143 | if module: |
|
144 | 144 | globals_dict = module.__dict__ |
|
145 | 145 | lines = linecache.getlines(file, globals_dict) |
|
146 | 146 | if not lines: |
|
147 | 147 | raise IOError('could not get source code') |
|
148 | 148 | |
|
149 | 149 | if ismodule(object): |
|
150 | 150 | return lines, 0 |
|
151 | 151 | |
|
152 | 152 | if isclass(object): |
|
153 | 153 | name = object.__name__ |
|
154 | 154 | pat = re.compile(r'^(\s*)class\s*' + name + r'\b') |
|
155 | 155 | # make some effort to find the best matching class definition: |
|
156 | 156 | # use the one with the least indentation, which is the one |
|
157 | 157 | # that's most probably not inside a function definition. |
|
158 | 158 | candidates = [] |
|
159 | 159 | for i in range(len(lines)): |
|
160 | 160 | match = pat.match(lines[i]) |
|
161 | 161 | if match: |
|
162 | 162 | # if it's at toplevel, it's already the best one |
|
163 | 163 | if lines[i][0] == 'c': |
|
164 | 164 | return lines, i |
|
165 | 165 | # else add whitespace to candidate list |
|
166 | 166 | candidates.append((match.group(1), i)) |
|
167 | 167 | if candidates: |
|
168 | 168 | # this will sort by whitespace, and by line number, |
|
169 | 169 | # less whitespace first |
|
170 | 170 | candidates.sort() |
|
171 | 171 | return lines, candidates[0][1] |
|
172 | 172 | else: |
|
173 | 173 | raise IOError('could not find class definition') |
|
174 | 174 | |
|
175 | 175 | if ismethod(object): |
|
176 | 176 | object = object.im_func |
|
177 | 177 | if isfunction(object): |
|
178 | 178 | object = object.func_code |
|
179 | 179 | if istraceback(object): |
|
180 | 180 | object = object.tb_frame |
|
181 | 181 | if isframe(object): |
|
182 | 182 | object = object.f_code |
|
183 | 183 | if iscode(object): |
|
184 | 184 | if not hasattr(object, 'co_firstlineno'): |
|
185 | 185 | raise IOError('could not find function definition') |
|
186 | 186 | pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)') |
|
187 | 187 | pmatch = pat.match |
|
188 | 188 | # fperez - fix: sometimes, co_firstlineno can give a number larger than |
|
189 | 189 | # the length of lines, which causes an error. Safeguard against that. |
|
190 | 190 | lnum = min(object.co_firstlineno,len(lines))-1 |
|
191 | 191 | while lnum > 0: |
|
192 | 192 | if pmatch(lines[lnum]): break |
|
193 | 193 | lnum -= 1 |
|
194 | 194 | |
|
195 | 195 | return lines, lnum |
|
196 | 196 | raise IOError('could not find code object') |
|
197 | 197 | |
|
198 | 198 | # Monkeypatch inspect to apply our bugfix. This code only works with py25 |
|
199 | 199 | if sys.version_info[:2] >= (2,5): |
|
200 | 200 | inspect.findsource = findsource |
|
201 | 201 | |
|
202 | 202 | def fix_frame_records_filenames(records): |
|
203 | 203 | """Try to fix the filenames in each record from inspect.getinnerframes(). |
|
204 | 204 | |
|
205 | 205 | Particularly, modules loaded from within zip files have useless filenames |
|
206 | 206 | attached to their code object, and inspect.getinnerframes() just uses it. |
|
207 | 207 | """ |
|
208 | 208 | fixed_records = [] |
|
209 | 209 | for frame, filename, line_no, func_name, lines, index in records: |
|
210 | 210 | # Look inside the frame's globals dictionary for __file__, which should |
|
211 | 211 | # be better. |
|
212 | 212 | better_fn = frame.f_globals.get('__file__', None) |
|
213 | 213 | if isinstance(better_fn, str): |
|
214 | 214 | # Check the type just in case someone did something weird with |
|
215 | 215 | # __file__. It might also be None if the error occurred during |
|
216 | 216 | # import. |
|
217 | 217 | filename = better_fn |
|
218 | 218 | fixed_records.append((frame, filename, line_no, func_name, lines, index)) |
|
219 | 219 | return fixed_records |
|
220 | 220 | |
|
221 | 221 | |
|
222 | 222 | def _fixed_getinnerframes(etb, context=1,tb_offset=0): |
|
223 | 223 | import linecache |
|
224 | 224 | LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 |
|
225 | 225 | |
|
226 | 226 | records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) |
|
227 | 227 | |
|
228 | 228 | # If the error is at the console, don't build any context, since it would |
|
229 | 229 | # otherwise produce 5 blank lines printed out (there is no file at the |
|
230 | 230 | # console) |
|
231 | 231 | rec_check = records[tb_offset:] |
|
232 | 232 | try: |
|
233 | 233 | rname = rec_check[0][1] |
|
234 | 234 | if rname == '<ipython console>' or rname.endswith('<string>'): |
|
235 | 235 | return rec_check |
|
236 | 236 | except IndexError: |
|
237 | 237 | pass |
|
238 | 238 | |
|
239 | 239 | aux = traceback.extract_tb(etb) |
|
240 | 240 | assert len(records) == len(aux) |
|
241 | 241 | for i, (file, lnum, _, _) in zip(range(len(records)), aux): |
|
242 | 242 | maybeStart = lnum-1 - context//2 |
|
243 | 243 | start = max(maybeStart, 0) |
|
244 | 244 | end = start + context |
|
245 | 245 | lines = linecache.getlines(file)[start:end] |
|
246 | 246 | buf = list(records[i]) |
|
247 | 247 | buf[LNUM_POS] = lnum |
|
248 | 248 | buf[INDEX_POS] = lnum - 1 - start |
|
249 | 249 | buf[LINES_POS] = lines |
|
250 | 250 | records[i] = tuple(buf) |
|
251 | 251 | return records[tb_offset:] |
|
252 | 252 | |
|
253 | 253 | # Helper function -- largely belongs to VerboseTB, but we need the same |
|
254 | 254 | # functionality to produce a pseudo verbose TB for SyntaxErrors, so that they |
|
255 | 255 | # can be recognized properly by ipython.el's py-traceback-line-re |
|
256 | 256 | # (SyntaxErrors have to be treated specially because they have no traceback) |
|
257 | 257 | |
|
258 | 258 | _parser = PyColorize.Parser() |
|
259 | 259 | |
|
260 | 260 | def _format_traceback_lines(lnum, index, lines, Colors, lvals=None,scheme=None): |
|
261 | 261 | numbers_width = INDENT_SIZE - 1 |
|
262 | 262 | res = [] |
|
263 | 263 | i = lnum - index |
|
264 | 264 | |
|
265 | 265 | # This lets us get fully syntax-highlighted tracebacks. |
|
266 | 266 | if scheme is None: |
|
267 | 267 | ipinst = ipapi.get() |
|
268 | 268 | if ipinst is not None: |
|
269 | 269 | scheme = ipinst.colors |
|
270 | 270 | else: |
|
271 | 271 | scheme = DEFAULT_SCHEME |
|
272 | 272 | |
|
273 | 273 | _line_format = _parser.format2 |
|
274 | 274 | |
|
275 | 275 | for line in lines: |
|
276 | 276 | # FIXME: we need to ensure the source is a pure string at this point, |
|
277 | 277 | # else the coloring code makes a royal mess. This is in need of a |
|
278 | 278 | # serious refactoring, so that all of the ultratb and PyColorize code |
|
279 | 279 | # is unicode-safe. So for now this is rather an ugly hack, but |
|
280 | 280 | # necessary to at least have readable tracebacks. Improvements welcome! |
|
281 | 281 | if type(line)==unicode: |
|
282 | 282 | line = line.encode('utf-8', 'replace') |
|
283 | 283 | |
|
284 | 284 | new_line, err = _line_format(line, 'str', scheme) |
|
285 | 285 | if not err: line = new_line |
|
286 | 286 | |
|
287 | 287 | if i == lnum: |
|
288 | 288 | # This is the line with the error |
|
289 | 289 | pad = numbers_width - len(str(i)) |
|
290 | 290 | if pad >= 3: |
|
291 | 291 | marker = '-'*(pad-3) + '-> ' |
|
292 | 292 | elif pad == 2: |
|
293 | 293 | marker = '> ' |
|
294 | 294 | elif pad == 1: |
|
295 | 295 | marker = '>' |
|
296 | 296 | else: |
|
297 | 297 | marker = '' |
|
298 | 298 | num = marker + str(i) |
|
299 | 299 | line = '%s%s%s %s%s' %(Colors.linenoEm, num, |
|
300 | 300 | Colors.line, line, Colors.Normal) |
|
301 | 301 | else: |
|
302 | 302 | num = '%*s' % (numbers_width,i) |
|
303 | 303 | line = '%s%s%s %s' %(Colors.lineno, num, |
|
304 | 304 | Colors.Normal, line) |
|
305 | 305 | |
|
306 | 306 | res.append(line) |
|
307 | 307 | if lvals and i == lnum: |
|
308 | 308 | res.append(lvals + '\n') |
|
309 | 309 | i = i + 1 |
|
310 | 310 | return res |
|
311 | 311 | |
|
312 | 312 | |
|
313 | 313 | #--------------------------------------------------------------------------- |
|
314 | 314 | # Module classes |
|
315 | 315 | class TBTools(object): |
|
316 | 316 | """Basic tools used by all traceback printer classes.""" |
|
317 | 317 | |
|
318 | 318 | # Number of frames to skip when reporting tracebacks |
|
319 | 319 | tb_offset = 0 |
|
320 | 320 | |
|
321 | 321 | def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None): |
|
322 | 322 | # Whether to call the interactive pdb debugger after printing |
|
323 | 323 | # tracebacks or not |
|
324 | 324 | self.call_pdb = call_pdb |
|
325 | 325 | |
|
326 | 326 | # Output stream to write to. Note that we store the original value in |
|
327 | 327 | # a private attribute and then make the public ostream a property, so |
|
328 |
# that we can delay accessing io. |
|
|
329 |
# things are written now, the |
|
|
328 | # that we can delay accessing io.stdout until runtime. The way | |
|
329 | # things are written now, the io.stdout object is dynamically managed | |
|
330 | 330 | # so a reference to it should NEVER be stored statically. This |
|
331 | 331 | # property approach confines this detail to a single location, and all |
|
332 | 332 | # subclasses can simply access self.ostream for writing. |
|
333 | 333 | self._ostream = ostream |
|
334 | 334 | |
|
335 | 335 | # Create color table |
|
336 | 336 | self.color_scheme_table = exception_colors() |
|
337 | 337 | |
|
338 | 338 | self.set_colors(color_scheme) |
|
339 | 339 | self.old_scheme = color_scheme # save initial value for toggles |
|
340 | 340 | |
|
341 | 341 | if call_pdb: |
|
342 | 342 | self.pdb = debugger.Pdb(self.color_scheme_table.active_scheme_name) |
|
343 | 343 | else: |
|
344 | 344 | self.pdb = None |
|
345 | 345 | |
|
346 | 346 | def _get_ostream(self): |
|
347 | 347 | """Output stream that exceptions are written to. |
|
348 | 348 | |
|
349 | 349 | Valid values are: |
|
350 | 350 | |
|
351 | 351 | - None: the default, which means that IPython will dynamically resolve |
|
352 |
to io. |
|
|
352 | to io.stdout. This ensures compatibility with most tools, including | |
|
353 | 353 | Windows (where plain stdout doesn't recognize ANSI escapes). |
|
354 | 354 | |
|
355 | 355 | - Any object with 'write' and 'flush' attributes. |
|
356 | 356 | """ |
|
357 |
return io. |
|
|
357 | return io.stdout if self._ostream is None else self._ostream | |
|
358 | 358 | |
|
359 | 359 | def _set_ostream(self, val): |
|
360 | 360 | assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush')) |
|
361 | 361 | self._ostream = val |
|
362 | 362 | |
|
363 | 363 | ostream = property(_get_ostream, _set_ostream) |
|
364 | 364 | |
|
365 | 365 | def set_colors(self,*args,**kw): |
|
366 | 366 | """Shorthand access to the color table scheme selector method.""" |
|
367 | 367 | |
|
368 | 368 | # Set own color table |
|
369 | 369 | self.color_scheme_table.set_active_scheme(*args,**kw) |
|
370 | 370 | # for convenience, set Colors to the active scheme |
|
371 | 371 | self.Colors = self.color_scheme_table.active_colors |
|
372 | 372 | # Also set colors of debugger |
|
373 | 373 | if hasattr(self,'pdb') and self.pdb is not None: |
|
374 | 374 | self.pdb.set_colors(*args,**kw) |
|
375 | 375 | |
|
376 | 376 | def color_toggle(self): |
|
377 | 377 | """Toggle between the currently active color scheme and NoColor.""" |
|
378 | 378 | |
|
379 | 379 | if self.color_scheme_table.active_scheme_name == 'NoColor': |
|
380 | 380 | self.color_scheme_table.set_active_scheme(self.old_scheme) |
|
381 | 381 | self.Colors = self.color_scheme_table.active_colors |
|
382 | 382 | else: |
|
383 | 383 | self.old_scheme = self.color_scheme_table.active_scheme_name |
|
384 | 384 | self.color_scheme_table.set_active_scheme('NoColor') |
|
385 | 385 | self.Colors = self.color_scheme_table.active_colors |
|
386 | 386 | |
|
387 | 387 | def stb2text(self, stb): |
|
388 | 388 | """Convert a structured traceback (a list) to a string.""" |
|
389 | 389 | return '\n'.join(stb) |
|
390 | 390 | |
|
391 | 391 | def text(self, etype, value, tb, tb_offset=None, context=5): |
|
392 | 392 | """Return formatted traceback. |
|
393 | 393 | |
|
394 | 394 | Subclasses may override this if they add extra arguments. |
|
395 | 395 | """ |
|
396 | 396 | tb_list = self.structured_traceback(etype, value, tb, |
|
397 | 397 | tb_offset, context) |
|
398 | 398 | return self.stb2text(tb_list) |
|
399 | 399 | |
|
400 | 400 | def structured_traceback(self, etype, evalue, tb, tb_offset=None, |
|
401 | 401 | context=5, mode=None): |
|
402 | 402 | """Return a list of traceback frames. |
|
403 | 403 | |
|
404 | 404 | Must be implemented by each class. |
|
405 | 405 | """ |
|
406 | 406 | raise NotImplementedError() |
|
407 | 407 | |
|
408 | 408 | |
|
409 | 409 | #--------------------------------------------------------------------------- |
|
410 | 410 | class ListTB(TBTools): |
|
411 | 411 | """Print traceback information from a traceback list, with optional color. |
|
412 | 412 | |
|
413 | 413 | Calling: requires 3 arguments: |
|
414 | 414 | (etype, evalue, elist) |
|
415 | 415 | as would be obtained by: |
|
416 | 416 | etype, evalue, tb = sys.exc_info() |
|
417 | 417 | if tb: |
|
418 | 418 | elist = traceback.extract_tb(tb) |
|
419 | 419 | else: |
|
420 | 420 | elist = None |
|
421 | 421 | |
|
422 | 422 | It can thus be used by programs which need to process the traceback before |
|
423 | 423 | printing (such as console replacements based on the code module from the |
|
424 | 424 | standard library). |
|
425 | 425 | |
|
426 | 426 | Because they are meant to be called without a full traceback (only a |
|
427 | 427 | list), instances of this class can't call the interactive pdb debugger.""" |
|
428 | 428 | |
|
429 | 429 | def __init__(self,color_scheme = 'NoColor', call_pdb=False, ostream=None): |
|
430 | 430 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
431 | 431 | ostream=ostream) |
|
432 | 432 | |
|
433 | 433 | def __call__(self, etype, value, elist): |
|
434 | 434 | self.ostream.flush() |
|
435 | 435 | self.ostream.write(self.text(etype, value, elist)) |
|
436 | 436 | self.ostream.write('\n') |
|
437 | 437 | |
|
438 | 438 | def structured_traceback(self, etype, value, elist, tb_offset=None, |
|
439 | 439 | context=5): |
|
440 | 440 | """Return a color formatted string with the traceback info. |
|
441 | 441 | |
|
442 | 442 | Parameters |
|
443 | 443 | ---------- |
|
444 | 444 | etype : exception type |
|
445 | 445 | Type of the exception raised. |
|
446 | 446 | |
|
447 | 447 | value : object |
|
448 | 448 | Data stored in the exception |
|
449 | 449 | |
|
450 | 450 | elist : list |
|
451 | 451 | List of frames, see class docstring for details. |
|
452 | 452 | |
|
453 | 453 | tb_offset : int, optional |
|
454 | 454 | Number of frames in the traceback to skip. If not given, the |
|
455 | 455 | instance value is used (set in constructor). |
|
456 | 456 | |
|
457 | 457 | context : int, optional |
|
458 | 458 | Number of lines of context information to print. |
|
459 | 459 | |
|
460 | 460 | Returns |
|
461 | 461 | ------- |
|
462 | 462 | String with formatted exception. |
|
463 | 463 | """ |
|
464 | 464 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
465 | 465 | Colors = self.Colors |
|
466 | 466 | out_list = [] |
|
467 | 467 | if elist: |
|
468 | 468 | |
|
469 | 469 | if tb_offset and len(elist) > tb_offset: |
|
470 | 470 | elist = elist[tb_offset:] |
|
471 | 471 | |
|
472 | 472 | out_list.append('Traceback %s(most recent call last)%s:' % |
|
473 | 473 | (Colors.normalEm, Colors.Normal) + '\n') |
|
474 | 474 | out_list.extend(self._format_list(elist)) |
|
475 | 475 | # The exception info should be a single entry in the list. |
|
476 | 476 | lines = ''.join(self._format_exception_only(etype, value)) |
|
477 | 477 | out_list.append(lines) |
|
478 | 478 | |
|
479 | 479 | # Note: this code originally read: |
|
480 | 480 | |
|
481 | 481 | ## for line in lines[:-1]: |
|
482 | 482 | ## out_list.append(" "+line) |
|
483 | 483 | ## out_list.append(lines[-1]) |
|
484 | 484 | |
|
485 | 485 | # This means it was indenting everything but the last line by a little |
|
486 | 486 | # bit. I've disabled this for now, but if we see ugliness somewhre we |
|
487 | 487 | # can restore it. |
|
488 | 488 | |
|
489 | 489 | return out_list |
|
490 | 490 | |
|
491 | 491 | def _format_list(self, extracted_list): |
|
492 | 492 | """Format a list of traceback entry tuples for printing. |
|
493 | 493 | |
|
494 | 494 | Given a list of tuples as returned by extract_tb() or |
|
495 | 495 | extract_stack(), return a list of strings ready for printing. |
|
496 | 496 | Each string in the resulting list corresponds to the item with the |
|
497 | 497 | same index in the argument list. Each string ends in a newline; |
|
498 | 498 | the strings may contain internal newlines as well, for those items |
|
499 | 499 | whose source text line is not None. |
|
500 | 500 | |
|
501 | 501 | Lifted almost verbatim from traceback.py |
|
502 | 502 | """ |
|
503 | 503 | |
|
504 | 504 | Colors = self.Colors |
|
505 | 505 | list = [] |
|
506 | 506 | for filename, lineno, name, line in extracted_list[:-1]: |
|
507 | 507 | item = ' File %s"%s"%s, line %s%d%s, in %s%s%s\n' % \ |
|
508 | 508 | (Colors.filename, filename, Colors.Normal, |
|
509 | 509 | Colors.lineno, lineno, Colors.Normal, |
|
510 | 510 | Colors.name, name, Colors.Normal) |
|
511 | 511 | if line: |
|
512 | 512 | item = item + ' %s\n' % line.strip() |
|
513 | 513 | list.append(item) |
|
514 | 514 | # Emphasize the last entry |
|
515 | 515 | filename, lineno, name, line = extracted_list[-1] |
|
516 | 516 | item = '%s File %s"%s"%s, line %s%d%s, in %s%s%s%s\n' % \ |
|
517 | 517 | (Colors.normalEm, |
|
518 | 518 | Colors.filenameEm, filename, Colors.normalEm, |
|
519 | 519 | Colors.linenoEm, lineno, Colors.normalEm, |
|
520 | 520 | Colors.nameEm, name, Colors.normalEm, |
|
521 | 521 | Colors.Normal) |
|
522 | 522 | if line: |
|
523 | 523 | item = item + '%s %s%s\n' % (Colors.line, line.strip(), |
|
524 | 524 | Colors.Normal) |
|
525 | 525 | list.append(item) |
|
526 | 526 | #from pprint import pformat; print 'LISTTB', pformat(list) # dbg |
|
527 | 527 | return list |
|
528 | 528 | |
|
529 | 529 | def _format_exception_only(self, etype, value): |
|
530 | 530 | """Format the exception part of a traceback. |
|
531 | 531 | |
|
532 | 532 | The arguments are the exception type and value such as given by |
|
533 | 533 | sys.exc_info()[:2]. The return value is a list of strings, each ending |
|
534 | 534 | in a newline. Normally, the list contains a single string; however, |
|
535 | 535 | for SyntaxError exceptions, it contains several lines that (when |
|
536 | 536 | printed) display detailed information about where the syntax error |
|
537 | 537 | occurred. The message indicating which exception occurred is the |
|
538 | 538 | always last string in the list. |
|
539 | 539 | |
|
540 | 540 | Also lifted nearly verbatim from traceback.py |
|
541 | 541 | """ |
|
542 | 542 | |
|
543 | 543 | have_filedata = False |
|
544 | 544 | Colors = self.Colors |
|
545 | 545 | list = [] |
|
546 | 546 | try: |
|
547 | 547 | stype = Colors.excName + etype.__name__ + Colors.Normal |
|
548 | 548 | except AttributeError: |
|
549 | 549 | stype = etype # String exceptions don't get special coloring |
|
550 | 550 | if value is None: |
|
551 | 551 | list.append( str(stype) + '\n') |
|
552 | 552 | else: |
|
553 | 553 | if etype is SyntaxError: |
|
554 | 554 | try: |
|
555 | 555 | msg, (filename, lineno, offset, line) = value |
|
556 | 556 | except: |
|
557 | 557 | have_filedata = False |
|
558 | 558 | else: |
|
559 | 559 | have_filedata = True |
|
560 | 560 | #print 'filename is',filename # dbg |
|
561 | 561 | if not filename: filename = "<string>" |
|
562 | 562 | list.append('%s File %s"%s"%s, line %s%d%s\n' % \ |
|
563 | 563 | (Colors.normalEm, |
|
564 | 564 | Colors.filenameEm, filename, Colors.normalEm, |
|
565 | 565 | Colors.linenoEm, lineno, Colors.Normal )) |
|
566 | 566 | if line is not None: |
|
567 | 567 | i = 0 |
|
568 | 568 | while i < len(line) and line[i].isspace(): |
|
569 | 569 | i = i+1 |
|
570 | 570 | list.append('%s %s%s\n' % (Colors.line, |
|
571 | 571 | line.strip(), |
|
572 | 572 | Colors.Normal)) |
|
573 | 573 | if offset is not None: |
|
574 | 574 | s = ' ' |
|
575 | 575 | for c in line[i:offset-1]: |
|
576 | 576 | if c.isspace(): |
|
577 | 577 | s = s + c |
|
578 | 578 | else: |
|
579 | 579 | s = s + ' ' |
|
580 | 580 | list.append('%s%s^%s\n' % (Colors.caret, s, |
|
581 | 581 | Colors.Normal) ) |
|
582 | 582 | value = msg |
|
583 | 583 | s = self._some_str(value) |
|
584 | 584 | if s: |
|
585 | 585 | list.append('%s%s:%s %s\n' % (str(stype), Colors.excName, |
|
586 | 586 | Colors.Normal, s)) |
|
587 | 587 | else: |
|
588 | 588 | list.append('%s\n' % str(stype)) |
|
589 | 589 | |
|
590 | 590 | # sync with user hooks |
|
591 | 591 | if have_filedata: |
|
592 | 592 | ipinst = ipapi.get() |
|
593 | 593 | if ipinst is not None: |
|
594 | 594 | ipinst.hooks.synchronize_with_editor(filename, lineno, 0) |
|
595 | 595 | |
|
596 | 596 | return list |
|
597 | 597 | |
|
598 | 598 | def get_exception_only(self, etype, value): |
|
599 | 599 | """Only print the exception type and message, without a traceback. |
|
600 | 600 | |
|
601 | 601 | Parameters |
|
602 | 602 | ---------- |
|
603 | 603 | etype : exception type |
|
604 | 604 | value : exception value |
|
605 | 605 | """ |
|
606 | 606 | return ListTB.structured_traceback(self, etype, value, []) |
|
607 | 607 | |
|
608 | 608 | |
|
609 | 609 | def show_exception_only(self, etype, evalue): |
|
610 | 610 | """Only print the exception type and message, without a traceback. |
|
611 | 611 | |
|
612 | 612 | Parameters |
|
613 | 613 | ---------- |
|
614 | 614 | etype : exception type |
|
615 | 615 | value : exception value |
|
616 | 616 | """ |
|
617 | 617 | # This method needs to use __call__ from *this* class, not the one from |
|
618 | 618 | # a subclass whose signature or behavior may be different |
|
619 | 619 | ostream = self.ostream |
|
620 | 620 | ostream.flush() |
|
621 | 621 | ostream.write('\n'.join(self.get_exception_only(etype, evalue))) |
|
622 | 622 | ostream.flush() |
|
623 | 623 | |
|
624 | 624 | def _some_str(self, value): |
|
625 | 625 | # Lifted from traceback.py |
|
626 | 626 | try: |
|
627 | 627 | return str(value) |
|
628 | 628 | except: |
|
629 | 629 | return '<unprintable %s object>' % type(value).__name__ |
|
630 | 630 | |
|
631 | 631 | #---------------------------------------------------------------------------- |
|
632 | 632 | class VerboseTB(TBTools): |
|
633 | 633 | """A port of Ka-Ping Yee's cgitb.py module that outputs color text instead |
|
634 | 634 | of HTML. Requires inspect and pydoc. Crazy, man. |
|
635 | 635 | |
|
636 | 636 | Modified version which optionally strips the topmost entries from the |
|
637 | 637 | traceback, to be used with alternate interpreters (because their own code |
|
638 | 638 | would appear in the traceback).""" |
|
639 | 639 | |
|
640 | 640 | def __init__(self,color_scheme = 'Linux', call_pdb=False, ostream=None, |
|
641 | 641 | tb_offset=0, long_header=False, include_vars=True, |
|
642 | 642 | check_cache=None): |
|
643 | 643 | """Specify traceback offset, headers and color scheme. |
|
644 | 644 | |
|
645 | 645 | Define how many frames to drop from the tracebacks. Calling it with |
|
646 | 646 | tb_offset=1 allows use of this handler in interpreters which will have |
|
647 | 647 | their own code at the top of the traceback (VerboseTB will first |
|
648 | 648 | remove that frame before printing the traceback info).""" |
|
649 | 649 | TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
650 | 650 | ostream=ostream) |
|
651 | 651 | self.tb_offset = tb_offset |
|
652 | 652 | self.long_header = long_header |
|
653 | 653 | self.include_vars = include_vars |
|
654 | 654 | # By default we use linecache.checkcache, but the user can provide a |
|
655 | 655 | # different check_cache implementation. This is used by the IPython |
|
656 | 656 | # kernel to provide tracebacks for interactive code that is cached, |
|
657 | 657 | # by a compiler instance that flushes the linecache but preserves its |
|
658 | 658 | # own code cache. |
|
659 | 659 | if check_cache is None: |
|
660 | 660 | check_cache = linecache.checkcache |
|
661 | 661 | self.check_cache = check_cache |
|
662 | 662 | |
|
663 | 663 | def structured_traceback(self, etype, evalue, etb, tb_offset=None, |
|
664 | 664 | context=5): |
|
665 | 665 | """Return a nice text document describing the traceback.""" |
|
666 | 666 | |
|
667 | 667 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
668 | 668 | |
|
669 | 669 | # some locals |
|
670 | 670 | try: |
|
671 | 671 | etype = etype.__name__ |
|
672 | 672 | except AttributeError: |
|
673 | 673 | pass |
|
674 | 674 | Colors = self.Colors # just a shorthand + quicker name lookup |
|
675 | 675 | ColorsNormal = Colors.Normal # used a lot |
|
676 | 676 | col_scheme = self.color_scheme_table.active_scheme_name |
|
677 | 677 | indent = ' '*INDENT_SIZE |
|
678 | 678 | em_normal = '%s\n%s%s' % (Colors.valEm, indent,ColorsNormal) |
|
679 | 679 | undefined = '%sundefined%s' % (Colors.em, ColorsNormal) |
|
680 | 680 | exc = '%s%s%s' % (Colors.excName,etype,ColorsNormal) |
|
681 | 681 | |
|
682 | 682 | # some internal-use functions |
|
683 | 683 | def text_repr(value): |
|
684 | 684 | """Hopefully pretty robust repr equivalent.""" |
|
685 | 685 | # this is pretty horrible but should always return *something* |
|
686 | 686 | try: |
|
687 | 687 | return pydoc.text.repr(value) |
|
688 | 688 | except KeyboardInterrupt: |
|
689 | 689 | raise |
|
690 | 690 | except: |
|
691 | 691 | try: |
|
692 | 692 | return repr(value) |
|
693 | 693 | except KeyboardInterrupt: |
|
694 | 694 | raise |
|
695 | 695 | except: |
|
696 | 696 | try: |
|
697 | 697 | # all still in an except block so we catch |
|
698 | 698 | # getattr raising |
|
699 | 699 | name = getattr(value, '__name__', None) |
|
700 | 700 | if name: |
|
701 | 701 | # ick, recursion |
|
702 | 702 | return text_repr(name) |
|
703 | 703 | klass = getattr(value, '__class__', None) |
|
704 | 704 | if klass: |
|
705 | 705 | return '%s instance' % text_repr(klass) |
|
706 | 706 | except KeyboardInterrupt: |
|
707 | 707 | raise |
|
708 | 708 | except: |
|
709 | 709 | return 'UNRECOVERABLE REPR FAILURE' |
|
710 | 710 | def eqrepr(value, repr=text_repr): return '=%s' % repr(value) |
|
711 | 711 | def nullrepr(value, repr=text_repr): return '' |
|
712 | 712 | |
|
713 | 713 | # meat of the code begins |
|
714 | 714 | try: |
|
715 | 715 | etype = etype.__name__ |
|
716 | 716 | except AttributeError: |
|
717 | 717 | pass |
|
718 | 718 | |
|
719 | 719 | if self.long_header: |
|
720 | 720 | # Header with the exception type, python version, and date |
|
721 | 721 | pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable |
|
722 | 722 | date = time.ctime(time.time()) |
|
723 | 723 | |
|
724 | 724 | head = '%s%s%s\n%s%s%s\n%s' % (Colors.topline, '-'*75, ColorsNormal, |
|
725 | 725 | exc, ' '*(75-len(str(etype))-len(pyver)), |
|
726 | 726 | pyver, date.rjust(75) ) |
|
727 | 727 | head += "\nA problem occured executing Python code. Here is the sequence of function"\ |
|
728 | 728 | "\ncalls leading up to the error, with the most recent (innermost) call last." |
|
729 | 729 | else: |
|
730 | 730 | # Simplified header |
|
731 | 731 | head = '%s%s%s\n%s%s' % (Colors.topline, '-'*75, ColorsNormal,exc, |
|
732 | 732 | 'Traceback (most recent call last)'.\ |
|
733 | 733 | rjust(75 - len(str(etype)) ) ) |
|
734 | 734 | frames = [] |
|
735 | 735 | # Flush cache before calling inspect. This helps alleviate some of the |
|
736 | 736 | # problems with python 2.3's inspect.py. |
|
737 | 737 | ##self.check_cache() |
|
738 | 738 | # Drop topmost frames if requested |
|
739 | 739 | try: |
|
740 | 740 | # Try the default getinnerframes and Alex's: Alex's fixes some |
|
741 | 741 | # problems, but it generates empty tracebacks for console errors |
|
742 | 742 | # (5 blanks lines) where none should be returned. |
|
743 | 743 | #records = inspect.getinnerframes(etb, context)[tb_offset:] |
|
744 | 744 | #print 'python records:', records # dbg |
|
745 | 745 | records = _fixed_getinnerframes(etb, context, tb_offset) |
|
746 | 746 | #print 'alex records:', records # dbg |
|
747 | 747 | except: |
|
748 | 748 | |
|
749 | 749 | # FIXME: I've been getting many crash reports from python 2.3 |
|
750 | 750 | # users, traceable to inspect.py. If I can find a small test-case |
|
751 | 751 | # to reproduce this, I should either write a better workaround or |
|
752 | 752 | # file a bug report against inspect (if that's the real problem). |
|
753 | 753 | # So far, I haven't been able to find an isolated example to |
|
754 | 754 | # reproduce the problem. |
|
755 | 755 | inspect_error() |
|
756 | 756 | traceback.print_exc(file=self.ostream) |
|
757 | 757 | info('\nUnfortunately, your original traceback can not be constructed.\n') |
|
758 | 758 | return '' |
|
759 | 759 | |
|
760 | 760 | # build some color string templates outside these nested loops |
|
761 | 761 | tpl_link = '%s%%s%s' % (Colors.filenameEm,ColorsNormal) |
|
762 | 762 | tpl_call = 'in %s%%s%s%%s%s' % (Colors.vName, Colors.valEm, |
|
763 | 763 | ColorsNormal) |
|
764 | 764 | tpl_call_fail = 'in %s%%s%s(***failed resolving arguments***)%s' % \ |
|
765 | 765 | (Colors.vName, Colors.valEm, ColorsNormal) |
|
766 | 766 | tpl_local_var = '%s%%s%s' % (Colors.vName, ColorsNormal) |
|
767 | 767 | tpl_global_var = '%sglobal%s %s%%s%s' % (Colors.em, ColorsNormal, |
|
768 | 768 | Colors.vName, ColorsNormal) |
|
769 | 769 | tpl_name_val = '%%s %s= %%s%s' % (Colors.valEm, ColorsNormal) |
|
770 | 770 | tpl_line = '%s%%s%s %%s' % (Colors.lineno, ColorsNormal) |
|
771 | 771 | tpl_line_em = '%s%%s%s %%s%s' % (Colors.linenoEm,Colors.line, |
|
772 | 772 | ColorsNormal) |
|
773 | 773 | |
|
774 | 774 | # now, loop over all records printing context and info |
|
775 | 775 | abspath = os.path.abspath |
|
776 | 776 | for frame, file, lnum, func, lines, index in records: |
|
777 | 777 | #print '*** record:',file,lnum,func,lines,index # dbg |
|
778 | 778 | try: |
|
779 | 779 | file = file and abspath(file) or '?' |
|
780 | 780 | except OSError: |
|
781 | 781 | # if file is '<console>' or something not in the filesystem, |
|
782 | 782 | # the abspath call will throw an OSError. Just ignore it and |
|
783 | 783 | # keep the original file string. |
|
784 | 784 | pass |
|
785 | 785 | link = tpl_link % file |
|
786 | 786 | try: |
|
787 | 787 | args, varargs, varkw, locals = inspect.getargvalues(frame) |
|
788 | 788 | except: |
|
789 | 789 | # This can happen due to a bug in python2.3. We should be |
|
790 | 790 | # able to remove this try/except when 2.4 becomes a |
|
791 | 791 | # requirement. Bug details at http://python.org/sf/1005466 |
|
792 | 792 | inspect_error() |
|
793 | 793 | traceback.print_exc(file=self.ostream) |
|
794 | 794 | info("\nIPython's exception reporting continues...\n") |
|
795 | 795 | |
|
796 | 796 | if func == '?': |
|
797 | 797 | call = '' |
|
798 | 798 | else: |
|
799 | 799 | # Decide whether to include variable details or not |
|
800 | 800 | var_repr = self.include_vars and eqrepr or nullrepr |
|
801 | 801 | try: |
|
802 | 802 | call = tpl_call % (func,inspect.formatargvalues(args, |
|
803 | 803 | varargs, varkw, |
|
804 | 804 | locals,formatvalue=var_repr)) |
|
805 | 805 | except KeyError: |
|
806 | 806 | # This happens in situations like errors inside generator |
|
807 | 807 | # expressions, where local variables are listed in the |
|
808 | 808 | # line, but can't be extracted from the frame. I'm not |
|
809 | 809 | # 100% sure this isn't actually a bug in inspect itself, |
|
810 | 810 | # but since there's no info for us to compute with, the |
|
811 | 811 | # best we can do is report the failure and move on. Here |
|
812 | 812 | # we must *not* call any traceback construction again, |
|
813 | 813 | # because that would mess up use of %debug later on. So we |
|
814 | 814 | # simply report the failure and move on. The only |
|
815 | 815 | # limitation will be that this frame won't have locals |
|
816 | 816 | # listed in the call signature. Quite subtle problem... |
|
817 | 817 | # I can't think of a good way to validate this in a unit |
|
818 | 818 | # test, but running a script consisting of: |
|
819 | 819 | # dict( (k,v.strip()) for (k,v) in range(10) ) |
|
820 | 820 | # will illustrate the error, if this exception catch is |
|
821 | 821 | # disabled. |
|
822 | 822 | call = tpl_call_fail % func |
|
823 | 823 | |
|
824 | 824 | # Initialize a list of names on the current line, which the |
|
825 | 825 | # tokenizer below will populate. |
|
826 | 826 | names = [] |
|
827 | 827 | |
|
828 | 828 | def tokeneater(token_type, token, start, end, line): |
|
829 | 829 | """Stateful tokeneater which builds dotted names. |
|
830 | 830 | |
|
831 | 831 | The list of names it appends to (from the enclosing scope) can |
|
832 | 832 | contain repeated composite names. This is unavoidable, since |
|
833 | 833 | there is no way to disambguate partial dotted structures until |
|
834 | 834 | the full list is known. The caller is responsible for pruning |
|
835 | 835 | the final list of duplicates before using it.""" |
|
836 | 836 | |
|
837 | 837 | # build composite names |
|
838 | 838 | if token == '.': |
|
839 | 839 | try: |
|
840 | 840 | names[-1] += '.' |
|
841 | 841 | # store state so the next token is added for x.y.z names |
|
842 | 842 | tokeneater.name_cont = True |
|
843 | 843 | return |
|
844 | 844 | except IndexError: |
|
845 | 845 | pass |
|
846 | 846 | if token_type == tokenize.NAME and token not in keyword.kwlist: |
|
847 | 847 | if tokeneater.name_cont: |
|
848 | 848 | # Dotted names |
|
849 | 849 | names[-1] += token |
|
850 | 850 | tokeneater.name_cont = False |
|
851 | 851 | else: |
|
852 | 852 | # Regular new names. We append everything, the caller |
|
853 | 853 | # will be responsible for pruning the list later. It's |
|
854 | 854 | # very tricky to try to prune as we go, b/c composite |
|
855 | 855 | # names can fool us. The pruning at the end is easy |
|
856 | 856 | # to do (or the caller can print a list with repeated |
|
857 | 857 | # names if so desired. |
|
858 | 858 | names.append(token) |
|
859 | 859 | elif token_type == tokenize.NEWLINE: |
|
860 | 860 | raise IndexError |
|
861 | 861 | # we need to store a bit of state in the tokenizer to build |
|
862 | 862 | # dotted names |
|
863 | 863 | tokeneater.name_cont = False |
|
864 | 864 | |
|
865 | 865 | def linereader(file=file, lnum=[lnum], getline=linecache.getline): |
|
866 | 866 | line = getline(file, lnum[0]) |
|
867 | 867 | lnum[0] += 1 |
|
868 | 868 | return line |
|
869 | 869 | |
|
870 | 870 | # Build the list of names on this line of code where the exception |
|
871 | 871 | # occurred. |
|
872 | 872 | try: |
|
873 | 873 | # This builds the names list in-place by capturing it from the |
|
874 | 874 | # enclosing scope. |
|
875 | 875 | tokenize.tokenize(linereader, tokeneater) |
|
876 | 876 | except IndexError: |
|
877 | 877 | # signals exit of tokenizer |
|
878 | 878 | pass |
|
879 | 879 | except tokenize.TokenError,msg: |
|
880 | 880 | _m = ("An unexpected error occurred while tokenizing input\n" |
|
881 | 881 | "The following traceback may be corrupted or invalid\n" |
|
882 | 882 | "The error message is: %s\n" % msg) |
|
883 | 883 | error(_m) |
|
884 | 884 | |
|
885 | 885 | # prune names list of duplicates, but keep the right order |
|
886 | 886 | unique_names = uniq_stable(names) |
|
887 | 887 | |
|
888 | 888 | # Start loop over vars |
|
889 | 889 | lvals = [] |
|
890 | 890 | if self.include_vars: |
|
891 | 891 | for name_full in unique_names: |
|
892 | 892 | name_base = name_full.split('.',1)[0] |
|
893 | 893 | if name_base in frame.f_code.co_varnames: |
|
894 | 894 | if locals.has_key(name_base): |
|
895 | 895 | try: |
|
896 | 896 | value = repr(eval(name_full,locals)) |
|
897 | 897 | except: |
|
898 | 898 | value = undefined |
|
899 | 899 | else: |
|
900 | 900 | value = undefined |
|
901 | 901 | name = tpl_local_var % name_full |
|
902 | 902 | else: |
|
903 | 903 | if frame.f_globals.has_key(name_base): |
|
904 | 904 | try: |
|
905 | 905 | value = repr(eval(name_full,frame.f_globals)) |
|
906 | 906 | except: |
|
907 | 907 | value = undefined |
|
908 | 908 | else: |
|
909 | 909 | value = undefined |
|
910 | 910 | name = tpl_global_var % name_full |
|
911 | 911 | lvals.append(tpl_name_val % (name,value)) |
|
912 | 912 | if lvals: |
|
913 | 913 | lvals = '%s%s' % (indent,em_normal.join(lvals)) |
|
914 | 914 | else: |
|
915 | 915 | lvals = '' |
|
916 | 916 | |
|
917 | 917 | level = '%s %s\n' % (link,call) |
|
918 | 918 | |
|
919 | 919 | if index is None: |
|
920 | 920 | frames.append(level) |
|
921 | 921 | else: |
|
922 | 922 | frames.append('%s%s' % (level,''.join( |
|
923 | 923 | _format_traceback_lines(lnum,index,lines,Colors,lvals, |
|
924 | 924 | col_scheme)))) |
|
925 | 925 | |
|
926 | 926 | # Get (safely) a string form of the exception info |
|
927 | 927 | try: |
|
928 | 928 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
929 | 929 | except: |
|
930 | 930 | # User exception is improperly defined. |
|
931 | 931 | etype,evalue = str,sys.exc_info()[:2] |
|
932 | 932 | etype_str,evalue_str = map(str,(etype,evalue)) |
|
933 | 933 | # ... and format it |
|
934 | 934 | exception = ['%s%s%s: %s' % (Colors.excName, etype_str, |
|
935 | 935 | ColorsNormal, evalue_str)] |
|
936 | 936 | if type(evalue) is types.InstanceType: |
|
937 | 937 | try: |
|
938 | 938 | names = [w for w in dir(evalue) if isinstance(w, basestring)] |
|
939 | 939 | except: |
|
940 | 940 | # Every now and then, an object with funny inernals blows up |
|
941 | 941 | # when dir() is called on it. We do the best we can to report |
|
942 | 942 | # the problem and continue |
|
943 | 943 | _m = '%sException reporting error (object with broken dir())%s:' |
|
944 | 944 | exception.append(_m % (Colors.excName,ColorsNormal)) |
|
945 | 945 | etype_str,evalue_str = map(str,sys.exc_info()[:2]) |
|
946 | 946 | exception.append('%s%s%s: %s' % (Colors.excName,etype_str, |
|
947 | 947 | ColorsNormal, evalue_str)) |
|
948 | 948 | names = [] |
|
949 | 949 | for name in names: |
|
950 | 950 | value = text_repr(getattr(evalue, name)) |
|
951 | 951 | exception.append('\n%s%s = %s' % (indent, name, value)) |
|
952 | 952 | |
|
953 | 953 | # vds: >> |
|
954 | 954 | if records: |
|
955 | 955 | filepath, lnum = records[-1][1:3] |
|
956 | 956 | #print "file:", str(file), "linenb", str(lnum) # dbg |
|
957 | 957 | filepath = os.path.abspath(filepath) |
|
958 | 958 | ipinst = ipapi.get() |
|
959 | 959 | if ipinst is not None: |
|
960 | 960 | ipinst.hooks.synchronize_with_editor(filepath, lnum, 0) |
|
961 | 961 | # vds: << |
|
962 | 962 | |
|
963 | 963 | # return all our info assembled as a single string |
|
964 | 964 | # return '%s\n\n%s\n%s' % (head,'\n'.join(frames),''.join(exception[0]) ) |
|
965 | 965 | return [head] + frames + [''.join(exception[0])] |
|
966 | 966 | |
|
967 | 967 | def debugger(self,force=False): |
|
968 | 968 | """Call up the pdb debugger if desired, always clean up the tb |
|
969 | 969 | reference. |
|
970 | 970 | |
|
971 | 971 | Keywords: |
|
972 | 972 | |
|
973 | 973 | - force(False): by default, this routine checks the instance call_pdb |
|
974 | 974 | flag and does not actually invoke the debugger if the flag is false. |
|
975 | 975 | The 'force' option forces the debugger to activate even if the flag |
|
976 | 976 | is false. |
|
977 | 977 | |
|
978 | 978 | If the call_pdb flag is set, the pdb interactive debugger is |
|
979 | 979 | invoked. In all cases, the self.tb reference to the current traceback |
|
980 | 980 | is deleted to prevent lingering references which hamper memory |
|
981 | 981 | management. |
|
982 | 982 | |
|
983 | 983 | Note that each call to pdb() does an 'import readline', so if your app |
|
984 | 984 | requires a special setup for the readline completers, you'll have to |
|
985 | 985 | fix that by hand after invoking the exception handler.""" |
|
986 | 986 | |
|
987 | 987 | if force or self.call_pdb: |
|
988 | 988 | if self.pdb is None: |
|
989 | 989 | self.pdb = debugger.Pdb( |
|
990 | 990 | self.color_scheme_table.active_scheme_name) |
|
991 | 991 | # the system displayhook may have changed, restore the original |
|
992 | 992 | # for pdb |
|
993 | 993 | display_trap = DisplayTrap(hook=sys.__displayhook__) |
|
994 | 994 | with display_trap: |
|
995 | 995 | self.pdb.reset() |
|
996 | 996 | # Find the right frame so we don't pop up inside ipython itself |
|
997 | 997 | if hasattr(self,'tb') and self.tb is not None: |
|
998 | 998 | etb = self.tb |
|
999 | 999 | else: |
|
1000 | 1000 | etb = self.tb = sys.last_traceback |
|
1001 | 1001 | while self.tb is not None and self.tb.tb_next is not None: |
|
1002 | 1002 | self.tb = self.tb.tb_next |
|
1003 | 1003 | if etb and etb.tb_next: |
|
1004 | 1004 | etb = etb.tb_next |
|
1005 | 1005 | self.pdb.botframe = etb.tb_frame |
|
1006 | 1006 | self.pdb.interaction(self.tb.tb_frame, self.tb) |
|
1007 | 1007 | |
|
1008 | 1008 | if hasattr(self,'tb'): |
|
1009 | 1009 | del self.tb |
|
1010 | 1010 | |
|
1011 | 1011 | def handler(self, info=None): |
|
1012 | 1012 | (etype, evalue, etb) = info or sys.exc_info() |
|
1013 | 1013 | self.tb = etb |
|
1014 | 1014 | ostream = self.ostream |
|
1015 | 1015 | ostream.flush() |
|
1016 | 1016 | ostream.write(self.text(etype, evalue, etb)) |
|
1017 | 1017 | ostream.write('\n') |
|
1018 | 1018 | ostream.flush() |
|
1019 | 1019 | |
|
1020 | 1020 | # Changed so an instance can just be called as VerboseTB_inst() and print |
|
1021 | 1021 | # out the right info on its own. |
|
1022 | 1022 | def __call__(self, etype=None, evalue=None, etb=None): |
|
1023 | 1023 | """This hook can replace sys.excepthook (for Python 2.1 or higher).""" |
|
1024 | 1024 | if etb is None: |
|
1025 | 1025 | self.handler() |
|
1026 | 1026 | else: |
|
1027 | 1027 | self.handler((etype, evalue, etb)) |
|
1028 | 1028 | try: |
|
1029 | 1029 | self.debugger() |
|
1030 | 1030 | except KeyboardInterrupt: |
|
1031 | 1031 | print "\nKeyboardInterrupt" |
|
1032 | 1032 | |
|
1033 | 1033 | #---------------------------------------------------------------------------- |
|
1034 | 1034 | class FormattedTB(VerboseTB, ListTB): |
|
1035 | 1035 | """Subclass ListTB but allow calling with a traceback. |
|
1036 | 1036 | |
|
1037 | 1037 | It can thus be used as a sys.excepthook for Python > 2.1. |
|
1038 | 1038 | |
|
1039 | 1039 | Also adds 'Context' and 'Verbose' modes, not available in ListTB. |
|
1040 | 1040 | |
|
1041 | 1041 | Allows a tb_offset to be specified. This is useful for situations where |
|
1042 | 1042 | one needs to remove a number of topmost frames from the traceback (such as |
|
1043 | 1043 | occurs with python programs that themselves execute other python code, |
|
1044 | 1044 | like Python shells). """ |
|
1045 | 1045 | |
|
1046 | 1046 | def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False, |
|
1047 | 1047 | ostream=None, |
|
1048 | 1048 | tb_offset=0, long_header=False, include_vars=False, |
|
1049 | 1049 | check_cache=None): |
|
1050 | 1050 | |
|
1051 | 1051 | # NEVER change the order of this list. Put new modes at the end: |
|
1052 | 1052 | self.valid_modes = ['Plain','Context','Verbose'] |
|
1053 | 1053 | self.verbose_modes = self.valid_modes[1:3] |
|
1054 | 1054 | |
|
1055 | 1055 | VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb, |
|
1056 | 1056 | ostream=ostream, tb_offset=tb_offset, |
|
1057 | 1057 | long_header=long_header, include_vars=include_vars, |
|
1058 | 1058 | check_cache=check_cache) |
|
1059 | 1059 | |
|
1060 | 1060 | # Different types of tracebacks are joined with different separators to |
|
1061 | 1061 | # form a single string. They are taken from this dict |
|
1062 | 1062 | self._join_chars = dict(Plain='', Context='\n', Verbose='\n') |
|
1063 | 1063 | # set_mode also sets the tb_join_char attribute |
|
1064 | 1064 | self.set_mode(mode) |
|
1065 | 1065 | |
|
1066 | 1066 | def _extract_tb(self,tb): |
|
1067 | 1067 | if tb: |
|
1068 | 1068 | return traceback.extract_tb(tb) |
|
1069 | 1069 | else: |
|
1070 | 1070 | return None |
|
1071 | 1071 | |
|
1072 | 1072 | def structured_traceback(self, etype, value, tb, tb_offset=None, context=5): |
|
1073 | 1073 | tb_offset = self.tb_offset if tb_offset is None else tb_offset |
|
1074 | 1074 | mode = self.mode |
|
1075 | 1075 | if mode in self.verbose_modes: |
|
1076 | 1076 | # Verbose modes need a full traceback |
|
1077 | 1077 | return VerboseTB.structured_traceback( |
|
1078 | 1078 | self, etype, value, tb, tb_offset, context |
|
1079 | 1079 | ) |
|
1080 | 1080 | else: |
|
1081 | 1081 | # We must check the source cache because otherwise we can print |
|
1082 | 1082 | # out-of-date source code. |
|
1083 | 1083 | self.check_cache() |
|
1084 | 1084 | # Now we can extract and format the exception |
|
1085 | 1085 | elist = self._extract_tb(tb) |
|
1086 | 1086 | return ListTB.structured_traceback( |
|
1087 | 1087 | self, etype, value, elist, tb_offset, context |
|
1088 | 1088 | ) |
|
1089 | 1089 | |
|
1090 | 1090 | def stb2text(self, stb): |
|
1091 | 1091 | """Convert a structured traceback (a list) to a string.""" |
|
1092 | 1092 | return self.tb_join_char.join(stb) |
|
1093 | 1093 | |
|
1094 | 1094 | |
|
1095 | 1095 | def set_mode(self,mode=None): |
|
1096 | 1096 | """Switch to the desired mode. |
|
1097 | 1097 | |
|
1098 | 1098 | If mode is not specified, cycles through the available modes.""" |
|
1099 | 1099 | |
|
1100 | 1100 | if not mode: |
|
1101 | 1101 | new_idx = ( self.valid_modes.index(self.mode) + 1 ) % \ |
|
1102 | 1102 | len(self.valid_modes) |
|
1103 | 1103 | self.mode = self.valid_modes[new_idx] |
|
1104 | 1104 | elif mode not in self.valid_modes: |
|
1105 | 1105 | raise ValueError, 'Unrecognized mode in FormattedTB: <'+mode+'>\n'\ |
|
1106 | 1106 | 'Valid modes: '+str(self.valid_modes) |
|
1107 | 1107 | else: |
|
1108 | 1108 | self.mode = mode |
|
1109 | 1109 | # include variable details only in 'Verbose' mode |
|
1110 | 1110 | self.include_vars = (self.mode == self.valid_modes[2]) |
|
1111 | 1111 | # Set the join character for generating text tracebacks |
|
1112 | 1112 | self.tb_join_char = self._join_chars[self.mode] |
|
1113 | 1113 | |
|
1114 | 1114 | # some convenient shorcuts |
|
1115 | 1115 | def plain(self): |
|
1116 | 1116 | self.set_mode(self.valid_modes[0]) |
|
1117 | 1117 | |
|
1118 | 1118 | def context(self): |
|
1119 | 1119 | self.set_mode(self.valid_modes[1]) |
|
1120 | 1120 | |
|
1121 | 1121 | def verbose(self): |
|
1122 | 1122 | self.set_mode(self.valid_modes[2]) |
|
1123 | 1123 | |
|
1124 | 1124 | #---------------------------------------------------------------------------- |
|
1125 | 1125 | class AutoFormattedTB(FormattedTB): |
|
1126 | 1126 | """A traceback printer which can be called on the fly. |
|
1127 | 1127 | |
|
1128 | 1128 | It will find out about exceptions by itself. |
|
1129 | 1129 | |
|
1130 | 1130 | A brief example: |
|
1131 | 1131 | |
|
1132 | 1132 | AutoTB = AutoFormattedTB(mode = 'Verbose',color_scheme='Linux') |
|
1133 | 1133 | try: |
|
1134 | 1134 | ... |
|
1135 | 1135 | except: |
|
1136 | 1136 | AutoTB() # or AutoTB(out=logfile) where logfile is an open file object |
|
1137 | 1137 | """ |
|
1138 | 1138 | |
|
1139 | 1139 | def __call__(self,etype=None,evalue=None,etb=None, |
|
1140 | 1140 | out=None,tb_offset=None): |
|
1141 | 1141 | """Print out a formatted exception traceback. |
|
1142 | 1142 | |
|
1143 | 1143 | Optional arguments: |
|
1144 | 1144 | - out: an open file-like object to direct output to. |
|
1145 | 1145 | |
|
1146 | 1146 | - tb_offset: the number of frames to skip over in the stack, on a |
|
1147 | 1147 | per-call basis (this overrides temporarily the instance's tb_offset |
|
1148 | 1148 | given at initialization time. """ |
|
1149 | 1149 | |
|
1150 | 1150 | |
|
1151 | 1151 | if out is None: |
|
1152 | 1152 | out = self.ostream |
|
1153 | 1153 | out.flush() |
|
1154 | 1154 | out.write(self.text(etype, evalue, etb, tb_offset)) |
|
1155 | 1155 | out.write('\n') |
|
1156 | 1156 | out.flush() |
|
1157 | 1157 | # FIXME: we should remove the auto pdb behavior from here and leave |
|
1158 | 1158 | # that to the clients. |
|
1159 | 1159 | try: |
|
1160 | 1160 | self.debugger() |
|
1161 | 1161 | except KeyboardInterrupt: |
|
1162 | 1162 | print "\nKeyboardInterrupt" |
|
1163 | 1163 | |
|
1164 | 1164 | def structured_traceback(self, etype=None, value=None, tb=None, |
|
1165 | 1165 | tb_offset=None, context=5): |
|
1166 | 1166 | if etype is None: |
|
1167 | 1167 | etype,value,tb = sys.exc_info() |
|
1168 | 1168 | self.tb = tb |
|
1169 | 1169 | return FormattedTB.structured_traceback( |
|
1170 | 1170 | self, etype, value, tb, tb_offset, context) |
|
1171 | 1171 | |
|
1172 | 1172 | #--------------------------------------------------------------------------- |
|
1173 | 1173 | |
|
1174 | 1174 | # A simple class to preserve Nathan's original functionality. |
|
1175 | 1175 | class ColorTB(FormattedTB): |
|
1176 | 1176 | """Shorthand to initialize a FormattedTB in Linux colors mode.""" |
|
1177 | 1177 | def __init__(self,color_scheme='Linux',call_pdb=0): |
|
1178 | 1178 | FormattedTB.__init__(self,color_scheme=color_scheme, |
|
1179 | 1179 | call_pdb=call_pdb) |
|
1180 | 1180 | |
|
1181 | 1181 | |
|
1182 | 1182 | class SyntaxTB(ListTB): |
|
1183 | 1183 | """Extension which holds some state: the last exception value""" |
|
1184 | 1184 | |
|
1185 | 1185 | def __init__(self,color_scheme = 'NoColor'): |
|
1186 | 1186 | ListTB.__init__(self,color_scheme) |
|
1187 | 1187 | self.last_syntax_error = None |
|
1188 | 1188 | |
|
1189 | 1189 | def __call__(self, etype, value, elist): |
|
1190 | 1190 | self.last_syntax_error = value |
|
1191 | 1191 | ListTB.__call__(self,etype,value,elist) |
|
1192 | 1192 | |
|
1193 | 1193 | def clear_err_state(self): |
|
1194 | 1194 | """Return the current error state and clear it""" |
|
1195 | 1195 | e = self.last_syntax_error |
|
1196 | 1196 | self.last_syntax_error = None |
|
1197 | 1197 | return e |
|
1198 | 1198 | |
|
1199 | 1199 | def stb2text(self, stb): |
|
1200 | 1200 | """Convert a structured traceback (a list) to a string.""" |
|
1201 | 1201 | return ''.join(stb) |
|
1202 | 1202 | |
|
1203 | 1203 | |
|
1204 | 1204 | #---------------------------------------------------------------------------- |
|
1205 | 1205 | # module testing (minimal) |
|
1206 | 1206 | if __name__ == "__main__": |
|
1207 | 1207 | def spam(c, (d, e)): |
|
1208 | 1208 | x = c + d |
|
1209 | 1209 | y = c * d |
|
1210 | 1210 | foo(x, y) |
|
1211 | 1211 | |
|
1212 | 1212 | def foo(a, b, bar=1): |
|
1213 | 1213 | eggs(a, b + bar) |
|
1214 | 1214 | |
|
1215 | 1215 | def eggs(f, g, z=globals()): |
|
1216 | 1216 | h = f + g |
|
1217 | 1217 | i = f - g |
|
1218 | 1218 | return h / i |
|
1219 | 1219 | |
|
1220 | 1220 | print '' |
|
1221 | 1221 | print '*** Before ***' |
|
1222 | 1222 | try: |
|
1223 | 1223 | print spam(1, (2, 3)) |
|
1224 | 1224 | except: |
|
1225 | 1225 | traceback.print_exc() |
|
1226 | 1226 | print '' |
|
1227 | 1227 | |
|
1228 | 1228 | handler = ColorTB() |
|
1229 | 1229 | print '*** ColorTB ***' |
|
1230 | 1230 | try: |
|
1231 | 1231 | print spam(1, (2, 3)) |
|
1232 | 1232 | except: |
|
1233 | 1233 | apply(handler, sys.exc_info() ) |
|
1234 | 1234 | print '' |
|
1235 | 1235 | |
|
1236 | 1236 | handler = VerboseTB() |
|
1237 | 1237 | print '*** VerboseTB ***' |
|
1238 | 1238 | try: |
|
1239 | 1239 | print spam(1, (2, 3)) |
|
1240 | 1240 | except: |
|
1241 | 1241 | apply(handler, sys.exc_info() ) |
|
1242 | 1242 | print '' |
|
1243 | 1243 |
@@ -1,575 +1,575 b'' | |||
|
1 | 1 | """Module for interactive demos using IPython. |
|
2 | 2 | |
|
3 | 3 | This module implements a few classes for running Python scripts interactively |
|
4 | 4 | in IPython for demonstrations. With very simple markup (a few tags in |
|
5 | 5 | comments), you can control points where the script stops executing and returns |
|
6 | 6 | control to IPython. |
|
7 | 7 | |
|
8 | 8 | |
|
9 | 9 | Provided classes |
|
10 | 10 | ================ |
|
11 | 11 | |
|
12 | 12 | The classes are (see their docstrings for further details): |
|
13 | 13 | |
|
14 | 14 | - Demo: pure python demos |
|
15 | 15 | |
|
16 | 16 | - IPythonDemo: demos with input to be processed by IPython as if it had been |
|
17 | 17 | typed interactively (so magics work, as well as any other special syntax you |
|
18 | 18 | may have added via input prefilters). |
|
19 | 19 | |
|
20 | 20 | - LineDemo: single-line version of the Demo class. These demos are executed |
|
21 | 21 | one line at a time, and require no markup. |
|
22 | 22 | |
|
23 | 23 | - IPythonLineDemo: IPython version of the LineDemo class (the demo is |
|
24 | 24 | executed a line at a time, but processed via IPython). |
|
25 | 25 | |
|
26 | 26 | - ClearMixin: mixin to make Demo classes with less visual clutter. It |
|
27 | 27 | declares an empty marquee and a pre_cmd that clears the screen before each |
|
28 | 28 | block (see Subclassing below). |
|
29 | 29 | |
|
30 | 30 | - ClearDemo, ClearIPDemo: mixin-enabled versions of the Demo and IPythonDemo |
|
31 | 31 | classes. |
|
32 | 32 | |
|
33 | 33 | |
|
34 | 34 | Subclassing |
|
35 | 35 | =========== |
|
36 | 36 | |
|
37 | 37 | The classes here all include a few methods meant to make customization by |
|
38 | 38 | subclassing more convenient. Their docstrings below have some more details: |
|
39 | 39 | |
|
40 | 40 | - marquee(): generates a marquee to provide visible on-screen markers at each |
|
41 | 41 | block start and end. |
|
42 | 42 | |
|
43 | 43 | - pre_cmd(): run right before the execution of each block. |
|
44 | 44 | |
|
45 | 45 | - post_cmd(): run right after the execution of each block. If the block |
|
46 | 46 | raises an exception, this is NOT called. |
|
47 | 47 | |
|
48 | 48 | |
|
49 | 49 | Operation |
|
50 | 50 | ========= |
|
51 | 51 | |
|
52 | 52 | The file is run in its own empty namespace (though you can pass it a string of |
|
53 | 53 | arguments as if in a command line environment, and it will see those as |
|
54 | 54 | sys.argv). But at each stop, the global IPython namespace is updated with the |
|
55 | 55 | current internal demo namespace, so you can work interactively with the data |
|
56 | 56 | accumulated so far. |
|
57 | 57 | |
|
58 | 58 | By default, each block of code is printed (with syntax highlighting) before |
|
59 | 59 | executing it and you have to confirm execution. This is intended to show the |
|
60 | 60 | code to an audience first so you can discuss it, and only proceed with |
|
61 | 61 | execution once you agree. There are a few tags which allow you to modify this |
|
62 | 62 | behavior. |
|
63 | 63 | |
|
64 | 64 | The supported tags are: |
|
65 | 65 | |
|
66 | 66 | # <demo> stop |
|
67 | 67 | |
|
68 | 68 | Defines block boundaries, the points where IPython stops execution of the |
|
69 | 69 | file and returns to the interactive prompt. |
|
70 | 70 | |
|
71 | 71 | You can optionally mark the stop tag with extra dashes before and after the |
|
72 | 72 | word 'stop', to help visually distinguish the blocks in a text editor: |
|
73 | 73 | |
|
74 | 74 | # <demo> --- stop --- |
|
75 | 75 | |
|
76 | 76 | |
|
77 | 77 | # <demo> silent |
|
78 | 78 | |
|
79 | 79 | Make a block execute silently (and hence automatically). Typically used in |
|
80 | 80 | cases where you have some boilerplate or initialization code which you need |
|
81 | 81 | executed but do not want to be seen in the demo. |
|
82 | 82 | |
|
83 | 83 | # <demo> auto |
|
84 | 84 | |
|
85 | 85 | Make a block execute automatically, but still being printed. Useful for |
|
86 | 86 | simple code which does not warrant discussion, since it avoids the extra |
|
87 | 87 | manual confirmation. |
|
88 | 88 | |
|
89 | 89 | # <demo> auto_all |
|
90 | 90 | |
|
91 | 91 | This tag can _only_ be in the first block, and if given it overrides the |
|
92 | 92 | individual auto tags to make the whole demo fully automatic (no block asks |
|
93 | 93 | for confirmation). It can also be given at creation time (or the attribute |
|
94 | 94 | set later) to override what's in the file. |
|
95 | 95 | |
|
96 | 96 | While _any_ python file can be run as a Demo instance, if there are no stop |
|
97 | 97 | tags the whole file will run in a single block (no different that calling |
|
98 | 98 | first %pycat and then %run). The minimal markup to make this useful is to |
|
99 | 99 | place a set of stop tags; the other tags are only there to let you fine-tune |
|
100 | 100 | the execution. |
|
101 | 101 | |
|
102 | 102 | This is probably best explained with the simple example file below. You can |
|
103 | 103 | copy this into a file named ex_demo.py, and try running it via: |
|
104 | 104 | |
|
105 | 105 | from IPython.demo import Demo |
|
106 | 106 | d = Demo('ex_demo.py') |
|
107 | 107 | d() <--- Call the d object (omit the parens if you have autocall set to 2). |
|
108 | 108 | |
|
109 | 109 | Each time you call the demo object, it runs the next block. The demo object |
|
110 | 110 | has a few useful methods for navigation, like again(), edit(), jump(), seek() |
|
111 | 111 | and back(). It can be reset for a new run via reset() or reloaded from disk |
|
112 | 112 | (in case you've edited the source) via reload(). See their docstrings below. |
|
113 | 113 | |
|
114 | 114 | Note: To make this simpler to explore, a file called "demo-exercizer.py" has |
|
115 | 115 | been added to the "docs/examples/core" directory. Just cd to this directory in |
|
116 | 116 | an IPython session, and type:: |
|
117 | 117 | |
|
118 | 118 | %run demo-exercizer.py |
|
119 | 119 | |
|
120 | 120 | and then follow the directions. |
|
121 | 121 | |
|
122 | 122 | Example |
|
123 | 123 | ======= |
|
124 | 124 | |
|
125 | 125 | The following is a very simple example of a valid demo file. |
|
126 | 126 | |
|
127 | 127 | #################### EXAMPLE DEMO <ex_demo.py> ############################### |
|
128 | 128 | '''A simple interactive demo to illustrate the use of IPython's Demo class.''' |
|
129 | 129 | |
|
130 | 130 | print 'Hello, welcome to an interactive IPython demo.' |
|
131 | 131 | |
|
132 | 132 | # The mark below defines a block boundary, which is a point where IPython will |
|
133 | 133 | # stop execution and return to the interactive prompt. The dashes are actually |
|
134 | 134 | # optional and used only as a visual aid to clearly separate blocks while |
|
135 | 135 | # editing the demo code. |
|
136 | 136 | # <demo> stop |
|
137 | 137 | |
|
138 | 138 | x = 1 |
|
139 | 139 | y = 2 |
|
140 | 140 | |
|
141 | 141 | # <demo> stop |
|
142 | 142 | |
|
143 | 143 | # the mark below makes this block as silent |
|
144 | 144 | # <demo> silent |
|
145 | 145 | |
|
146 | 146 | print 'This is a silent block, which gets executed but not printed.' |
|
147 | 147 | |
|
148 | 148 | # <demo> stop |
|
149 | 149 | # <demo> auto |
|
150 | 150 | print 'This is an automatic block.' |
|
151 | 151 | print 'It is executed without asking for confirmation, but printed.' |
|
152 | 152 | z = x+y |
|
153 | 153 | |
|
154 | 154 | print 'z=',x |
|
155 | 155 | |
|
156 | 156 | # <demo> stop |
|
157 | 157 | # This is just another normal block. |
|
158 | 158 | print 'z is now:', z |
|
159 | 159 | |
|
160 | 160 | print 'bye!' |
|
161 | 161 | ################### END EXAMPLE DEMO <ex_demo.py> ############################ |
|
162 | 162 | """ |
|
163 | 163 | |
|
164 | 164 | #***************************************************************************** |
|
165 | 165 | # Copyright (C) 2005-2006 Fernando Perez. <Fernando.Perez@colorado.edu> |
|
166 | 166 | # |
|
167 | 167 | # Distributed under the terms of the BSD License. The full license is in |
|
168 | 168 | # the file COPYING, distributed as part of this software. |
|
169 | 169 | # |
|
170 | 170 | #***************************************************************************** |
|
171 | 171 | |
|
172 | 172 | import exceptions |
|
173 | 173 | import os |
|
174 | 174 | import re |
|
175 | 175 | import shlex |
|
176 | 176 | import sys |
|
177 | 177 | |
|
178 | 178 | from IPython.utils.PyColorize import Parser |
|
179 | from IPython.utils import io | |
|
179 | 180 | from IPython.utils.io import file_read, file_readlines |
|
180 | import IPython.utils.io | |
|
181 | 181 | from IPython.utils.text import marquee |
|
182 | 182 | |
|
183 | 183 | __all__ = ['Demo','IPythonDemo','LineDemo','IPythonLineDemo','DemoError'] |
|
184 | 184 | |
|
185 | 185 | class DemoError(exceptions.Exception): pass |
|
186 | 186 | |
|
187 | 187 | def re_mark(mark): |
|
188 | 188 | return re.compile(r'^\s*#\s+<demo>\s+%s\s*$' % mark,re.MULTILINE) |
|
189 | 189 | |
|
190 | 190 | class Demo(object): |
|
191 | 191 | |
|
192 | 192 | re_stop = re_mark('-*\s?stop\s?-*') |
|
193 | 193 | re_silent = re_mark('silent') |
|
194 | 194 | re_auto = re_mark('auto') |
|
195 | 195 | re_auto_all = re_mark('auto_all') |
|
196 | 196 | |
|
197 | 197 | def __init__(self,src,title='',arg_str='',auto_all=None): |
|
198 | 198 | """Make a new demo object. To run the demo, simply call the object. |
|
199 | 199 | |
|
200 | 200 | See the module docstring for full details and an example (you can use |
|
201 | 201 | IPython.Demo? in IPython to see it). |
|
202 | 202 | |
|
203 | 203 | Inputs: |
|
204 | 204 | |
|
205 | 205 | - src is either a file, or file-like object, or a |
|
206 | 206 | string that can be resolved to a filename. |
|
207 | 207 | |
|
208 | 208 | Optional inputs: |
|
209 | 209 | |
|
210 | 210 | - title: a string to use as the demo name. Of most use when the demo |
|
211 | 211 | you are making comes from an object that has no filename, or if you |
|
212 | 212 | want an alternate denotation distinct from the filename. |
|
213 | 213 | |
|
214 | 214 | - arg_str(''): a string of arguments, internally converted to a list |
|
215 | 215 | just like sys.argv, so the demo script can see a similar |
|
216 | 216 | environment. |
|
217 | 217 | |
|
218 | 218 | - auto_all(None): global flag to run all blocks automatically without |
|
219 | 219 | confirmation. This attribute overrides the block-level tags and |
|
220 | 220 | applies to the whole demo. It is an attribute of the object, and |
|
221 | 221 | can be changed at runtime simply by reassigning it to a boolean |
|
222 | 222 | value. |
|
223 | 223 | """ |
|
224 | 224 | if hasattr(src, "read"): |
|
225 | 225 | # It seems to be a file or a file-like object |
|
226 | 226 | self.fname = "from a file-like object" |
|
227 | 227 | if title == '': |
|
228 | 228 | self.title = "from a file-like object" |
|
229 | 229 | else: |
|
230 | 230 | self.title = title |
|
231 | 231 | else: |
|
232 | 232 | # Assume it's a string or something that can be converted to one |
|
233 | 233 | self.fname = src |
|
234 | 234 | if title == '': |
|
235 | 235 | (filepath, filename) = os.path.split(src) |
|
236 | 236 | self.title = filename |
|
237 | 237 | else: |
|
238 | 238 | self.title = title |
|
239 | 239 | self.sys_argv = [src] + shlex.split(arg_str) |
|
240 | 240 | self.auto_all = auto_all |
|
241 | 241 | self.src = src |
|
242 | 242 | |
|
243 | 243 | # get a few things from ipython. While it's a bit ugly design-wise, |
|
244 | 244 | # it ensures that things like color scheme and the like are always in |
|
245 | 245 | # sync with the ipython mode being used. This class is only meant to |
|
246 | 246 | # be used inside ipython anyways, so it's OK. |
|
247 | 247 | ip = get_ipython() # this is in builtins whenever IPython is running |
|
248 | 248 | self.ip_ns = ip.user_ns |
|
249 | 249 | self.ip_colorize = ip.pycolorize |
|
250 | 250 | self.ip_showtb = ip.showtraceback |
|
251 | 251 | self.ip_run_cell = ip.run_cell |
|
252 | 252 | self.shell = ip |
|
253 | 253 | |
|
254 | 254 | # load user data and initialize data structures |
|
255 | 255 | self.reload() |
|
256 | 256 | |
|
257 | 257 | def fload(self): |
|
258 | 258 | """Load file object.""" |
|
259 | 259 | # read data and parse into blocks |
|
260 | 260 | if hasattr(self, 'fobj') and self.fobj is not None: |
|
261 | 261 | self.fobj.close() |
|
262 | 262 | if hasattr(self.src, "read"): |
|
263 | 263 | # It seems to be a file or a file-like object |
|
264 | 264 | self.fobj = self.src |
|
265 | 265 | else: |
|
266 | 266 | # Assume it's a string or something that can be converted to one |
|
267 | 267 | self.fobj = open(self.fname) |
|
268 | 268 | |
|
269 | 269 | def reload(self): |
|
270 | 270 | """Reload source from disk and initialize state.""" |
|
271 | 271 | self.fload() |
|
272 | 272 | |
|
273 | 273 | self.src = self.fobj.read() |
|
274 | 274 | src_b = [b.strip() for b in self.re_stop.split(self.src) if b] |
|
275 | 275 | self._silent = [bool(self.re_silent.findall(b)) for b in src_b] |
|
276 | 276 | self._auto = [bool(self.re_auto.findall(b)) for b in src_b] |
|
277 | 277 | |
|
278 | 278 | # if auto_all is not given (def. None), we read it from the file |
|
279 | 279 | if self.auto_all is None: |
|
280 | 280 | self.auto_all = bool(self.re_auto_all.findall(src_b[0])) |
|
281 | 281 | else: |
|
282 | 282 | self.auto_all = bool(self.auto_all) |
|
283 | 283 | |
|
284 | 284 | # Clean the sources from all markup so it doesn't get displayed when |
|
285 | 285 | # running the demo |
|
286 | 286 | src_blocks = [] |
|
287 | 287 | auto_strip = lambda s: self.re_auto.sub('',s) |
|
288 | 288 | for i,b in enumerate(src_b): |
|
289 | 289 | if self._auto[i]: |
|
290 | 290 | src_blocks.append(auto_strip(b)) |
|
291 | 291 | else: |
|
292 | 292 | src_blocks.append(b) |
|
293 | 293 | # remove the auto_all marker |
|
294 | 294 | src_blocks[0] = self.re_auto_all.sub('',src_blocks[0]) |
|
295 | 295 | |
|
296 | 296 | self.nblocks = len(src_blocks) |
|
297 | 297 | self.src_blocks = src_blocks |
|
298 | 298 | |
|
299 | 299 | # also build syntax-highlighted source |
|
300 | 300 | self.src_blocks_colored = map(self.ip_colorize,self.src_blocks) |
|
301 | 301 | |
|
302 | 302 | # ensure clean namespace and seek offset |
|
303 | 303 | self.reset() |
|
304 | 304 | |
|
305 | 305 | def reset(self): |
|
306 | 306 | """Reset the namespace and seek pointer to restart the demo""" |
|
307 | 307 | self.user_ns = {} |
|
308 | 308 | self.finished = False |
|
309 | 309 | self.block_index = 0 |
|
310 | 310 | |
|
311 | 311 | def _validate_index(self,index): |
|
312 | 312 | if index<0 or index>=self.nblocks: |
|
313 | 313 | raise ValueError('invalid block index %s' % index) |
|
314 | 314 | |
|
315 | 315 | def _get_index(self,index): |
|
316 | 316 | """Get the current block index, validating and checking status. |
|
317 | 317 | |
|
318 | 318 | Returns None if the demo is finished""" |
|
319 | 319 | |
|
320 | 320 | if index is None: |
|
321 | 321 | if self.finished: |
|
322 |
print >> |
|
|
322 | print >>io.stdout, 'Demo finished. Use <demo_name>.reset() if you want to rerun it.' | |
|
323 | 323 | return None |
|
324 | 324 | index = self.block_index |
|
325 | 325 | else: |
|
326 | 326 | self._validate_index(index) |
|
327 | 327 | return index |
|
328 | 328 | |
|
329 | 329 | def seek(self,index): |
|
330 | 330 | """Move the current seek pointer to the given block. |
|
331 | 331 | |
|
332 | 332 | You can use negative indices to seek from the end, with identical |
|
333 | 333 | semantics to those of Python lists.""" |
|
334 | 334 | if index<0: |
|
335 | 335 | index = self.nblocks + index |
|
336 | 336 | self._validate_index(index) |
|
337 | 337 | self.block_index = index |
|
338 | 338 | self.finished = False |
|
339 | 339 | |
|
340 | 340 | def back(self,num=1): |
|
341 | 341 | """Move the seek pointer back num blocks (default is 1).""" |
|
342 | 342 | self.seek(self.block_index-num) |
|
343 | 343 | |
|
344 | 344 | def jump(self,num=1): |
|
345 | 345 | """Jump a given number of blocks relative to the current one. |
|
346 | 346 | |
|
347 | 347 | The offset can be positive or negative, defaults to 1.""" |
|
348 | 348 | self.seek(self.block_index+num) |
|
349 | 349 | |
|
350 | 350 | def again(self): |
|
351 | 351 | """Move the seek pointer back one block and re-execute.""" |
|
352 | 352 | self.back(1) |
|
353 | 353 | self() |
|
354 | 354 | |
|
355 | 355 | def edit(self,index=None): |
|
356 | 356 | """Edit a block. |
|
357 | 357 | |
|
358 | 358 | If no number is given, use the last block executed. |
|
359 | 359 | |
|
360 | 360 | This edits the in-memory copy of the demo, it does NOT modify the |
|
361 | 361 | original source file. If you want to do that, simply open the file in |
|
362 | 362 | an editor and use reload() when you make changes to the file. This |
|
363 | 363 | method is meant to let you change a block during a demonstration for |
|
364 | 364 | explanatory purposes, without damaging your original script.""" |
|
365 | 365 | |
|
366 | 366 | index = self._get_index(index) |
|
367 | 367 | if index is None: |
|
368 | 368 | return |
|
369 | 369 | # decrease the index by one (unless we're at the very beginning), so |
|
370 | 370 | # that the default demo.edit() call opens up the sblock we've last run |
|
371 | 371 | if index>0: |
|
372 | 372 | index -= 1 |
|
373 | 373 | |
|
374 | 374 | filename = self.shell.mktempfile(self.src_blocks[index]) |
|
375 | 375 | self.shell.hooks.editor(filename,1) |
|
376 | 376 | new_block = file_read(filename) |
|
377 | 377 | # update the source and colored block |
|
378 | 378 | self.src_blocks[index] = new_block |
|
379 | 379 | self.src_blocks_colored[index] = self.ip_colorize(new_block) |
|
380 | 380 | self.block_index = index |
|
381 | 381 | # call to run with the newly edited index |
|
382 | 382 | self() |
|
383 | 383 | |
|
384 | 384 | def show(self,index=None): |
|
385 | 385 | """Show a single block on screen""" |
|
386 | 386 | |
|
387 | 387 | index = self._get_index(index) |
|
388 | 388 | if index is None: |
|
389 | 389 | return |
|
390 | 390 | |
|
391 |
print >> |
|
|
391 | print >>io.stdout, self.marquee('<%s> block # %s (%s remaining)' % | |
|
392 | 392 | (self.title,index,self.nblocks-index-1)) |
|
393 |
print >> |
|
|
393 | print >>io.stdout,(self.src_blocks_colored[index]) | |
|
394 | 394 | sys.stdout.flush() |
|
395 | 395 | |
|
396 | 396 | def show_all(self): |
|
397 | 397 | """Show entire demo on screen, block by block""" |
|
398 | 398 | |
|
399 | 399 | fname = self.title |
|
400 | 400 | title = self.title |
|
401 | 401 | nblocks = self.nblocks |
|
402 | 402 | silent = self._silent |
|
403 | 403 | marquee = self.marquee |
|
404 | 404 | for index,block in enumerate(self.src_blocks_colored): |
|
405 | 405 | if silent[index]: |
|
406 |
print >> |
|
|
406 | print >>io.stdout, marquee('<%s> SILENT block # %s (%s remaining)' % | |
|
407 | 407 | (title,index,nblocks-index-1)) |
|
408 | 408 | else: |
|
409 |
print >> |
|
|
409 | print >>io.stdout, marquee('<%s> block # %s (%s remaining)' % | |
|
410 | 410 | (title,index,nblocks-index-1)) |
|
411 |
print >> |
|
|
411 | print >>io.stdout, block, | |
|
412 | 412 | sys.stdout.flush() |
|
413 | 413 | |
|
414 | 414 | def run_cell(self,source): |
|
415 | 415 | """Execute a string with one or more lines of code""" |
|
416 | 416 | |
|
417 | 417 | exec source in self.user_ns |
|
418 | 418 | |
|
419 | 419 | def __call__(self,index=None): |
|
420 | 420 | """run a block of the demo. |
|
421 | 421 | |
|
422 | 422 | If index is given, it should be an integer >=1 and <= nblocks. This |
|
423 | 423 | means that the calling convention is one off from typical Python |
|
424 | 424 | lists. The reason for the inconsistency is that the demo always |
|
425 | 425 | prints 'Block n/N, and N is the total, so it would be very odd to use |
|
426 | 426 | zero-indexing here.""" |
|
427 | 427 | |
|
428 | 428 | index = self._get_index(index) |
|
429 | 429 | if index is None: |
|
430 | 430 | return |
|
431 | 431 | try: |
|
432 | 432 | marquee = self.marquee |
|
433 | 433 | next_block = self.src_blocks[index] |
|
434 | 434 | self.block_index += 1 |
|
435 | 435 | if self._silent[index]: |
|
436 |
print >> |
|
|
436 | print >>io.stdout, marquee('Executing silent block # %s (%s remaining)' % | |
|
437 | 437 | (index,self.nblocks-index-1)) |
|
438 | 438 | else: |
|
439 | 439 | self.pre_cmd() |
|
440 | 440 | self.show(index) |
|
441 | 441 | if self.auto_all or self._auto[index]: |
|
442 |
print >> |
|
|
442 | print >>io.stdout, marquee('output:') | |
|
443 | 443 | else: |
|
444 |
print >> |
|
|
444 | print >>io.stdout, marquee('Press <q> to quit, <Enter> to execute...'), | |
|
445 | 445 | ans = raw_input().strip() |
|
446 | 446 | if ans: |
|
447 |
print >> |
|
|
447 | print >>io.stdout, marquee('Block NOT executed') | |
|
448 | 448 | return |
|
449 | 449 | try: |
|
450 | 450 | save_argv = sys.argv |
|
451 | 451 | sys.argv = self.sys_argv |
|
452 | 452 | self.run_cell(next_block) |
|
453 | 453 | self.post_cmd() |
|
454 | 454 | finally: |
|
455 | 455 | sys.argv = save_argv |
|
456 | 456 | |
|
457 | 457 | except: |
|
458 | 458 | self.ip_showtb(filename=self.fname) |
|
459 | 459 | else: |
|
460 | 460 | self.ip_ns.update(self.user_ns) |
|
461 | 461 | |
|
462 | 462 | if self.block_index == self.nblocks: |
|
463 | 463 | mq1 = self.marquee('END OF DEMO') |
|
464 | 464 | if mq1: |
|
465 |
# avoid spurious print >> |
|
|
466 |
print >> |
|
|
467 |
print >> |
|
|
468 |
print >> |
|
|
465 | # avoid spurious print >>io.stdout,s if empty marquees are used | |
|
466 | print >>io.stdout | |
|
467 | print >>io.stdout, mq1 | |
|
468 | print >>io.stdout, self.marquee('Use <demo_name>.reset() if you want to rerun it.') | |
|
469 | 469 | self.finished = True |
|
470 | 470 | |
|
471 | 471 | # These methods are meant to be overridden by subclasses who may wish to |
|
472 | 472 | # customize the behavior of of their demos. |
|
473 | 473 | def marquee(self,txt='',width=78,mark='*'): |
|
474 | 474 | """Return the input string centered in a 'marquee'.""" |
|
475 | 475 | return marquee(txt,width,mark) |
|
476 | 476 | |
|
477 | 477 | def pre_cmd(self): |
|
478 | 478 | """Method called before executing each block.""" |
|
479 | 479 | pass |
|
480 | 480 | |
|
481 | 481 | def post_cmd(self): |
|
482 | 482 | """Method called after executing each block.""" |
|
483 | 483 | pass |
|
484 | 484 | |
|
485 | 485 | |
|
486 | 486 | class IPythonDemo(Demo): |
|
487 | 487 | """Class for interactive demos with IPython's input processing applied. |
|
488 | 488 | |
|
489 | 489 | This subclasses Demo, but instead of executing each block by the Python |
|
490 | 490 | interpreter (via exec), it actually calls IPython on it, so that any input |
|
491 | 491 | filters which may be in place are applied to the input block. |
|
492 | 492 | |
|
493 | 493 | If you have an interactive environment which exposes special input |
|
494 | 494 | processing, you can use this class instead to write demo scripts which |
|
495 | 495 | operate exactly as if you had typed them interactively. The default Demo |
|
496 | 496 | class requires the input to be valid, pure Python code. |
|
497 | 497 | """ |
|
498 | 498 | |
|
499 | 499 | def run_cell(self,source): |
|
500 | 500 | """Execute a string with one or more lines of code""" |
|
501 | 501 | |
|
502 | 502 | self.shell.run_cell(source) |
|
503 | 503 | |
|
504 | 504 | class LineDemo(Demo): |
|
505 | 505 | """Demo where each line is executed as a separate block. |
|
506 | 506 | |
|
507 | 507 | The input script should be valid Python code. |
|
508 | 508 | |
|
509 | 509 | This class doesn't require any markup at all, and it's meant for simple |
|
510 | 510 | scripts (with no nesting or any kind of indentation) which consist of |
|
511 | 511 | multiple lines of input to be executed, one at a time, as if they had been |
|
512 | 512 | typed in the interactive prompt. |
|
513 | 513 | |
|
514 | 514 | Note: the input can not have *any* indentation, which means that only |
|
515 | 515 | single-lines of input are accepted, not even function definitions are |
|
516 | 516 | valid.""" |
|
517 | 517 | |
|
518 | 518 | def reload(self): |
|
519 | 519 | """Reload source from disk and initialize state.""" |
|
520 | 520 | # read data and parse into blocks |
|
521 | 521 | self.fload() |
|
522 | 522 | lines = self.fobj.readlines() |
|
523 | 523 | src_b = [l for l in lines if l.strip()] |
|
524 | 524 | nblocks = len(src_b) |
|
525 | 525 | self.src = ''.join(lines) |
|
526 | 526 | self._silent = [False]*nblocks |
|
527 | 527 | self._auto = [True]*nblocks |
|
528 | 528 | self.auto_all = True |
|
529 | 529 | self.nblocks = nblocks |
|
530 | 530 | self.src_blocks = src_b |
|
531 | 531 | |
|
532 | 532 | # also build syntax-highlighted source |
|
533 | 533 | self.src_blocks_colored = map(self.ip_colorize,self.src_blocks) |
|
534 | 534 | |
|
535 | 535 | # ensure clean namespace and seek offset |
|
536 | 536 | self.reset() |
|
537 | 537 | |
|
538 | 538 | |
|
539 | 539 | class IPythonLineDemo(IPythonDemo,LineDemo): |
|
540 | 540 | """Variant of the LineDemo class whose input is processed by IPython.""" |
|
541 | 541 | pass |
|
542 | 542 | |
|
543 | 543 | |
|
544 | 544 | class ClearMixin(object): |
|
545 | 545 | """Use this mixin to make Demo classes with less visual clutter. |
|
546 | 546 | |
|
547 | 547 | Demos using this mixin will clear the screen before every block and use |
|
548 | 548 | blank marquees. |
|
549 | 549 | |
|
550 | 550 | Note that in order for the methods defined here to actually override those |
|
551 | 551 | of the classes it's mixed with, it must go /first/ in the inheritance |
|
552 | 552 | tree. For example: |
|
553 | 553 | |
|
554 | 554 | class ClearIPDemo(ClearMixin,IPythonDemo): pass |
|
555 | 555 | |
|
556 | 556 | will provide an IPythonDemo class with the mixin's features. |
|
557 | 557 | """ |
|
558 | 558 | |
|
559 | 559 | def marquee(self,txt='',width=78,mark='*'): |
|
560 | 560 | """Blank marquee that returns '' no matter what the input.""" |
|
561 | 561 | return '' |
|
562 | 562 | |
|
563 | 563 | def pre_cmd(self): |
|
564 | 564 | """Method called before executing each block. |
|
565 | 565 | |
|
566 | 566 | This one simply clears the screen.""" |
|
567 | 567 | from IPython.utils.terminal import term_clear |
|
568 | 568 | term_clear() |
|
569 | 569 | |
|
570 | 570 | class ClearDemo(ClearMixin,Demo): |
|
571 | 571 | pass |
|
572 | 572 | |
|
573 | 573 | |
|
574 | 574 | class ClearIPDemo(ClearMixin,IPythonDemo): |
|
575 | 575 | pass |
@@ -1,299 +1,322 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | IO related utilities. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2008-2009 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 | from __future__ import print_function |
|
13 | 13 | |
|
14 | 14 | #----------------------------------------------------------------------------- |
|
15 | 15 | # Imports |
|
16 | 16 | #----------------------------------------------------------------------------- |
|
17 | 17 | import sys |
|
18 | 18 | import tempfile |
|
19 | 19 | |
|
20 | 20 | from IPython.external.Itpl import itpl, printpl |
|
21 | 21 | |
|
22 | 22 | #----------------------------------------------------------------------------- |
|
23 | 23 | # Code |
|
24 | 24 | #----------------------------------------------------------------------------- |
|
25 | 25 | |
|
26 | 26 | |
|
27 | 27 | class IOStream: |
|
28 | 28 | |
|
29 | def __init__(self,stream,fallback): | |
|
29 | def __init__(self,stream, fallback=None): | |
|
30 | 30 | if not hasattr(stream,'write') or not hasattr(stream,'flush'): |
|
31 | if fallback is not None: | |
|
31 | 32 | stream = fallback |
|
33 | else: | |
|
34 | raise ValueError("fallback required, but not specified") | |
|
32 | 35 | self.stream = stream |
|
33 | 36 | self._swrite = stream.write |
|
34 | self.flush = stream.flush | |
|
37 | ||
|
38 | # clone all methods not overridden: | |
|
39 | def clone(meth): | |
|
40 | return not hasattr(self, meth) and not meth.startswith('_') | |
|
41 | for meth in filter(clone, dir(stream)): | |
|
42 | setattr(self, meth, getattr(stream, meth)) | |
|
35 | 43 | |
|
36 | 44 | def write(self,data): |
|
37 | 45 | try: |
|
38 | 46 | self._swrite(data) |
|
39 | 47 | except: |
|
40 | 48 | try: |
|
41 | 49 | # print handles some unicode issues which may trip a plain |
|
42 | 50 | # write() call. Emulate write() by using an empty end |
|
43 | 51 | # argument. |
|
44 | 52 | print(data, end='', file=self.stream) |
|
45 | 53 | except: |
|
46 | 54 | # if we get here, something is seriously broken. |
|
47 | 55 | print('ERROR - failed to write data to stream:', self.stream, |
|
48 | 56 | file=sys.stderr) |
|
49 | 57 | |
|
58 | def writelines(self, lines): | |
|
59 | if isinstance(lines, basestring): | |
|
60 | lines = [lines] | |
|
61 | for line in lines: | |
|
62 | self.write(line) | |
|
63 | ||
|
50 | 64 | # This class used to have a writeln method, but regular files and streams |
|
51 | 65 | # in Python don't have this method. We need to keep this completely |
|
52 | 66 | # compatible so we removed it. |
|
53 | 67 | |
|
68 | @property | |
|
69 | def closed(self): | |
|
70 | return self.stream.closed | |
|
71 | ||
|
54 | 72 | def close(self): |
|
55 | 73 | pass |
|
56 | 74 | |
|
57 | 75 | |
|
58 | 76 | class IOTerm: |
|
59 | 77 | """ Term holds the file or file-like objects for handling I/O operations. |
|
60 | 78 | |
|
61 | 79 | These are normally just sys.stdin, sys.stdout and sys.stderr but for |
|
62 | 80 | Windows they can can replaced to allow editing the strings before they are |
|
63 | 81 | displayed.""" |
|
64 | 82 | |
|
65 | 83 | # In the future, having IPython channel all its I/O operations through |
|
66 | 84 | # this class will make it easier to embed it into other environments which |
|
67 | 85 | # are not a normal terminal (such as a GUI-based shell) |
|
68 |
def __init__(self, |
|
|
69 |
self. |
|
|
70 |
self. |
|
|
71 |
self. |
|
|
86 | def __init__(self, stdin=None, stdout=None, stderr=None): | |
|
87 | self.stdin = IOStream(stdin, sys.stdin) | |
|
88 | self.stdout = IOStream(stdout, sys.stdout) | |
|
89 | self.stderr = IOStream(stderr, sys.stderr) | |
|
90 | ||
|
91 | # setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr | |
|
92 | stdin = IOStream(sys.stdin) | |
|
93 | stdout = IOStream(sys.stdout) | |
|
94 | stderr = IOStream(sys.stderr) | |
|
72 | 95 | |
|
73 | 96 | |
|
74 | 97 | class Tee(object): |
|
75 | 98 | """A class to duplicate an output stream to stdout/err. |
|
76 | 99 | |
|
77 | 100 | This works in a manner very similar to the Unix 'tee' command. |
|
78 | 101 | |
|
79 | 102 | When the object is closed or deleted, it closes the original file given to |
|
80 | 103 | it for duplication. |
|
81 | 104 | """ |
|
82 | 105 | # Inspired by: |
|
83 | 106 | # http://mail.python.org/pipermail/python-list/2007-May/442737.html |
|
84 | 107 | |
|
85 | 108 | def __init__(self, file_or_name, mode=None, channel='stdout'): |
|
86 | 109 | """Construct a new Tee object. |
|
87 | 110 | |
|
88 | 111 | Parameters |
|
89 | 112 | ---------- |
|
90 | 113 | file_or_name : filename or open filehandle (writable) |
|
91 | 114 | File that will be duplicated |
|
92 | 115 | |
|
93 | 116 | mode : optional, valid mode for open(). |
|
94 | 117 | If a filename was give, open with this mode. |
|
95 | 118 | |
|
96 | 119 | channel : str, one of ['stdout', 'stderr'] |
|
97 | 120 | """ |
|
98 | 121 | if channel not in ['stdout', 'stderr']: |
|
99 | 122 | raise ValueError('Invalid channel spec %s' % channel) |
|
100 | 123 | |
|
101 | 124 | if hasattr(file, 'write') and hasattr(file, 'seek'): |
|
102 | 125 | self.file = file_or_name |
|
103 | 126 | else: |
|
104 | 127 | self.file = open(file_or_name, mode) |
|
105 | 128 | self.channel = channel |
|
106 | 129 | self.ostream = getattr(sys, channel) |
|
107 | 130 | setattr(sys, channel, self) |
|
108 | 131 | self._closed = False |
|
109 | 132 | |
|
110 | 133 | def close(self): |
|
111 | 134 | """Close the file and restore the channel.""" |
|
112 | 135 | self.flush() |
|
113 | 136 | setattr(sys, self.channel, self.ostream) |
|
114 | 137 | self.file.close() |
|
115 | 138 | self._closed = True |
|
116 | 139 | |
|
117 | 140 | def write(self, data): |
|
118 | 141 | """Write data to both channels.""" |
|
119 | 142 | self.file.write(data) |
|
120 | 143 | self.ostream.write(data) |
|
121 | 144 | self.ostream.flush() |
|
122 | 145 | |
|
123 | 146 | def flush(self): |
|
124 | 147 | """Flush both channels.""" |
|
125 | 148 | self.file.flush() |
|
126 | 149 | self.ostream.flush() |
|
127 | 150 | |
|
128 | 151 | def __del__(self): |
|
129 | 152 | if not self._closed: |
|
130 | 153 | self.close() |
|
131 | 154 | |
|
132 | 155 | |
|
133 | 156 | def file_read(filename): |
|
134 | 157 | """Read a file and close it. Returns the file source.""" |
|
135 | 158 | fobj = open(filename,'r'); |
|
136 | 159 | source = fobj.read(); |
|
137 | 160 | fobj.close() |
|
138 | 161 | return source |
|
139 | 162 | |
|
140 | 163 | |
|
141 | 164 | def file_readlines(filename): |
|
142 | 165 | """Read a file and close it. Returns the file source using readlines().""" |
|
143 | 166 | fobj = open(filename,'r'); |
|
144 | 167 | lines = fobj.readlines(); |
|
145 | 168 | fobj.close() |
|
146 | 169 | return lines |
|
147 | 170 | |
|
148 | 171 | |
|
149 | 172 | def raw_input_multi(header='', ps1='==> ', ps2='..> ',terminate_str = '.'): |
|
150 | 173 | """Take multiple lines of input. |
|
151 | 174 | |
|
152 | 175 | A list with each line of input as a separate element is returned when a |
|
153 | 176 | termination string is entered (defaults to a single '.'). Input can also |
|
154 | 177 | terminate via EOF (^D in Unix, ^Z-RET in Windows). |
|
155 | 178 | |
|
156 | 179 | Lines of input which end in \\ are joined into single entries (and a |
|
157 | 180 | secondary continuation prompt is issued as long as the user terminates |
|
158 | 181 | lines with \\). This allows entering very long strings which are still |
|
159 | 182 | meant to be treated as single entities. |
|
160 | 183 | """ |
|
161 | 184 | |
|
162 | 185 | try: |
|
163 | 186 | if header: |
|
164 | 187 | header += '\n' |
|
165 | 188 | lines = [raw_input(header + ps1)] |
|
166 | 189 | except EOFError: |
|
167 | 190 | return [] |
|
168 | 191 | terminate = [terminate_str] |
|
169 | 192 | try: |
|
170 | 193 | while lines[-1:] != terminate: |
|
171 | 194 | new_line = raw_input(ps1) |
|
172 | 195 | while new_line.endswith('\\'): |
|
173 | 196 | new_line = new_line[:-1] + raw_input(ps2) |
|
174 | 197 | lines.append(new_line) |
|
175 | 198 | |
|
176 | 199 | return lines[:-1] # don't return the termination command |
|
177 | 200 | except EOFError: |
|
178 | 201 | |
|
179 | 202 | return lines |
|
180 | 203 | |
|
181 | 204 | |
|
182 | 205 | def raw_input_ext(prompt='', ps2='... '): |
|
183 | 206 | """Similar to raw_input(), but accepts extended lines if input ends with \\.""" |
|
184 | 207 | |
|
185 | 208 | line = raw_input(prompt) |
|
186 | 209 | while line.endswith('\\'): |
|
187 | 210 | line = line[:-1] + raw_input(ps2) |
|
188 | 211 | return line |
|
189 | 212 | |
|
190 | 213 | |
|
191 | 214 | def ask_yes_no(prompt,default=None): |
|
192 | 215 | """Asks a question and returns a boolean (y/n) answer. |
|
193 | 216 | |
|
194 | 217 | If default is given (one of 'y','n'), it is used if the user input is |
|
195 | 218 | empty. Otherwise the question is repeated until an answer is given. |
|
196 | 219 | |
|
197 | 220 | An EOF is treated as the default answer. If there is no default, an |
|
198 | 221 | exception is raised to prevent infinite loops. |
|
199 | 222 | |
|
200 | 223 | Valid answers are: y/yes/n/no (match is not case sensitive).""" |
|
201 | 224 | |
|
202 | 225 | answers = {'y':True,'n':False,'yes':True,'no':False} |
|
203 | 226 | ans = None |
|
204 | 227 | while ans not in answers.keys(): |
|
205 | 228 | try: |
|
206 | 229 | ans = raw_input(prompt+' ').lower() |
|
207 | 230 | if not ans: # response was an empty string |
|
208 | 231 | ans = default |
|
209 | 232 | except KeyboardInterrupt: |
|
210 | 233 | pass |
|
211 | 234 | except EOFError: |
|
212 | 235 | if default in answers.keys(): |
|
213 | 236 | ans = default |
|
214 | 237 | |
|
215 | 238 | else: |
|
216 | 239 | raise |
|
217 | 240 | |
|
218 | 241 | return answers[ans] |
|
219 | 242 | |
|
220 | 243 | |
|
221 | 244 | class NLprinter: |
|
222 | 245 | """Print an arbitrarily nested list, indicating index numbers. |
|
223 | 246 | |
|
224 | 247 | An instance of this class called nlprint is available and callable as a |
|
225 | 248 | function. |
|
226 | 249 | |
|
227 | 250 | nlprint(list,indent=' ',sep=': ') -> prints indenting each level by 'indent' |
|
228 | 251 | and using 'sep' to separate the index from the value. """ |
|
229 | 252 | |
|
230 | 253 | def __init__(self): |
|
231 | 254 | self.depth = 0 |
|
232 | 255 | |
|
233 | 256 | def __call__(self,lst,pos='',**kw): |
|
234 | 257 | """Prints the nested list numbering levels.""" |
|
235 | 258 | kw.setdefault('indent',' ') |
|
236 | 259 | kw.setdefault('sep',': ') |
|
237 | 260 | kw.setdefault('start',0) |
|
238 | 261 | kw.setdefault('stop',len(lst)) |
|
239 | 262 | # we need to remove start and stop from kw so they don't propagate |
|
240 | 263 | # into a recursive call for a nested list. |
|
241 | 264 | start = kw['start']; del kw['start'] |
|
242 | 265 | stop = kw['stop']; del kw['stop'] |
|
243 | 266 | if self.depth == 0 and 'header' in kw.keys(): |
|
244 | 267 | print(kw['header']) |
|
245 | 268 | |
|
246 | 269 | for idx in range(start,stop): |
|
247 | 270 | elem = lst[idx] |
|
248 | 271 | if type(elem)==type([]): |
|
249 | 272 | self.depth += 1 |
|
250 | 273 | self.__call__(elem,itpl('$pos$idx,'),**kw) |
|
251 | 274 | self.depth -= 1 |
|
252 | 275 | else: |
|
253 | 276 | printpl(kw['indent']*self.depth+'$pos$idx$kw["sep"]$elem') |
|
254 | 277 | |
|
255 | 278 | nlprint = NLprinter() |
|
256 | 279 | |
|
257 | 280 | |
|
258 | 281 | def temp_pyfile(src, ext='.py'): |
|
259 | 282 | """Make a temporary python file, return filename and filehandle. |
|
260 | 283 | |
|
261 | 284 | Parameters |
|
262 | 285 | ---------- |
|
263 | 286 | src : string or list of strings (no need for ending newlines if list) |
|
264 | 287 | Source code to be written to the file. |
|
265 | 288 | |
|
266 | 289 | ext : optional, string |
|
267 | 290 | Extension for the generated file. |
|
268 | 291 | |
|
269 | 292 | Returns |
|
270 | 293 | ------- |
|
271 | 294 | (filename, open filehandle) |
|
272 | 295 | It is the caller's responsibility to close the open file and unlink it. |
|
273 | 296 | """ |
|
274 | 297 | fname = tempfile.mkstemp(ext)[1] |
|
275 | 298 | f = open(fname,'w') |
|
276 | 299 | f.write(src) |
|
277 | 300 | f.flush() |
|
278 | 301 | return fname, f |
|
279 | 302 | |
|
280 | 303 | |
|
281 | 304 | def raw_print(*args, **kw): |
|
282 | 305 | """Raw print to sys.__stdout__, otherwise identical interface to print().""" |
|
283 | 306 | |
|
284 | 307 | print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'), |
|
285 | 308 | file=sys.__stdout__) |
|
286 | 309 | sys.__stdout__.flush() |
|
287 | 310 | |
|
288 | 311 | |
|
289 | 312 | def raw_print_err(*args, **kw): |
|
290 | 313 | """Raw print to sys.__stderr__, otherwise identical interface to print().""" |
|
291 | 314 | |
|
292 | 315 | print(*args, sep=kw.get('sep', ' '), end=kw.get('end', '\n'), |
|
293 | 316 | file=sys.__stderr__) |
|
294 | 317 | sys.__stderr__.flush() |
|
295 | 318 | |
|
296 | 319 | |
|
297 | 320 | # Short aliases for quick debugging, do NOT use these in production code. |
|
298 | 321 | rprint = raw_print |
|
299 | 322 | rprinte = raw_print_err |
@@ -1,61 +1,71 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """Tests for io.py""" |
|
3 | 3 | |
|
4 | 4 | #----------------------------------------------------------------------------- |
|
5 | 5 | # Copyright (C) 2008 The IPython Development Team |
|
6 | 6 | # |
|
7 | 7 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | 8 | # the file COPYING, distributed as part of this software. |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Imports |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | import sys |
|
16 | 16 | |
|
17 | 17 | from cStringIO import StringIO |
|
18 | from subprocess import Popen, PIPE | |
|
18 | 19 | |
|
19 | 20 | import nose.tools as nt |
|
20 | 21 | |
|
21 | 22 | from IPython.testing import decorators as dec |
|
22 | 23 | from IPython.utils.io import Tee |
|
23 | 24 | |
|
24 | 25 | #----------------------------------------------------------------------------- |
|
25 | 26 | # Tests |
|
26 | 27 | #----------------------------------------------------------------------------- |
|
27 | 28 | |
|
28 | 29 | |
|
29 | 30 | def test_tee_simple(): |
|
30 | 31 | "Very simple check with stdout only" |
|
31 | 32 | chan = StringIO() |
|
32 | 33 | text = 'Hello' |
|
33 | 34 | tee = Tee(chan, channel='stdout') |
|
34 | 35 | print >> chan, text, |
|
35 | 36 | nt.assert_equal(chan.getvalue(), text) |
|
36 | 37 | |
|
37 | 38 | |
|
38 | 39 | class TeeTestCase(dec.ParametricTestCase): |
|
39 | 40 | |
|
40 | 41 | def tchan(self, channel, check='close'): |
|
41 | 42 | trap = StringIO() |
|
42 | 43 | chan = StringIO() |
|
43 | 44 | text = 'Hello' |
|
44 | 45 | |
|
45 | 46 | std_ori = getattr(sys, channel) |
|
46 | 47 | setattr(sys, channel, trap) |
|
47 | 48 | |
|
48 | 49 | tee = Tee(chan, channel=channel) |
|
49 | 50 | print >> chan, text, |
|
50 | 51 | setattr(sys, channel, std_ori) |
|
51 | 52 | trap_val = trap.getvalue() |
|
52 | 53 | nt.assert_equals(chan.getvalue(), text) |
|
53 | 54 | if check=='close': |
|
54 | 55 | tee.close() |
|
55 | 56 | else: |
|
56 | 57 | del tee |
|
57 | 58 | |
|
58 | 59 | def test(self): |
|
59 | 60 | for chan in ['stdout', 'stderr']: |
|
60 | 61 | for check in ['close', 'del']: |
|
61 | 62 | yield self.tchan(chan, check) |
|
63 | ||
|
64 | def test_io_init(): | |
|
65 | """Test that io.stdin/out/err exist at startup""" | |
|
66 | for name in ('stdin', 'stdout', 'stderr'): | |
|
67 | p = Popen([sys.executable, '-c', "from IPython.utils import io;print io.%s.__class__"%name], | |
|
68 | stdout=PIPE) | |
|
69 | p.wait() | |
|
70 | classname = p.stdout.read().strip() | |
|
71 | nt.assert_equals(classname, 'IPython.utils.io.IOStream') |
@@ -1,66 +1,66 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | Utilities for warnings. Shoudn't we just use the built in warnings module. |
|
4 | 4 | """ |
|
5 | 5 | |
|
6 | 6 | #----------------------------------------------------------------------------- |
|
7 | 7 | # Copyright (C) 2008-2009 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 | #----------------------------------------------------------------------------- |
|
14 | 14 | # Imports |
|
15 | 15 | #----------------------------------------------------------------------------- |
|
16 | 16 | |
|
17 | 17 | import sys |
|
18 | 18 | |
|
19 |
|
|
|
19 | from IPython.utils import io | |
|
20 | 20 | |
|
21 | 21 | #----------------------------------------------------------------------------- |
|
22 | 22 | # Code |
|
23 | 23 | #----------------------------------------------------------------------------- |
|
24 | 24 | |
|
25 | 25 | def warn(msg,level=2,exit_val=1): |
|
26 | 26 | """Standard warning printer. Gives formatting consistency. |
|
27 | 27 | |
|
28 |
Output is sent to |
|
|
28 | Output is sent to io.stderr (sys.stderr by default). | |
|
29 | 29 | |
|
30 | 30 | Options: |
|
31 | 31 | |
|
32 | 32 | -level(2): allows finer control: |
|
33 | 33 | 0 -> Do nothing, dummy function. |
|
34 | 34 | 1 -> Print message. |
|
35 | 35 | 2 -> Print 'WARNING:' + message. (Default level). |
|
36 | 36 | 3 -> Print 'ERROR:' + message. |
|
37 | 37 | 4 -> Print 'FATAL ERROR:' + message and trigger a sys.exit(exit_val). |
|
38 | 38 | |
|
39 | 39 | -exit_val (1): exit value returned by sys.exit() for a level 4 |
|
40 | 40 | warning. Ignored for all other levels.""" |
|
41 | 41 | |
|
42 | 42 | if level>0: |
|
43 | 43 | header = ['','','WARNING: ','ERROR: ','FATAL ERROR: '] |
|
44 |
print >> |
|
|
44 | print >> io.stderr, '%s%s' % (header[level],msg) | |
|
45 | 45 | if level == 4: |
|
46 |
print >> |
|
|
46 | print >> io.stderr,'Exiting.\n' | |
|
47 | 47 | sys.exit(exit_val) |
|
48 | 48 | |
|
49 | 49 | |
|
50 | 50 | def info(msg): |
|
51 | 51 | """Equivalent to warn(msg,level=1).""" |
|
52 | 52 | |
|
53 | 53 | warn(msg,level=1) |
|
54 | 54 | |
|
55 | 55 | |
|
56 | 56 | def error(msg): |
|
57 | 57 | """Equivalent to warn(msg,level=3).""" |
|
58 | 58 | |
|
59 | 59 | warn(msg,level=3) |
|
60 | 60 | |
|
61 | 61 | |
|
62 | 62 | def fatal(msg,exit_val=1): |
|
63 | 63 | """Equivalent to warn(msg,exit_val=exit_val,level=4).""" |
|
64 | 64 | |
|
65 | 65 | warn(msg,exit_val=exit_val,level=4) |
|
66 | 66 |
General Comments 0
You need to be logged in to leave comments.
Login now