Show More
@@ -1,557 +1,557 b'' | |||
|
1 | 1 | # -*- coding: utf-8 -*- |
|
2 | 2 | """ |
|
3 | 3 | Pdb debugger class. |
|
4 | 4 | |
|
5 | 5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
6 | 6 | the command line completion of other programs which include this isn't |
|
7 | 7 | damaged. |
|
8 | 8 | |
|
9 | 9 | In the future, this class will be expanded with improvements over the standard |
|
10 | 10 | pdb. |
|
11 | 11 | |
|
12 | 12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
13 | 13 | changes. Licensing should therefore be under the standard Python terms. For |
|
14 | 14 | details on the PSF (Python Software Foundation) standard license, see: |
|
15 | 15 | |
|
16 | 16 | http://www.python.org/2.2.3/license.html""" |
|
17 | 17 | |
|
18 | 18 | #***************************************************************************** |
|
19 | 19 | # |
|
20 | 20 | # This file is licensed under the PSF license. |
|
21 | 21 | # |
|
22 | 22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
23 | 23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
24 | 24 | # |
|
25 | 25 | # |
|
26 | 26 | #***************************************************************************** |
|
27 | 27 | from __future__ import print_function |
|
28 | 28 | |
|
29 | 29 | import bdb |
|
30 | 30 | import linecache |
|
31 | 31 | import sys |
|
32 | 32 | |
|
33 | 33 | from IPython.utils import PyColorize, ulinecache |
|
34 | 34 | from IPython.core import ipapi |
|
35 | 35 | from IPython.utils import coloransi, io, openpy, py3compat |
|
36 | 36 | from IPython.core.excolors import exception_colors |
|
37 | 37 | |
|
38 | 38 | # See if we can use pydb. |
|
39 | 39 | has_pydb = False |
|
40 | 40 | prompt = 'ipdb> ' |
|
41 | 41 | #We have to check this directly from sys.argv, config struct not yet available |
|
42 | 42 | if '--pydb' in sys.argv: |
|
43 | 43 | try: |
|
44 | 44 | import pydb |
|
45 | 45 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': |
|
46 | 46 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we |
|
47 | 47 | # better protect against it. |
|
48 | 48 | has_pydb = True |
|
49 | 49 | except ImportError: |
|
50 | 50 | print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available") |
|
51 | 51 | |
|
52 | 52 | if has_pydb: |
|
53 | 53 | from pydb import Pdb as OldPdb |
|
54 | 54 | #print "Using pydb for %run -d and post-mortem" #dbg |
|
55 | 55 | prompt = 'ipydb> ' |
|
56 | 56 | else: |
|
57 | 57 | from pdb import Pdb as OldPdb |
|
58 | 58 | |
|
59 | 59 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
60 | 60 | # it does so with some limitations. The rest of this support is implemented in |
|
61 | 61 | # the Tracer constructor. |
|
62 | 62 | def BdbQuit_excepthook(et,ev,tb): |
|
63 | 63 | if et==bdb.BdbQuit: |
|
64 | 64 | print('Exiting Debugger.') |
|
65 | 65 | else: |
|
66 | 66 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
67 | 67 | |
|
68 | 68 | def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): |
|
69 | 69 | print('Exiting Debugger.') |
|
70 | 70 | |
|
71 | 71 | |
|
72 | 72 | class Tracer(object): |
|
73 | 73 | """Class for local debugging, similar to pdb.set_trace. |
|
74 | 74 | |
|
75 | 75 | Instances of this class, when called, behave like pdb.set_trace, but |
|
76 | 76 | providing IPython's enhanced capabilities. |
|
77 | 77 | |
|
78 | 78 | This is implemented as a class which must be initialized in your own code |
|
79 | 79 | and not as a standalone function because we need to detect at runtime |
|
80 | 80 | whether IPython is already active or not. That detection is done in the |
|
81 | 81 | constructor, ensuring that this code plays nicely with a running IPython, |
|
82 | 82 | while functioning acceptably (though with limitations) if outside of it. |
|
83 | 83 | """ |
|
84 | 84 | |
|
85 | 85 | def __init__(self,colors=None): |
|
86 | 86 | """Create a local debugger instance. |
|
87 | 87 | |
|
88 | 88 | :Parameters: |
|
89 | 89 | |
|
90 | 90 | - `colors` (None): a string containing the name of the color scheme to |
|
91 | 91 | use, it must be one of IPython's valid color schemes. If not given, the |
|
92 | 92 | function will default to the current IPython scheme when running inside |
|
93 | 93 | IPython, and to 'NoColor' otherwise. |
|
94 | 94 | |
|
95 | 95 | Usage example: |
|
96 | 96 | |
|
97 | 97 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
98 | 98 | |
|
99 | 99 | ... later in your code |
|
100 | 100 | debug_here() # -> will open up the debugger at that point. |
|
101 | 101 | |
|
102 | 102 | Once the debugger activates, you can use all of its regular commands to |
|
103 | 103 | step through code, set breakpoints, etc. See the pdb documentation |
|
104 | 104 | from the Python standard library for usage details. |
|
105 | 105 | """ |
|
106 | 106 | |
|
107 | 107 | try: |
|
108 | 108 | ip = get_ipython() |
|
109 | 109 | except NameError: |
|
110 | 110 | # Outside of ipython, we set our own exception hook manually |
|
111 | 111 | BdbQuit_excepthook.excepthook_ori = sys.excepthook |
|
112 | 112 | sys.excepthook = BdbQuit_excepthook |
|
113 | 113 | def_colors = 'NoColor' |
|
114 | 114 | try: |
|
115 | 115 | # Limited tab completion support |
|
116 | 116 | import readline |
|
117 | 117 | readline.parse_and_bind('tab: complete') |
|
118 | 118 | except ImportError: |
|
119 | 119 | pass |
|
120 | 120 | else: |
|
121 | 121 | # In ipython, we use its custom exception handler mechanism |
|
122 | 122 | def_colors = ip.colors |
|
123 | 123 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) |
|
124 | 124 | |
|
125 | 125 | if colors is None: |
|
126 | 126 | colors = def_colors |
|
127 | 127 | |
|
128 | 128 | # The stdlib debugger internally uses a modified repr from the `repr` |
|
129 | 129 | # module, that limits the length of printed strings to a hardcoded |
|
130 | 130 | # limit of 30 characters. That much trimming is too aggressive, let's |
|
131 | 131 | # at least raise that limit to 80 chars, which should be enough for |
|
132 | 132 | # most interactive uses. |
|
133 | 133 | try: |
|
134 | 134 | from repr import aRepr |
|
135 | 135 | aRepr.maxstring = 80 |
|
136 | 136 | except: |
|
137 | 137 | # This is only a user-facing convenience, so any error we encounter |
|
138 | 138 | # here can be warned about but can be otherwise ignored. These |
|
139 | 139 | # printouts will tell us about problems if this API changes |
|
140 | 140 | import traceback |
|
141 | 141 | traceback.print_exc() |
|
142 | 142 | |
|
143 | 143 | self.debugger = Pdb(colors) |
|
144 | 144 | |
|
145 | 145 | def __call__(self): |
|
146 | 146 | """Starts an interactive debugger at the point where called. |
|
147 | 147 | |
|
148 | 148 | This is similar to the pdb.set_trace() function from the std lib, but |
|
149 | 149 | using IPython's enhanced debugger.""" |
|
150 | 150 | |
|
151 | 151 | self.debugger.set_trace(sys._getframe().f_back) |
|
152 | 152 | |
|
153 | 153 | |
|
154 | 154 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
155 | 155 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
156 | 156 | for the do_... commands that hook into the help system. |
|
157 | 157 | Adapted from from a comp.lang.python posting |
|
158 | 158 | by Duncan Booth.""" |
|
159 | 159 | def wrapper(*args, **kw): |
|
160 | 160 | return new_fn(*args, **kw) |
|
161 | 161 | if old_fn.__doc__: |
|
162 | 162 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
163 | 163 | return wrapper |
|
164 | 164 | |
|
165 | 165 | |
|
166 | 166 | def _file_lines(fname): |
|
167 | 167 | """Return the contents of a named file as a list of lines. |
|
168 | 168 | |
|
169 | 169 | This function never raises an IOError exception: if the file can't be |
|
170 | 170 | read, it simply returns an empty list.""" |
|
171 | 171 | |
|
172 | 172 | try: |
|
173 | 173 | outfile = open(fname) |
|
174 | 174 | except IOError: |
|
175 | 175 | return [] |
|
176 | 176 | else: |
|
177 | 177 | out = outfile.readlines() |
|
178 | 178 | outfile.close() |
|
179 | 179 | return out |
|
180 | 180 | |
|
181 | 181 | |
|
182 | 182 | class Pdb(OldPdb): |
|
183 | 183 | """Modified Pdb class, does not load readline.""" |
|
184 | 184 | |
|
185 | 185 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
186 | 186 | stdin=None, stdout=None): |
|
187 | 187 | |
|
188 | 188 | # Parent constructor: |
|
189 | 189 | if has_pydb and completekey is None: |
|
190 | 190 | OldPdb.__init__(self,stdin=stdin,stdout=io.stdout) |
|
191 | 191 | else: |
|
192 | 192 | OldPdb.__init__(self,completekey,stdin,stdout) |
|
193 | 193 | |
|
194 | 194 | self.prompt = prompt # The default prompt is '(Pdb)' |
|
195 | 195 | |
|
196 | 196 | # IPython changes... |
|
197 | 197 | self.is_pydb = has_pydb |
|
198 | 198 | |
|
199 | 199 | self.shell = ipapi.get() |
|
200 | 200 | |
|
201 | 201 | if self.is_pydb: |
|
202 | 202 | |
|
203 | 203 | # interactiveshell.py's ipalias seems to want pdb's checkline |
|
204 | 204 | # which located in pydb.fn |
|
205 | 205 | import pydb.fns |
|
206 | 206 | self.checkline = lambda filename, lineno: \ |
|
207 | 207 | pydb.fns.checkline(self, filename, lineno) |
|
208 | 208 | |
|
209 | 209 | self.curframe = None |
|
210 | 210 | self.do_restart = self.new_do_restart |
|
211 | 211 | |
|
212 | 212 | self.old_all_completions = self.shell.Completer.all_completions |
|
213 | 213 | self.shell.Completer.all_completions=self.all_completions |
|
214 | 214 | |
|
215 | 215 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, |
|
216 | 216 | OldPdb.do_list) |
|
217 | 217 | self.do_l = self.do_list |
|
218 | 218 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, |
|
219 | 219 | OldPdb.do_frame) |
|
220 | 220 | |
|
221 | 221 | self.aliases = {} |
|
222 | 222 | |
|
223 | 223 | # Create color table: we copy the default one from the traceback |
|
224 | 224 | # module and add a few attributes needed for debugging |
|
225 | 225 | self.color_scheme_table = exception_colors() |
|
226 | 226 | |
|
227 | 227 | # shorthands |
|
228 | 228 | C = coloransi.TermColors |
|
229 | 229 | cst = self.color_scheme_table |
|
230 | 230 | |
|
231 | 231 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
232 | 232 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
233 | 233 | |
|
234 | 234 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
235 | 235 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
236 | 236 | |
|
237 | 237 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
238 | 238 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
239 | 239 | |
|
240 | 240 | self.set_colors(color_scheme) |
|
241 | 241 | |
|
242 | 242 | # Add a python parser so we can syntax highlight source while |
|
243 | 243 | # debugging. |
|
244 | 244 | self.parser = PyColorize.Parser() |
|
245 | 245 | |
|
246 | 246 | def set_colors(self, scheme): |
|
247 | 247 | """Shorthand access to the color table scheme selector method.""" |
|
248 | 248 | self.color_scheme_table.set_active_scheme(scheme) |
|
249 | 249 | |
|
250 | 250 | def interaction(self, frame, traceback): |
|
251 | 251 | self.shell.set_completer_frame(frame) |
|
252 | 252 | OldPdb.interaction(self, frame, traceback) |
|
253 | 253 | |
|
254 | 254 | def new_do_up(self, arg): |
|
255 | 255 | OldPdb.do_up(self, arg) |
|
256 | 256 | self.shell.set_completer_frame(self.curframe) |
|
257 | 257 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
258 | 258 | |
|
259 | 259 | def new_do_down(self, arg): |
|
260 | 260 | OldPdb.do_down(self, arg) |
|
261 | 261 | self.shell.set_completer_frame(self.curframe) |
|
262 | 262 | |
|
263 | 263 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
264 | 264 | |
|
265 | 265 | def new_do_frame(self, arg): |
|
266 | 266 | OldPdb.do_frame(self, arg) |
|
267 | 267 | self.shell.set_completer_frame(self.curframe) |
|
268 | 268 | |
|
269 | 269 | def new_do_quit(self, arg): |
|
270 | 270 | |
|
271 | 271 | if hasattr(self, 'old_all_completions'): |
|
272 | 272 | self.shell.Completer.all_completions=self.old_all_completions |
|
273 | 273 | |
|
274 | 274 | |
|
275 | 275 | return OldPdb.do_quit(self, arg) |
|
276 | 276 | |
|
277 | 277 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
278 | 278 | |
|
279 | 279 | def new_do_restart(self, arg): |
|
280 | 280 | """Restart command. In the context of ipython this is exactly the same |
|
281 | 281 | thing as 'quit'.""" |
|
282 | 282 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
283 | 283 | return self.do_quit(arg) |
|
284 | 284 | |
|
285 | 285 | def postloop(self): |
|
286 | 286 | self.shell.set_completer_frame(None) |
|
287 | 287 | |
|
288 | 288 | def print_stack_trace(self): |
|
289 | 289 | try: |
|
290 | 290 | for frame_lineno in self.stack: |
|
291 | 291 | self.print_stack_entry(frame_lineno, context = 5) |
|
292 | 292 | except KeyboardInterrupt: |
|
293 | 293 | pass |
|
294 | 294 | |
|
295 | 295 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
296 | 296 | context = 3): |
|
297 | 297 | #frame, lineno = frame_lineno |
|
298 | 298 | print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout) |
|
299 | 299 | |
|
300 | 300 | # vds: >> |
|
301 | 301 | frame, lineno = frame_lineno |
|
302 | 302 | filename = frame.f_code.co_filename |
|
303 | 303 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
304 | 304 | # vds: << |
|
305 | 305 | |
|
306 | 306 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): |
|
307 | 307 | import repr |
|
308 | 308 | |
|
309 | 309 | ret = [] |
|
310 | 310 | |
|
311 | 311 | Colors = self.color_scheme_table.active_colors |
|
312 | 312 | ColorsNormal = Colors.Normal |
|
313 | 313 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
314 | 314 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
315 | 315 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
316 | 316 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
317 | 317 | ColorsNormal) |
|
318 | 318 | |
|
319 | 319 | frame, lineno = frame_lineno |
|
320 | 320 | |
|
321 | 321 | return_value = '' |
|
322 | 322 | if '__return__' in frame.f_locals: |
|
323 | 323 | rv = frame.f_locals['__return__'] |
|
324 | 324 | #return_value += '->' |
|
325 | 325 | return_value += repr.repr(rv) + '\n' |
|
326 | 326 | ret.append(return_value) |
|
327 | 327 | |
|
328 | 328 | #s = filename + '(' + `lineno` + ')' |
|
329 | 329 | filename = self.canonic(frame.f_code.co_filename) |
|
330 | 330 | link = tpl_link % py3compat.cast_unicode(filename) |
|
331 | 331 | |
|
332 | 332 | if frame.f_code.co_name: |
|
333 | 333 | func = frame.f_code.co_name |
|
334 | 334 | else: |
|
335 | 335 | func = "<lambda>" |
|
336 | 336 | |
|
337 | 337 | call = '' |
|
338 | 338 | if func != '?': |
|
339 | 339 | if '__args__' in frame.f_locals: |
|
340 | 340 | args = repr.repr(frame.f_locals['__args__']) |
|
341 | 341 | else: |
|
342 | 342 | args = '()' |
|
343 | 343 | call = tpl_call % (func, args) |
|
344 | 344 | |
|
345 | 345 | # The level info should be generated in the same format pdb uses, to |
|
346 | 346 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
347 | 347 | if frame is self.curframe: |
|
348 | 348 | ret.append('> ') |
|
349 | 349 | else: |
|
350 | 350 | ret.append(' ') |
|
351 | 351 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) |
|
352 | 352 | |
|
353 | 353 | start = lineno - 1 - context//2 |
|
354 | 354 | lines = ulinecache.getlines(filename) |
|
355 | 355 | start = max(start, 0) |
|
356 | 356 | start = min(start, len(lines) - context) |
|
357 | 357 | lines = lines[start : start + context] |
|
358 | 358 | |
|
359 | 359 | for i,line in enumerate(lines): |
|
360 | 360 | show_arrow = (start + 1 + i == lineno) |
|
361 | 361 | linetpl = (frame is self.curframe or show_arrow) \ |
|
362 | 362 | and tpl_line_em \ |
|
363 | 363 | or tpl_line |
|
364 | 364 | ret.append(self.__format_line(linetpl, filename, |
|
365 | 365 | start + 1 + i, line, |
|
366 | 366 | arrow = show_arrow) ) |
|
367 | 367 | return ''.join(ret) |
|
368 | 368 | |
|
369 | 369 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
370 | 370 | bp_mark = "" |
|
371 | 371 | bp_mark_color = "" |
|
372 | 372 | |
|
373 | 373 | scheme = self.color_scheme_table.active_scheme_name |
|
374 | 374 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
375 | 375 | if not err: line = new_line |
|
376 | 376 | |
|
377 | 377 | bp = None |
|
378 | 378 | if lineno in self.get_file_breaks(filename): |
|
379 | 379 | bps = self.get_breaks(filename, lineno) |
|
380 | 380 | bp = bps[-1] |
|
381 | 381 | |
|
382 | 382 | if bp: |
|
383 | 383 | Colors = self.color_scheme_table.active_colors |
|
384 | 384 | bp_mark = str(bp.number) |
|
385 | 385 | bp_mark_color = Colors.breakpoint_enabled |
|
386 | 386 | if not bp.enabled: |
|
387 | 387 | bp_mark_color = Colors.breakpoint_disabled |
|
388 | 388 | |
|
389 | 389 | numbers_width = 7 |
|
390 | 390 | if arrow: |
|
391 | 391 | # This is the line with the error |
|
392 | 392 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
393 | 393 | if pad >= 3: |
|
394 | 394 | marker = '-'*(pad-3) + '-> ' |
|
395 | 395 | elif pad == 2: |
|
396 | 396 | marker = '> ' |
|
397 | 397 | elif pad == 1: |
|
398 | 398 | marker = '>' |
|
399 | 399 | else: |
|
400 | 400 | marker = '' |
|
401 | 401 | num = '%s%s' % (marker, str(lineno)) |
|
402 | 402 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
403 | 403 | else: |
|
404 | 404 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
405 | 405 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
406 | 406 | |
|
407 | 407 | return line |
|
408 | 408 | |
|
409 | 409 | def list_command_pydb(self, arg): |
|
410 | 410 | """List command to use if we have a newer pydb installed""" |
|
411 | 411 | filename, first, last = OldPdb.parse_list_cmd(self, arg) |
|
412 | 412 | if filename is not None: |
|
413 | 413 | self.print_list_lines(filename, first, last) |
|
414 | 414 | |
|
415 | 415 | def print_list_lines(self, filename, first, last): |
|
416 | 416 | """The printing (as opposed to the parsing part of a 'list' |
|
417 | 417 | command.""" |
|
418 | 418 | try: |
|
419 | 419 | Colors = self.color_scheme_table.active_colors |
|
420 | 420 | ColorsNormal = Colors.Normal |
|
421 | 421 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
422 | 422 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
423 | 423 | src = [] |
|
424 | 424 | if filename == "<string>" and hasattr(self, "_exec_filename"): |
|
425 | 425 | filename = self._exec_filename |
|
426 | 426 | |
|
427 | 427 | for lineno in range(first, last+1): |
|
428 | 428 | line = ulinecache.getline(filename, lineno) |
|
429 | 429 | if not line: |
|
430 | 430 | break |
|
431 | 431 | |
|
432 | 432 | if lineno == self.curframe.f_lineno: |
|
433 | 433 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
434 | 434 | else: |
|
435 | 435 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
436 | 436 | |
|
437 | 437 | src.append(line) |
|
438 | 438 | self.lineno = lineno |
|
439 | 439 | |
|
440 | 440 | print(''.join(src), file=io.stdout) |
|
441 | 441 | |
|
442 | 442 | except KeyboardInterrupt: |
|
443 | 443 | pass |
|
444 | 444 | |
|
445 | 445 | def do_list(self, arg): |
|
446 | 446 | self.lastcmd = 'list' |
|
447 | 447 | last = None |
|
448 | 448 | if arg: |
|
449 | 449 | try: |
|
450 | 450 | x = eval(arg, {}, {}) |
|
451 | 451 | if type(x) == type(()): |
|
452 | 452 | first, last = x |
|
453 | 453 | first = int(first) |
|
454 | 454 | last = int(last) |
|
455 | 455 | if last < first: |
|
456 | 456 | # Assume it's a count |
|
457 | 457 | last = first + last |
|
458 | 458 | else: |
|
459 | 459 | first = max(1, int(x) - 5) |
|
460 | 460 | except: |
|
461 | 461 | print('*** Error in argument:', repr(arg)) |
|
462 | 462 | return |
|
463 | 463 | elif self.lineno is None: |
|
464 | 464 | first = max(1, self.curframe.f_lineno - 5) |
|
465 | 465 | else: |
|
466 | 466 | first = self.lineno + 1 |
|
467 | 467 | if last is None: |
|
468 | 468 | last = first + 10 |
|
469 | 469 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
470 | 470 | |
|
471 | 471 | # vds: >> |
|
472 | 472 | lineno = first |
|
473 | 473 | filename = self.curframe.f_code.co_filename |
|
474 | 474 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
475 | 475 | # vds: << |
|
476 | 476 | |
|
477 | 477 | do_l = do_list |
|
478 | 478 | |
|
479 | 479 | def do_pdef(self, arg): |
|
480 |
"""Print the |
|
|
480 | """Print the call signature for any callable object. | |
|
481 | 481 | |
|
482 | 482 | The debugger interface to %pdef""" |
|
483 | 483 | namespaces = [('Locals', self.curframe.f_locals), |
|
484 | 484 | ('Globals', self.curframe.f_globals)] |
|
485 | 485 | self.shell.find_line_magic('pdef')(arg, namespaces=namespaces) |
|
486 | 486 | |
|
487 | 487 | def do_pdoc(self, arg): |
|
488 | 488 | """Print the docstring for an object. |
|
489 | 489 | |
|
490 | 490 | The debugger interface to %pdoc.""" |
|
491 | 491 | namespaces = [('Locals', self.curframe.f_locals), |
|
492 | 492 | ('Globals', self.curframe.f_globals)] |
|
493 | 493 | self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces) |
|
494 | 494 | |
|
495 | 495 | def do_pfile(self, arg): |
|
496 | 496 | """Print (or run through pager) the file where an object is defined. |
|
497 | 497 | |
|
498 | 498 | The debugger interface to %pfile. |
|
499 | 499 | """ |
|
500 | 500 | namespaces = [('Locals', self.curframe.f_locals), |
|
501 | 501 | ('Globals', self.curframe.f_globals)] |
|
502 | 502 | self.shell.find_line_magic('pfile')(arg, namespaces=namespaces) |
|
503 | 503 | |
|
504 | 504 | def do_pinfo(self, arg): |
|
505 | 505 | """Provide detailed information about an object. |
|
506 | 506 | |
|
507 | 507 | The debugger interface to %pinfo, i.e., obj?.""" |
|
508 | 508 | namespaces = [('Locals', self.curframe.f_locals), |
|
509 | 509 | ('Globals', self.curframe.f_globals)] |
|
510 | 510 | self.shell.find_line_magic('pinfo')(arg, namespaces=namespaces) |
|
511 | 511 | |
|
512 | 512 | def do_pinfo2(self, arg): |
|
513 | 513 | """Provide extra detailed information about an object. |
|
514 | 514 | |
|
515 | 515 | The debugger interface to %pinfo2, i.e., obj??.""" |
|
516 | 516 | namespaces = [('Locals', self.curframe.f_locals), |
|
517 | 517 | ('Globals', self.curframe.f_globals)] |
|
518 | 518 | self.shell.find_line_magic('pinfo2')(arg, namespaces=namespaces) |
|
519 | 519 | |
|
520 | 520 | def do_psource(self, arg): |
|
521 | 521 | """Print (or run through pager) the source code for an object.""" |
|
522 | 522 | namespaces = [('Locals', self.curframe.f_locals), |
|
523 | 523 | ('Globals', self.curframe.f_globals)] |
|
524 | 524 | self.shell.find_line_magic('psource')(arg, namespaces=namespaces) |
|
525 | 525 | |
|
526 | 526 | def checkline(self, filename, lineno): |
|
527 | 527 | """Check whether specified line seems to be executable. |
|
528 | 528 | |
|
529 | 529 | Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank |
|
530 | 530 | line or EOF). Warning: testing is not comprehensive. |
|
531 | 531 | """ |
|
532 | 532 | ####################################################################### |
|
533 | 533 | # XXX Hack! Use python-2.5 compatible code for this call, because with |
|
534 | 534 | # all of our changes, we've drifted from the pdb api in 2.6. For now, |
|
535 | 535 | # changing: |
|
536 | 536 | # |
|
537 | 537 | #line = linecache.getline(filename, lineno, self.curframe.f_globals) |
|
538 | 538 | # to: |
|
539 | 539 | # |
|
540 | 540 | line = linecache.getline(filename, lineno) |
|
541 | 541 | # |
|
542 | 542 | # does the trick. But in reality, we need to fix this by reconciling |
|
543 | 543 | # our updates with the new Pdb APIs in Python 2.6. |
|
544 | 544 | # |
|
545 | 545 | # End hack. The rest of this method is copied verbatim from 2.6 pdb.py |
|
546 | 546 | ####################################################################### |
|
547 | 547 | |
|
548 | 548 | if not line: |
|
549 | 549 | print('End of file', file=self.stdout) |
|
550 | 550 | return 0 |
|
551 | 551 | line = line.strip() |
|
552 | 552 | # Don't allow setting breakpoint at a blank line |
|
553 | 553 | if (not line or (line[0] == '#') or |
|
554 | 554 | (line[:3] == '"""') or line[:3] == "'''"): |
|
555 | 555 | print('*** Blank or comment', file=self.stdout) |
|
556 | 556 | return 0 |
|
557 | 557 | return lineno |
@@ -1,703 +1,703 b'' | |||
|
1 | 1 | """Implementation of namespace-related magic functions. |
|
2 | 2 | """ |
|
3 | 3 | #----------------------------------------------------------------------------- |
|
4 | 4 | # Copyright (c) 2012 The IPython Development Team. |
|
5 | 5 | # |
|
6 | 6 | # Distributed under the terms of the Modified BSD License. |
|
7 | 7 | # |
|
8 | 8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
9 | 9 | #----------------------------------------------------------------------------- |
|
10 | 10 | |
|
11 | 11 | #----------------------------------------------------------------------------- |
|
12 | 12 | # Imports |
|
13 | 13 | #----------------------------------------------------------------------------- |
|
14 | 14 | |
|
15 | 15 | # Stdlib |
|
16 | 16 | import gc |
|
17 | 17 | import re |
|
18 | 18 | import sys |
|
19 | 19 | |
|
20 | 20 | # Our own packages |
|
21 | 21 | from IPython.core import page |
|
22 | 22 | from IPython.core.error import StdinNotImplementedError, UsageError |
|
23 | 23 | from IPython.core.magic import Magics, magics_class, line_magic |
|
24 | 24 | from IPython.testing.skipdoctest import skip_doctest |
|
25 | 25 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
26 | 26 | from IPython.utils.openpy import read_py_file |
|
27 | 27 | from IPython.utils.path import get_py_filename |
|
28 | 28 | |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | # Magic implementation classes |
|
31 | 31 | #----------------------------------------------------------------------------- |
|
32 | 32 | |
|
33 | 33 | @magics_class |
|
34 | 34 | class NamespaceMagics(Magics): |
|
35 | 35 | """Magics to manage various aspects of the user's namespace. |
|
36 | 36 | |
|
37 | 37 | These include listing variables, introspecting into them, etc. |
|
38 | 38 | """ |
|
39 | 39 | |
|
40 | 40 | @line_magic |
|
41 | 41 | def pinfo(self, parameter_s='', namespaces=None): |
|
42 | 42 | """Provide detailed information about an object. |
|
43 | 43 | |
|
44 | 44 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
45 | 45 | |
|
46 | 46 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
47 | 47 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
48 | 48 | detail_level = 0 |
|
49 | 49 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
50 | 50 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
51 | 51 | pinfo,qmark1,oname,qmark2 = \ |
|
52 | 52 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
53 | 53 | if pinfo or qmark1 or qmark2: |
|
54 | 54 | detail_level = 1 |
|
55 | 55 | if "*" in oname: |
|
56 | 56 | self.psearch(oname) |
|
57 | 57 | else: |
|
58 | 58 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
59 | 59 | namespaces=namespaces) |
|
60 | 60 | |
|
61 | 61 | @line_magic |
|
62 | 62 | def pinfo2(self, parameter_s='', namespaces=None): |
|
63 | 63 | """Provide extra detailed information about an object. |
|
64 | 64 | |
|
65 | 65 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
66 | 66 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
67 | 67 | namespaces=namespaces) |
|
68 | 68 | |
|
69 | 69 | @skip_doctest |
|
70 | 70 | @line_magic |
|
71 | 71 | def pdef(self, parameter_s='', namespaces=None): |
|
72 |
"""Print the |
|
|
72 | """Print the call signature for any callable object. | |
|
73 | 73 | |
|
74 | 74 | If the object is a class, print the constructor information. |
|
75 | 75 | |
|
76 | 76 | Examples |
|
77 | 77 | -------- |
|
78 | 78 | :: |
|
79 | 79 | |
|
80 | 80 | In [3]: %pdef urllib.urlopen |
|
81 | 81 | urllib.urlopen(url, data=None, proxies=None) |
|
82 | 82 | """ |
|
83 | 83 | self.shell._inspect('pdef',parameter_s, namespaces) |
|
84 | 84 | |
|
85 | 85 | @line_magic |
|
86 | 86 | def pdoc(self, parameter_s='', namespaces=None): |
|
87 | 87 | """Print the docstring for an object. |
|
88 | 88 | |
|
89 | 89 | If the given object is a class, it will print both the class and the |
|
90 | 90 | constructor docstrings.""" |
|
91 | 91 | self.shell._inspect('pdoc',parameter_s, namespaces) |
|
92 | 92 | |
|
93 | 93 | @line_magic |
|
94 | 94 | def psource(self, parameter_s='', namespaces=None): |
|
95 | 95 | """Print (or run through pager) the source code for an object.""" |
|
96 | 96 | if not parameter_s: |
|
97 | 97 | raise UsageError('Missing object name.') |
|
98 | 98 | self.shell._inspect('psource',parameter_s, namespaces) |
|
99 | 99 | |
|
100 | 100 | @line_magic |
|
101 | 101 | def pfile(self, parameter_s='', namespaces=None): |
|
102 | 102 | """Print (or run through pager) the file where an object is defined. |
|
103 | 103 | |
|
104 | 104 | The file opens at the line where the object definition begins. IPython |
|
105 | 105 | will honor the environment variable PAGER if set, and otherwise will |
|
106 | 106 | do its best to print the file in a convenient form. |
|
107 | 107 | |
|
108 | 108 | If the given argument is not an object currently defined, IPython will |
|
109 | 109 | try to interpret it as a filename (automatically adding a .py extension |
|
110 | 110 | if needed). You can thus use %pfile as a syntax highlighting code |
|
111 | 111 | viewer.""" |
|
112 | 112 | |
|
113 | 113 | # first interpret argument as an object name |
|
114 | 114 | out = self.shell._inspect('pfile',parameter_s, namespaces) |
|
115 | 115 | # if not, try the input as a filename |
|
116 | 116 | if out == 'not found': |
|
117 | 117 | try: |
|
118 | 118 | filename = get_py_filename(parameter_s) |
|
119 | 119 | except IOError as msg: |
|
120 | 120 | print msg |
|
121 | 121 | return |
|
122 | 122 | page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False))) |
|
123 | 123 | |
|
124 | 124 | @line_magic |
|
125 | 125 | def psearch(self, parameter_s=''): |
|
126 | 126 | """Search for object in namespaces by wildcard. |
|
127 | 127 | |
|
128 | 128 | %psearch [options] PATTERN [OBJECT TYPE] |
|
129 | 129 | |
|
130 | 130 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
131 | 131 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
132 | 132 | rest of the command line must be unchanged (options come first), so |
|
133 | 133 | for example the following forms are equivalent |
|
134 | 134 | |
|
135 | 135 | %psearch -i a* function |
|
136 | 136 | -i a* function? |
|
137 | 137 | ?-i a* function |
|
138 | 138 | |
|
139 | 139 | Arguments: |
|
140 | 140 | |
|
141 | 141 | PATTERN |
|
142 | 142 | |
|
143 | 143 | where PATTERN is a string containing * as a wildcard similar to its |
|
144 | 144 | use in a shell. The pattern is matched in all namespaces on the |
|
145 | 145 | search path. By default objects starting with a single _ are not |
|
146 | 146 | matched, many IPython generated objects have a single |
|
147 | 147 | underscore. The default is case insensitive matching. Matching is |
|
148 | 148 | also done on the attributes of objects and not only on the objects |
|
149 | 149 | in a module. |
|
150 | 150 | |
|
151 | 151 | [OBJECT TYPE] |
|
152 | 152 | |
|
153 | 153 | Is the name of a python type from the types module. The name is |
|
154 | 154 | given in lowercase without the ending type, ex. StringType is |
|
155 | 155 | written string. By adding a type here only objects matching the |
|
156 | 156 | given type are matched. Using all here makes the pattern match all |
|
157 | 157 | types (this is the default). |
|
158 | 158 | |
|
159 | 159 | Options: |
|
160 | 160 | |
|
161 | 161 | -a: makes the pattern match even objects whose names start with a |
|
162 | 162 | single underscore. These names are normally omitted from the |
|
163 | 163 | search. |
|
164 | 164 | |
|
165 | 165 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
166 | 166 | these options are given, the default is read from your configuration |
|
167 | 167 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
168 | 168 | If this option is not specified in your configuration file, IPython's |
|
169 | 169 | internal default is to do a case sensitive search. |
|
170 | 170 | |
|
171 | 171 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
172 | 172 | specify can be searched in any of the following namespaces: |
|
173 | 173 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
174 | 174 | 'builtin' and 'user' are the search defaults. Note that you should |
|
175 | 175 | not use quotes when specifying namespaces. |
|
176 | 176 | |
|
177 | 177 | 'Builtin' contains the python module builtin, 'user' contains all |
|
178 | 178 | user data, 'alias' only contain the shell aliases and no python |
|
179 | 179 | objects, 'internal' contains objects used by IPython. The |
|
180 | 180 | 'user_global' namespace is only used by embedded IPython instances, |
|
181 | 181 | and it contains module-level globals. You can add namespaces to the |
|
182 | 182 | search with -s or exclude them with -e (these options can be given |
|
183 | 183 | more than once). |
|
184 | 184 | |
|
185 | 185 | Examples |
|
186 | 186 | -------- |
|
187 | 187 | :: |
|
188 | 188 | |
|
189 | 189 | %psearch a* -> objects beginning with an a |
|
190 | 190 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
191 | 191 | %psearch a* function -> all functions beginning with an a |
|
192 | 192 | %psearch re.e* -> objects beginning with an e in module re |
|
193 | 193 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
194 | 194 | %psearch r*.* string -> all strings in modules beginning with r |
|
195 | 195 | |
|
196 | 196 | Case sensitive search:: |
|
197 | 197 | |
|
198 | 198 | %psearch -c a* list all object beginning with lower case a |
|
199 | 199 | |
|
200 | 200 | Show objects beginning with a single _:: |
|
201 | 201 | |
|
202 | 202 | %psearch -a _* list objects beginning with a single underscore |
|
203 | 203 | """ |
|
204 | 204 | try: |
|
205 | 205 | parameter_s.encode('ascii') |
|
206 | 206 | except UnicodeEncodeError: |
|
207 | 207 | print 'Python identifiers can only contain ascii characters.' |
|
208 | 208 | return |
|
209 | 209 | |
|
210 | 210 | # default namespaces to be searched |
|
211 | 211 | def_search = ['user_local', 'user_global', 'builtin'] |
|
212 | 212 | |
|
213 | 213 | # Process options/args |
|
214 | 214 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
215 | 215 | opt = opts.get |
|
216 | 216 | shell = self.shell |
|
217 | 217 | psearch = shell.inspector.psearch |
|
218 | 218 | |
|
219 | 219 | # select case options |
|
220 | 220 | if 'i' in opts: |
|
221 | 221 | ignore_case = True |
|
222 | 222 | elif 'c' in opts: |
|
223 | 223 | ignore_case = False |
|
224 | 224 | else: |
|
225 | 225 | ignore_case = not shell.wildcards_case_sensitive |
|
226 | 226 | |
|
227 | 227 | # Build list of namespaces to search from user options |
|
228 | 228 | def_search.extend(opt('s',[])) |
|
229 | 229 | ns_exclude = ns_exclude=opt('e',[]) |
|
230 | 230 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
231 | 231 | |
|
232 | 232 | # Call the actual search |
|
233 | 233 | try: |
|
234 | 234 | psearch(args,shell.ns_table,ns_search, |
|
235 | 235 | show_all=opt('a'),ignore_case=ignore_case) |
|
236 | 236 | except: |
|
237 | 237 | shell.showtraceback() |
|
238 | 238 | |
|
239 | 239 | @skip_doctest |
|
240 | 240 | @line_magic |
|
241 | 241 | def who_ls(self, parameter_s=''): |
|
242 | 242 | """Return a sorted list of all interactive variables. |
|
243 | 243 | |
|
244 | 244 | If arguments are given, only variables of types matching these |
|
245 | 245 | arguments are returned. |
|
246 | 246 | |
|
247 | 247 | Examples |
|
248 | 248 | -------- |
|
249 | 249 | |
|
250 | 250 | Define two variables and list them with who_ls:: |
|
251 | 251 | |
|
252 | 252 | In [1]: alpha = 123 |
|
253 | 253 | |
|
254 | 254 | In [2]: beta = 'test' |
|
255 | 255 | |
|
256 | 256 | In [3]: %who_ls |
|
257 | 257 | Out[3]: ['alpha', 'beta'] |
|
258 | 258 | |
|
259 | 259 | In [4]: %who_ls int |
|
260 | 260 | Out[4]: ['alpha'] |
|
261 | 261 | |
|
262 | 262 | In [5]: %who_ls str |
|
263 | 263 | Out[5]: ['beta'] |
|
264 | 264 | """ |
|
265 | 265 | |
|
266 | 266 | user_ns = self.shell.user_ns |
|
267 | 267 | user_ns_hidden = self.shell.user_ns_hidden |
|
268 | 268 | out = [ i for i in user_ns |
|
269 | 269 | if not i.startswith('_') \ |
|
270 | 270 | and not i in user_ns_hidden ] |
|
271 | 271 | |
|
272 | 272 | typelist = parameter_s.split() |
|
273 | 273 | if typelist: |
|
274 | 274 | typeset = set(typelist) |
|
275 | 275 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
276 | 276 | |
|
277 | 277 | out.sort() |
|
278 | 278 | return out |
|
279 | 279 | |
|
280 | 280 | @skip_doctest |
|
281 | 281 | @line_magic |
|
282 | 282 | def who(self, parameter_s=''): |
|
283 | 283 | """Print all interactive variables, with some minimal formatting. |
|
284 | 284 | |
|
285 | 285 | If any arguments are given, only variables whose type matches one of |
|
286 | 286 | these are printed. For example:: |
|
287 | 287 | |
|
288 | 288 | %who function str |
|
289 | 289 | |
|
290 | 290 | will only list functions and strings, excluding all other types of |
|
291 | 291 | variables. To find the proper type names, simply use type(var) at a |
|
292 | 292 | command line to see how python prints type names. For example: |
|
293 | 293 | |
|
294 | 294 | :: |
|
295 | 295 | |
|
296 | 296 | In [1]: type('hello')\\ |
|
297 | 297 | Out[1]: <type 'str'> |
|
298 | 298 | |
|
299 | 299 | indicates that the type name for strings is 'str'. |
|
300 | 300 | |
|
301 | 301 | ``%who`` always excludes executed names loaded through your configuration |
|
302 | 302 | file and things which are internal to IPython. |
|
303 | 303 | |
|
304 | 304 | This is deliberate, as typically you may load many modules and the |
|
305 | 305 | purpose of %who is to show you only what you've manually defined. |
|
306 | 306 | |
|
307 | 307 | Examples |
|
308 | 308 | -------- |
|
309 | 309 | |
|
310 | 310 | Define two variables and list them with who:: |
|
311 | 311 | |
|
312 | 312 | In [1]: alpha = 123 |
|
313 | 313 | |
|
314 | 314 | In [2]: beta = 'test' |
|
315 | 315 | |
|
316 | 316 | In [3]: %who |
|
317 | 317 | alpha beta |
|
318 | 318 | |
|
319 | 319 | In [4]: %who int |
|
320 | 320 | alpha |
|
321 | 321 | |
|
322 | 322 | In [5]: %who str |
|
323 | 323 | beta |
|
324 | 324 | """ |
|
325 | 325 | |
|
326 | 326 | varlist = self.who_ls(parameter_s) |
|
327 | 327 | if not varlist: |
|
328 | 328 | if parameter_s: |
|
329 | 329 | print 'No variables match your requested type.' |
|
330 | 330 | else: |
|
331 | 331 | print 'Interactive namespace is empty.' |
|
332 | 332 | return |
|
333 | 333 | |
|
334 | 334 | # if we have variables, move on... |
|
335 | 335 | count = 0 |
|
336 | 336 | for i in varlist: |
|
337 | 337 | print i+'\t', |
|
338 | 338 | count += 1 |
|
339 | 339 | if count > 8: |
|
340 | 340 | count = 0 |
|
341 | 341 | |
|
342 | 342 | |
|
343 | 343 | |
|
344 | 344 | @skip_doctest |
|
345 | 345 | @line_magic |
|
346 | 346 | def whos(self, parameter_s=''): |
|
347 | 347 | """Like %who, but gives some extra information about each variable. |
|
348 | 348 | |
|
349 | 349 | The same type filtering of %who can be applied here. |
|
350 | 350 | |
|
351 | 351 | For all variables, the type is printed. Additionally it prints: |
|
352 | 352 | |
|
353 | 353 | - For {},[],(): their length. |
|
354 | 354 | |
|
355 | 355 | - For numpy arrays, a summary with shape, number of |
|
356 | 356 | elements, typecode and size in memory. |
|
357 | 357 | |
|
358 | 358 | - Everything else: a string representation, snipping their middle if |
|
359 | 359 | too long. |
|
360 | 360 | |
|
361 | 361 | Examples |
|
362 | 362 | -------- |
|
363 | 363 | |
|
364 | 364 | Define two variables and list them with whos:: |
|
365 | 365 | |
|
366 | 366 | In [1]: alpha = 123 |
|
367 | 367 | |
|
368 | 368 | In [2]: beta = 'test' |
|
369 | 369 | |
|
370 | 370 | In [3]: %whos |
|
371 | 371 | Variable Type Data/Info |
|
372 | 372 | -------------------------------- |
|
373 | 373 | alpha int 123 |
|
374 | 374 | beta str test |
|
375 | 375 | """ |
|
376 | 376 | |
|
377 | 377 | varnames = self.who_ls(parameter_s) |
|
378 | 378 | if not varnames: |
|
379 | 379 | if parameter_s: |
|
380 | 380 | print 'No variables match your requested type.' |
|
381 | 381 | else: |
|
382 | 382 | print 'Interactive namespace is empty.' |
|
383 | 383 | return |
|
384 | 384 | |
|
385 | 385 | # if we have variables, move on... |
|
386 | 386 | |
|
387 | 387 | # for these types, show len() instead of data: |
|
388 | 388 | seq_types = ['dict', 'list', 'tuple'] |
|
389 | 389 | |
|
390 | 390 | # for numpy arrays, display summary info |
|
391 | 391 | ndarray_type = None |
|
392 | 392 | if 'numpy' in sys.modules: |
|
393 | 393 | try: |
|
394 | 394 | from numpy import ndarray |
|
395 | 395 | except ImportError: |
|
396 | 396 | pass |
|
397 | 397 | else: |
|
398 | 398 | ndarray_type = ndarray.__name__ |
|
399 | 399 | |
|
400 | 400 | # Find all variable names and types so we can figure out column sizes |
|
401 | 401 | def get_vars(i): |
|
402 | 402 | return self.shell.user_ns[i] |
|
403 | 403 | |
|
404 | 404 | # some types are well known and can be shorter |
|
405 | 405 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
406 | 406 | def type_name(v): |
|
407 | 407 | tn = type(v).__name__ |
|
408 | 408 | return abbrevs.get(tn,tn) |
|
409 | 409 | |
|
410 | 410 | varlist = map(get_vars,varnames) |
|
411 | 411 | |
|
412 | 412 | typelist = [] |
|
413 | 413 | for vv in varlist: |
|
414 | 414 | tt = type_name(vv) |
|
415 | 415 | |
|
416 | 416 | if tt=='instance': |
|
417 | 417 | typelist.append( abbrevs.get(str(vv.__class__), |
|
418 | 418 | str(vv.__class__))) |
|
419 | 419 | else: |
|
420 | 420 | typelist.append(tt) |
|
421 | 421 | |
|
422 | 422 | # column labels and # of spaces as separator |
|
423 | 423 | varlabel = 'Variable' |
|
424 | 424 | typelabel = 'Type' |
|
425 | 425 | datalabel = 'Data/Info' |
|
426 | 426 | colsep = 3 |
|
427 | 427 | # variable format strings |
|
428 | 428 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
429 | 429 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
430 | 430 | # find the size of the columns to format the output nicely |
|
431 | 431 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
432 | 432 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
433 | 433 | # table header |
|
434 | 434 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
435 | 435 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
436 | 436 | # and the table itself |
|
437 | 437 | kb = 1024 |
|
438 | 438 | Mb = 1048576 # kb**2 |
|
439 | 439 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
440 | 440 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
441 | 441 | if vtype in seq_types: |
|
442 | 442 | print "n="+str(len(var)) |
|
443 | 443 | elif vtype == ndarray_type: |
|
444 | 444 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
445 | 445 | if vtype==ndarray_type: |
|
446 | 446 | # numpy |
|
447 | 447 | vsize = var.size |
|
448 | 448 | vbytes = vsize*var.itemsize |
|
449 | 449 | vdtype = var.dtype |
|
450 | 450 | |
|
451 | 451 | if vbytes < 100000: |
|
452 | 452 | print aformat % (vshape, vsize, vdtype, vbytes) |
|
453 | 453 | else: |
|
454 | 454 | print aformat % (vshape, vsize, vdtype, vbytes), |
|
455 | 455 | if vbytes < Mb: |
|
456 | 456 | print '(%s kb)' % (vbytes/kb,) |
|
457 | 457 | else: |
|
458 | 458 | print '(%s Mb)' % (vbytes/Mb,) |
|
459 | 459 | else: |
|
460 | 460 | try: |
|
461 | 461 | vstr = str(var) |
|
462 | 462 | except UnicodeEncodeError: |
|
463 | 463 | vstr = unicode(var).encode(DEFAULT_ENCODING, |
|
464 | 464 | 'backslashreplace') |
|
465 | 465 | except: |
|
466 | 466 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
467 | 467 | vstr = vstr.replace('\n', '\\n') |
|
468 | 468 | if len(vstr) < 50: |
|
469 | 469 | print vstr |
|
470 | 470 | else: |
|
471 | 471 | print vstr[:25] + "<...>" + vstr[-25:] |
|
472 | 472 | |
|
473 | 473 | @line_magic |
|
474 | 474 | def reset(self, parameter_s=''): |
|
475 | 475 | """Resets the namespace by removing all names defined by the user, if |
|
476 | 476 | called without arguments, or by removing some types of objects, such |
|
477 | 477 | as everything currently in IPython's In[] and Out[] containers (see |
|
478 | 478 | the parameters for details). |
|
479 | 479 | |
|
480 | 480 | Parameters |
|
481 | 481 | ---------- |
|
482 | 482 | -f : force reset without asking for confirmation. |
|
483 | 483 | |
|
484 | 484 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
485 | 485 | References to objects may be kept. By default (without this option), |
|
486 | 486 | we do a 'hard' reset, giving you a new session and removing all |
|
487 | 487 | references to objects from the current session. |
|
488 | 488 | |
|
489 | 489 | in : reset input history |
|
490 | 490 | |
|
491 | 491 | out : reset output history |
|
492 | 492 | |
|
493 | 493 | dhist : reset directory history |
|
494 | 494 | |
|
495 | 495 | array : reset only variables that are NumPy arrays |
|
496 | 496 | |
|
497 | 497 | See Also |
|
498 | 498 | -------- |
|
499 | 499 | magic_reset_selective : invoked as ``%reset_selective`` |
|
500 | 500 | |
|
501 | 501 | Examples |
|
502 | 502 | -------- |
|
503 | 503 | :: |
|
504 | 504 | |
|
505 | 505 | In [6]: a = 1 |
|
506 | 506 | |
|
507 | 507 | In [7]: a |
|
508 | 508 | Out[7]: 1 |
|
509 | 509 | |
|
510 | 510 | In [8]: 'a' in _ip.user_ns |
|
511 | 511 | Out[8]: True |
|
512 | 512 | |
|
513 | 513 | In [9]: %reset -f |
|
514 | 514 | |
|
515 | 515 | In [1]: 'a' in _ip.user_ns |
|
516 | 516 | Out[1]: False |
|
517 | 517 | |
|
518 | 518 | In [2]: %reset -f in |
|
519 | 519 | Flushing input history |
|
520 | 520 | |
|
521 | 521 | In [3]: %reset -f dhist in |
|
522 | 522 | Flushing directory history |
|
523 | 523 | Flushing input history |
|
524 | 524 | |
|
525 | 525 | Notes |
|
526 | 526 | ----- |
|
527 | 527 | Calling this magic from clients that do not implement standard input, |
|
528 | 528 | such as the ipython notebook interface, will reset the namespace |
|
529 | 529 | without confirmation. |
|
530 | 530 | """ |
|
531 | 531 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
532 | 532 | if 'f' in opts: |
|
533 | 533 | ans = True |
|
534 | 534 | else: |
|
535 | 535 | try: |
|
536 | 536 | ans = self.shell.ask_yes_no( |
|
537 | 537 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", |
|
538 | 538 | default='n') |
|
539 | 539 | except StdinNotImplementedError: |
|
540 | 540 | ans = True |
|
541 | 541 | if not ans: |
|
542 | 542 | print 'Nothing done.' |
|
543 | 543 | return |
|
544 | 544 | |
|
545 | 545 | if 's' in opts: # Soft reset |
|
546 | 546 | user_ns = self.shell.user_ns |
|
547 | 547 | for i in self.who_ls(): |
|
548 | 548 | del(user_ns[i]) |
|
549 | 549 | elif len(args) == 0: # Hard reset |
|
550 | 550 | self.shell.reset(new_session = False) |
|
551 | 551 | |
|
552 | 552 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
553 | 553 | ip = self.shell |
|
554 | 554 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
555 | 555 | |
|
556 | 556 | for target in args: |
|
557 | 557 | target = target.lower() # make matches case insensitive |
|
558 | 558 | if target == 'out': |
|
559 | 559 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
560 | 560 | self.shell.displayhook.flush() |
|
561 | 561 | |
|
562 | 562 | elif target == 'in': |
|
563 | 563 | print "Flushing input history" |
|
564 | 564 | pc = self.shell.displayhook.prompt_count + 1 |
|
565 | 565 | for n in range(1, pc): |
|
566 | 566 | key = '_i'+repr(n) |
|
567 | 567 | user_ns.pop(key,None) |
|
568 | 568 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
569 | 569 | hm = ip.history_manager |
|
570 | 570 | # don't delete these, as %save and %macro depending on the |
|
571 | 571 | # length of these lists to be preserved |
|
572 | 572 | hm.input_hist_parsed[:] = [''] * pc |
|
573 | 573 | hm.input_hist_raw[:] = [''] * pc |
|
574 | 574 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
575 | 575 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
576 | 576 | |
|
577 | 577 | elif target == 'array': |
|
578 | 578 | # Support cleaning up numpy arrays |
|
579 | 579 | try: |
|
580 | 580 | from numpy import ndarray |
|
581 | 581 | # This must be done with items and not iteritems because |
|
582 | 582 | # we're going to modify the dict in-place. |
|
583 | 583 | for x,val in user_ns.items(): |
|
584 | 584 | if isinstance(val,ndarray): |
|
585 | 585 | del user_ns[x] |
|
586 | 586 | except ImportError: |
|
587 | 587 | print "reset array only works if Numpy is available." |
|
588 | 588 | |
|
589 | 589 | elif target == 'dhist': |
|
590 | 590 | print "Flushing directory history" |
|
591 | 591 | del user_ns['_dh'][:] |
|
592 | 592 | |
|
593 | 593 | else: |
|
594 | 594 | print "Don't know how to reset ", |
|
595 | 595 | print target + ", please run `%reset?` for details" |
|
596 | 596 | |
|
597 | 597 | gc.collect() |
|
598 | 598 | |
|
599 | 599 | @line_magic |
|
600 | 600 | def reset_selective(self, parameter_s=''): |
|
601 | 601 | """Resets the namespace by removing names defined by the user. |
|
602 | 602 | |
|
603 | 603 | Input/Output history are left around in case you need them. |
|
604 | 604 | |
|
605 | 605 | %reset_selective [-f] regex |
|
606 | 606 | |
|
607 | 607 | No action is taken if regex is not included |
|
608 | 608 | |
|
609 | 609 | Options |
|
610 | 610 | -f : force reset without asking for confirmation. |
|
611 | 611 | |
|
612 | 612 | See Also |
|
613 | 613 | -------- |
|
614 | 614 | magic_reset : invoked as ``%reset`` |
|
615 | 615 | |
|
616 | 616 | Examples |
|
617 | 617 | -------- |
|
618 | 618 | |
|
619 | 619 | We first fully reset the namespace so your output looks identical to |
|
620 | 620 | this example for pedagogical reasons; in practice you do not need a |
|
621 | 621 | full reset:: |
|
622 | 622 | |
|
623 | 623 | In [1]: %reset -f |
|
624 | 624 | |
|
625 | 625 | Now, with a clean namespace we can make a few variables and use |
|
626 | 626 | ``%reset_selective`` to only delete names that match our regexp:: |
|
627 | 627 | |
|
628 | 628 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
629 | 629 | |
|
630 | 630 | In [3]: who_ls |
|
631 | 631 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
632 | 632 | |
|
633 | 633 | In [4]: %reset_selective -f b[2-3]m |
|
634 | 634 | |
|
635 | 635 | In [5]: who_ls |
|
636 | 636 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
637 | 637 | |
|
638 | 638 | In [6]: %reset_selective -f d |
|
639 | 639 | |
|
640 | 640 | In [7]: who_ls |
|
641 | 641 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
642 | 642 | |
|
643 | 643 | In [8]: %reset_selective -f c |
|
644 | 644 | |
|
645 | 645 | In [9]: who_ls |
|
646 | 646 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
647 | 647 | |
|
648 | 648 | In [10]: %reset_selective -f b |
|
649 | 649 | |
|
650 | 650 | In [11]: who_ls |
|
651 | 651 | Out[11]: ['a'] |
|
652 | 652 | |
|
653 | 653 | Notes |
|
654 | 654 | ----- |
|
655 | 655 | Calling this magic from clients that do not implement standard input, |
|
656 | 656 | such as the ipython notebook interface, will reset the namespace |
|
657 | 657 | without confirmation. |
|
658 | 658 | """ |
|
659 | 659 | |
|
660 | 660 | opts, regex = self.parse_options(parameter_s,'f') |
|
661 | 661 | |
|
662 | 662 | if 'f' in opts: |
|
663 | 663 | ans = True |
|
664 | 664 | else: |
|
665 | 665 | try: |
|
666 | 666 | ans = self.shell.ask_yes_no( |
|
667 | 667 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
668 | 668 | default='n') |
|
669 | 669 | except StdinNotImplementedError: |
|
670 | 670 | ans = True |
|
671 | 671 | if not ans: |
|
672 | 672 | print 'Nothing done.' |
|
673 | 673 | return |
|
674 | 674 | user_ns = self.shell.user_ns |
|
675 | 675 | if not regex: |
|
676 | 676 | print 'No regex pattern specified. Nothing done.' |
|
677 | 677 | return |
|
678 | 678 | else: |
|
679 | 679 | try: |
|
680 | 680 | m = re.compile(regex) |
|
681 | 681 | except TypeError: |
|
682 | 682 | raise TypeError('regex must be a string or compiled pattern') |
|
683 | 683 | for i in self.who_ls(): |
|
684 | 684 | if m.search(i): |
|
685 | 685 | del(user_ns[i]) |
|
686 | 686 | |
|
687 | 687 | @line_magic |
|
688 | 688 | def xdel(self, parameter_s=''): |
|
689 | 689 | """Delete a variable, trying to clear it from anywhere that |
|
690 | 690 | IPython's machinery has references to it. By default, this uses |
|
691 | 691 | the identity of the named object in the user namespace to remove |
|
692 | 692 | references held under other names. The object is also removed |
|
693 | 693 | from the output history. |
|
694 | 694 | |
|
695 | 695 | Options |
|
696 | 696 | -n : Delete the specified name from all namespaces, without |
|
697 | 697 | checking their identity. |
|
698 | 698 | """ |
|
699 | 699 | opts, varname = self.parse_options(parameter_s,'n') |
|
700 | 700 | try: |
|
701 | 701 | self.shell.del_var(varname, ('n' in opts)) |
|
702 | 702 | except (NameError, ValueError) as e: |
|
703 | 703 | print type(e).__name__ +": "+ str(e) |
@@ -1,873 +1,873 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 | from __future__ import print_function |
|
17 | 17 | |
|
18 | 18 | __all__ = ['Inspector','InspectColors'] |
|
19 | 19 | |
|
20 | 20 | # stdlib modules |
|
21 | 21 | import __builtin__ |
|
22 | 22 | import inspect |
|
23 | 23 | import linecache |
|
24 | 24 | import os |
|
25 | 25 | import sys |
|
26 | 26 | import types |
|
27 | 27 | import io as stdlib_io |
|
28 | 28 | |
|
29 | 29 | from collections import namedtuple |
|
30 | 30 | try: |
|
31 | 31 | from itertools import izip_longest |
|
32 | 32 | except ImportError: |
|
33 | 33 | from itertools import zip_longest as izip_longest |
|
34 | 34 | |
|
35 | 35 | # IPython's own |
|
36 | 36 | from IPython.core import page |
|
37 | 37 | from IPython.testing.skipdoctest import skip_doctest_py3 |
|
38 | 38 | from IPython.utils import PyColorize |
|
39 | 39 | from IPython.utils import io |
|
40 | 40 | from IPython.utils import openpy |
|
41 | 41 | from IPython.utils import py3compat |
|
42 | 42 | from IPython.utils.text import indent |
|
43 | 43 | from IPython.utils.wildcard import list_namespace |
|
44 | 44 | from IPython.utils.coloransi import * |
|
45 | 45 | from IPython.utils.py3compat import cast_unicode |
|
46 | 46 | |
|
47 | 47 | #**************************************************************************** |
|
48 | 48 | # Builtin color schemes |
|
49 | 49 | |
|
50 | 50 | Colors = TermColors # just a shorthand |
|
51 | 51 | |
|
52 | 52 | # Build a few color schemes |
|
53 | 53 | NoColor = ColorScheme( |
|
54 | 54 | 'NoColor',{ |
|
55 | 55 | 'header' : Colors.NoColor, |
|
56 | 56 | 'normal' : Colors.NoColor # color off (usu. Colors.Normal) |
|
57 | 57 | } ) |
|
58 | 58 | |
|
59 | 59 | LinuxColors = ColorScheme( |
|
60 | 60 | 'Linux',{ |
|
61 | 61 | 'header' : Colors.LightRed, |
|
62 | 62 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
63 | 63 | } ) |
|
64 | 64 | |
|
65 | 65 | LightBGColors = ColorScheme( |
|
66 | 66 | 'LightBG',{ |
|
67 | 67 | 'header' : Colors.Red, |
|
68 | 68 | 'normal' : Colors.Normal # color off (usu. Colors.Normal) |
|
69 | 69 | } ) |
|
70 | 70 | |
|
71 | 71 | # Build table of color schemes (needed by the parser) |
|
72 | 72 | InspectColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors], |
|
73 | 73 | 'Linux') |
|
74 | 74 | |
|
75 | 75 | #**************************************************************************** |
|
76 | 76 | # Auxiliary functions and objects |
|
77 | 77 | |
|
78 | 78 | # See the messaging spec for the definition of all these fields. This list |
|
79 | 79 | # effectively defines the order of display |
|
80 | 80 | info_fields = ['type_name', 'base_class', 'string_form', 'namespace', |
|
81 | 81 | 'length', 'file', 'definition', 'docstring', 'source', |
|
82 | 82 | 'init_definition', 'class_docstring', 'init_docstring', |
|
83 | 83 | 'call_def', 'call_docstring', |
|
84 | 84 | # These won't be printed but will be used to determine how to |
|
85 | 85 | # format the object |
|
86 | 86 | 'ismagic', 'isalias', 'isclass', 'argspec', 'found', 'name' |
|
87 | 87 | ] |
|
88 | 88 | |
|
89 | 89 | |
|
90 | 90 | def object_info(**kw): |
|
91 | 91 | """Make an object info dict with all fields present.""" |
|
92 | 92 | infodict = dict(izip_longest(info_fields, [None])) |
|
93 | 93 | infodict.update(kw) |
|
94 | 94 | return infodict |
|
95 | 95 | |
|
96 | 96 | |
|
97 | 97 | def get_encoding(obj): |
|
98 | 98 | """Get encoding for python source file defining obj |
|
99 | 99 | |
|
100 | 100 | Returns None if obj is not defined in a sourcefile. |
|
101 | 101 | """ |
|
102 | 102 | ofile = find_file(obj) |
|
103 | 103 | # run contents of file through pager starting at line where the object |
|
104 | 104 | # is defined, as long as the file isn't binary and is actually on the |
|
105 | 105 | # filesystem. |
|
106 | 106 | if ofile is None: |
|
107 | 107 | return None |
|
108 | 108 | elif ofile.endswith(('.so', '.dll', '.pyd')): |
|
109 | 109 | return None |
|
110 | 110 | elif not os.path.isfile(ofile): |
|
111 | 111 | return None |
|
112 | 112 | else: |
|
113 | 113 | # Print only text files, not extension binaries. Note that |
|
114 | 114 | # getsourcelines returns lineno with 1-offset and page() uses |
|
115 | 115 | # 0-offset, so we must adjust. |
|
116 | 116 | buffer = stdlib_io.open(ofile, 'rb') # Tweaked to use io.open for Python 2 |
|
117 | 117 | encoding, lines = openpy.detect_encoding(buffer.readline) |
|
118 | 118 | return encoding |
|
119 | 119 | |
|
120 | 120 | def getdoc(obj): |
|
121 | 121 | """Stable wrapper around inspect.getdoc. |
|
122 | 122 | |
|
123 | 123 | This can't crash because of attribute problems. |
|
124 | 124 | |
|
125 | 125 | It also attempts to call a getdoc() method on the given object. This |
|
126 | 126 | allows objects which provide their docstrings via non-standard mechanisms |
|
127 | 127 | (like Pyro proxies) to still be inspected by ipython's ? system.""" |
|
128 | 128 | # Allow objects to offer customized documentation via a getdoc method: |
|
129 | 129 | try: |
|
130 | 130 | ds = obj.getdoc() |
|
131 | 131 | except Exception: |
|
132 | 132 | pass |
|
133 | 133 | else: |
|
134 | 134 | # if we get extra info, we add it to the normal docstring. |
|
135 | 135 | if isinstance(ds, basestring): |
|
136 | 136 | return inspect.cleandoc(ds) |
|
137 | 137 | |
|
138 | 138 | try: |
|
139 | 139 | docstr = inspect.getdoc(obj) |
|
140 | 140 | encoding = get_encoding(obj) |
|
141 | 141 | return py3compat.cast_unicode(docstr, encoding=encoding) |
|
142 | 142 | except Exception: |
|
143 | 143 | # Harden against an inspect failure, which can occur with |
|
144 | 144 | # SWIG-wrapped extensions. |
|
145 | 145 | raise |
|
146 | 146 | return None |
|
147 | 147 | |
|
148 | 148 | |
|
149 | 149 | def getsource(obj,is_binary=False): |
|
150 | 150 | """Wrapper around inspect.getsource. |
|
151 | 151 | |
|
152 | 152 | This can be modified by other projects to provide customized source |
|
153 | 153 | extraction. |
|
154 | 154 | |
|
155 | 155 | Inputs: |
|
156 | 156 | |
|
157 | 157 | - obj: an object whose source code we will attempt to extract. |
|
158 | 158 | |
|
159 | 159 | Optional inputs: |
|
160 | 160 | |
|
161 | 161 | - is_binary: whether the object is known to come from a binary source. |
|
162 | 162 | This implementation will skip returning any output for binary objects, but |
|
163 | 163 | custom extractors may know how to meaningfully process them.""" |
|
164 | 164 | |
|
165 | 165 | if is_binary: |
|
166 | 166 | return None |
|
167 | 167 | else: |
|
168 | 168 | # get source if obj was decorated with @decorator |
|
169 | 169 | if hasattr(obj,"__wrapped__"): |
|
170 | 170 | obj = obj.__wrapped__ |
|
171 | 171 | try: |
|
172 | 172 | src = inspect.getsource(obj) |
|
173 | 173 | except TypeError: |
|
174 | 174 | if hasattr(obj,'__class__'): |
|
175 | 175 | src = inspect.getsource(obj.__class__) |
|
176 | 176 | encoding = get_encoding(obj) |
|
177 | 177 | return cast_unicode(src, encoding=encoding) |
|
178 | 178 | |
|
179 | 179 | def getargspec(obj): |
|
180 | 180 | """Get the names and default values of a function's arguments. |
|
181 | 181 | |
|
182 | 182 | A tuple of four things is returned: (args, varargs, varkw, defaults). |
|
183 | 183 | 'args' is a list of the argument names (it may contain nested lists). |
|
184 | 184 | 'varargs' and 'varkw' are the names of the * and ** arguments or None. |
|
185 | 185 | 'defaults' is an n-tuple of the default values of the last n arguments. |
|
186 | 186 | |
|
187 | 187 | Modified version of inspect.getargspec from the Python Standard |
|
188 | 188 | Library.""" |
|
189 | 189 | |
|
190 | 190 | if inspect.isfunction(obj): |
|
191 | 191 | func_obj = obj |
|
192 | 192 | elif inspect.ismethod(obj): |
|
193 | 193 | func_obj = obj.im_func |
|
194 | 194 | elif hasattr(obj, '__call__'): |
|
195 | 195 | func_obj = obj.__call__ |
|
196 | 196 | else: |
|
197 | 197 | raise TypeError('arg is not a Python function') |
|
198 | 198 | args, varargs, varkw = inspect.getargs(func_obj.func_code) |
|
199 | 199 | return args, varargs, varkw, func_obj.func_defaults |
|
200 | 200 | |
|
201 | 201 | |
|
202 | 202 | def format_argspec(argspec): |
|
203 | 203 | """Format argspect, convenience wrapper around inspect's. |
|
204 | 204 | |
|
205 | 205 | This takes a dict instead of ordered arguments and calls |
|
206 | 206 | inspect.format_argspec with the arguments in the necessary order. |
|
207 | 207 | """ |
|
208 | 208 | return inspect.formatargspec(argspec['args'], argspec['varargs'], |
|
209 | 209 | argspec['varkw'], argspec['defaults']) |
|
210 | 210 | |
|
211 | 211 | |
|
212 | 212 | def call_tip(oinfo, format_call=True): |
|
213 | 213 | """Extract call tip data from an oinfo dict. |
|
214 | 214 | |
|
215 | 215 | Parameters |
|
216 | 216 | ---------- |
|
217 | 217 | oinfo : dict |
|
218 | 218 | |
|
219 | 219 | format_call : bool, optional |
|
220 | 220 | If True, the call line is formatted and returned as a string. If not, a |
|
221 | 221 | tuple of (name, argspec) is returned. |
|
222 | 222 | |
|
223 | 223 | Returns |
|
224 | 224 | ------- |
|
225 | 225 | call_info : None, str or (str, dict) tuple. |
|
226 | 226 | When format_call is True, the whole call information is formattted as a |
|
227 | 227 | single string. Otherwise, the object's name and its argspec dict are |
|
228 | 228 | returned. If no call information is available, None is returned. |
|
229 | 229 | |
|
230 | 230 | docstring : str or None |
|
231 | 231 | The most relevant docstring for calling purposes is returned, if |
|
232 | 232 | available. The priority is: call docstring for callable instances, then |
|
233 | 233 | constructor docstring for classes, then main object's docstring otherwise |
|
234 | 234 | (regular functions). |
|
235 | 235 | """ |
|
236 | 236 | # Get call definition |
|
237 | 237 | argspec = oinfo.get('argspec') |
|
238 | 238 | if argspec is None: |
|
239 | 239 | call_line = None |
|
240 | 240 | else: |
|
241 | 241 | # Callable objects will have 'self' as their first argument, prune |
|
242 | 242 | # it out if it's there for clarity (since users do *not* pass an |
|
243 | 243 | # extra first argument explicitly). |
|
244 | 244 | try: |
|
245 | 245 | has_self = argspec['args'][0] == 'self' |
|
246 | 246 | except (KeyError, IndexError): |
|
247 | 247 | pass |
|
248 | 248 | else: |
|
249 | 249 | if has_self: |
|
250 | 250 | argspec['args'] = argspec['args'][1:] |
|
251 | 251 | |
|
252 | 252 | call_line = oinfo['name']+format_argspec(argspec) |
|
253 | 253 | |
|
254 | 254 | # Now get docstring. |
|
255 | 255 | # The priority is: call docstring, constructor docstring, main one. |
|
256 | 256 | doc = oinfo.get('call_docstring') |
|
257 | 257 | if doc is None: |
|
258 | 258 | doc = oinfo.get('init_docstring') |
|
259 | 259 | if doc is None: |
|
260 | 260 | doc = oinfo.get('docstring','') |
|
261 | 261 | |
|
262 | 262 | return call_line, doc |
|
263 | 263 | |
|
264 | 264 | |
|
265 | 265 | def find_file(obj): |
|
266 | 266 | """Find the absolute path to the file where an object was defined. |
|
267 | 267 | |
|
268 | 268 | This is essentially a robust wrapper around `inspect.getabsfile`. |
|
269 | 269 | |
|
270 | 270 | Returns None if no file can be found. |
|
271 | 271 | |
|
272 | 272 | Parameters |
|
273 | 273 | ---------- |
|
274 | 274 | obj : any Python object |
|
275 | 275 | |
|
276 | 276 | Returns |
|
277 | 277 | ------- |
|
278 | 278 | fname : str |
|
279 | 279 | The absolute path to the file where the object was defined. |
|
280 | 280 | """ |
|
281 | 281 | # get source if obj was decorated with @decorator |
|
282 | 282 | if hasattr(obj, '__wrapped__'): |
|
283 | 283 | obj = obj.__wrapped__ |
|
284 | 284 | |
|
285 | 285 | fname = None |
|
286 | 286 | try: |
|
287 | 287 | fname = inspect.getabsfile(obj) |
|
288 | 288 | except TypeError: |
|
289 | 289 | # For an instance, the file that matters is where its class was |
|
290 | 290 | # declared. |
|
291 | 291 | if hasattr(obj, '__class__'): |
|
292 | 292 | try: |
|
293 | 293 | fname = inspect.getabsfile(obj.__class__) |
|
294 | 294 | except TypeError: |
|
295 | 295 | # Can happen for builtins |
|
296 | 296 | pass |
|
297 | 297 | except: |
|
298 | 298 | pass |
|
299 | 299 | return fname |
|
300 | 300 | |
|
301 | 301 | |
|
302 | 302 | def find_source_lines(obj): |
|
303 | 303 | """Find the line number in a file where an object was defined. |
|
304 | 304 | |
|
305 | 305 | This is essentially a robust wrapper around `inspect.getsourcelines`. |
|
306 | 306 | |
|
307 | 307 | Returns None if no file can be found. |
|
308 | 308 | |
|
309 | 309 | Parameters |
|
310 | 310 | ---------- |
|
311 | 311 | obj : any Python object |
|
312 | 312 | |
|
313 | 313 | Returns |
|
314 | 314 | ------- |
|
315 | 315 | lineno : int |
|
316 | 316 | The line number where the object definition starts. |
|
317 | 317 | """ |
|
318 | 318 | # get source if obj was decorated with @decorator |
|
319 | 319 | if hasattr(obj, '__wrapped__'): |
|
320 | 320 | obj = obj.__wrapped__ |
|
321 | 321 | |
|
322 | 322 | try: |
|
323 | 323 | try: |
|
324 | 324 | lineno = inspect.getsourcelines(obj)[1] |
|
325 | 325 | except TypeError: |
|
326 | 326 | # For instances, try the class object like getsource() does |
|
327 | 327 | if hasattr(obj, '__class__'): |
|
328 | 328 | lineno = inspect.getsourcelines(obj.__class__)[1] |
|
329 | 329 | except: |
|
330 | 330 | return None |
|
331 | 331 | |
|
332 | 332 | return lineno |
|
333 | 333 | |
|
334 | 334 | |
|
335 | 335 | class Inspector: |
|
336 | 336 | def __init__(self, color_table=InspectColors, |
|
337 | 337 | code_color_table=PyColorize.ANSICodeColors, |
|
338 | 338 | scheme='NoColor', |
|
339 | 339 | str_detail_level=0): |
|
340 | 340 | self.color_table = color_table |
|
341 | 341 | self.parser = PyColorize.Parser(code_color_table,out='str') |
|
342 | 342 | self.format = self.parser.format |
|
343 | 343 | self.str_detail_level = str_detail_level |
|
344 | 344 | self.set_active_scheme(scheme) |
|
345 | 345 | |
|
346 | 346 | def _getdef(self,obj,oname=''): |
|
347 |
"""Return the |
|
|
347 | """Return the call signature for any callable object. | |
|
348 | 348 | |
|
349 | 349 | If any exception is generated, None is returned instead and the |
|
350 | 350 | exception is suppressed.""" |
|
351 | 351 | |
|
352 | 352 | try: |
|
353 | 353 | hdef = oname + inspect.formatargspec(*getargspec(obj)) |
|
354 | 354 | return cast_unicode(hdef) |
|
355 | 355 | except: |
|
356 | 356 | return None |
|
357 | 357 | |
|
358 | 358 | def __head(self,h): |
|
359 | 359 | """Return a header string with proper colors.""" |
|
360 | 360 | return '%s%s%s' % (self.color_table.active_colors.header,h, |
|
361 | 361 | self.color_table.active_colors.normal) |
|
362 | 362 | |
|
363 | 363 | def set_active_scheme(self, scheme): |
|
364 | 364 | self.color_table.set_active_scheme(scheme) |
|
365 | 365 | self.parser.color_table.set_active_scheme(scheme) |
|
366 | 366 | |
|
367 | 367 | def noinfo(self, msg, oname): |
|
368 | 368 | """Generic message when no information is found.""" |
|
369 | 369 | print('No %s found' % msg, end=' ') |
|
370 | 370 | if oname: |
|
371 | 371 | print('for %s' % oname) |
|
372 | 372 | else: |
|
373 | 373 | print() |
|
374 | 374 | |
|
375 | 375 | def pdef(self, obj, oname=''): |
|
376 |
"""Print the |
|
|
376 | """Print the call signature for any callable object. | |
|
377 | 377 | |
|
378 | 378 | If the object is a class, print the constructor information.""" |
|
379 | 379 | |
|
380 | 380 | if not callable(obj): |
|
381 | 381 | print('Object is not callable.') |
|
382 | 382 | return |
|
383 | 383 | |
|
384 | 384 | header = '' |
|
385 | 385 | |
|
386 | 386 | if inspect.isclass(obj): |
|
387 | 387 | header = self.__head('Class constructor information:\n') |
|
388 | 388 | obj = obj.__init__ |
|
389 | 389 | elif (not py3compat.PY3) and type(obj) is types.InstanceType: |
|
390 | 390 | obj = obj.__call__ |
|
391 | 391 | |
|
392 | 392 | output = self._getdef(obj,oname) |
|
393 | 393 | if output is None: |
|
394 | 394 | self.noinfo('definition header',oname) |
|
395 | 395 | else: |
|
396 | 396 | print(header,self.format(output), end=' ', file=io.stdout) |
|
397 | 397 | |
|
398 | 398 | # In Python 3, all classes are new-style, so they all have __init__. |
|
399 | 399 | @skip_doctest_py3 |
|
400 | 400 | def pdoc(self,obj,oname='',formatter = None): |
|
401 | 401 | """Print the docstring for any object. |
|
402 | 402 | |
|
403 | 403 | Optional: |
|
404 | 404 | -formatter: a function to run the docstring through for specially |
|
405 | 405 | formatted docstrings. |
|
406 | 406 | |
|
407 | 407 | Examples |
|
408 | 408 | -------- |
|
409 | 409 | |
|
410 | 410 | In [1]: class NoInit: |
|
411 | 411 | ...: pass |
|
412 | 412 | |
|
413 | 413 | In [2]: class NoDoc: |
|
414 | 414 | ...: def __init__(self): |
|
415 | 415 | ...: pass |
|
416 | 416 | |
|
417 | 417 | In [3]: %pdoc NoDoc |
|
418 | 418 | No documentation found for NoDoc |
|
419 | 419 | |
|
420 | 420 | In [4]: %pdoc NoInit |
|
421 | 421 | No documentation found for NoInit |
|
422 | 422 | |
|
423 | 423 | In [5]: obj = NoInit() |
|
424 | 424 | |
|
425 | 425 | In [6]: %pdoc obj |
|
426 | 426 | No documentation found for obj |
|
427 | 427 | |
|
428 | 428 | In [5]: obj2 = NoDoc() |
|
429 | 429 | |
|
430 | 430 | In [6]: %pdoc obj2 |
|
431 | 431 | No documentation found for obj2 |
|
432 | 432 | """ |
|
433 | 433 | |
|
434 | 434 | head = self.__head # For convenience |
|
435 | 435 | lines = [] |
|
436 | 436 | ds = getdoc(obj) |
|
437 | 437 | if formatter: |
|
438 | 438 | ds = formatter(ds) |
|
439 | 439 | if ds: |
|
440 | 440 | lines.append(head("Class Docstring:")) |
|
441 | 441 | lines.append(indent(ds)) |
|
442 | 442 | if inspect.isclass(obj) and hasattr(obj, '__init__'): |
|
443 | 443 | init_ds = getdoc(obj.__init__) |
|
444 | 444 | if init_ds is not None: |
|
445 | 445 | lines.append(head("Constructor Docstring:")) |
|
446 | 446 | lines.append(indent(init_ds)) |
|
447 | 447 | elif hasattr(obj,'__call__'): |
|
448 | 448 | call_ds = getdoc(obj.__call__) |
|
449 | 449 | if call_ds: |
|
450 | 450 | lines.append(head("Calling Docstring:")) |
|
451 | 451 | lines.append(indent(call_ds)) |
|
452 | 452 | |
|
453 | 453 | if not lines: |
|
454 | 454 | self.noinfo('documentation',oname) |
|
455 | 455 | else: |
|
456 | 456 | page.page('\n'.join(lines)) |
|
457 | 457 | |
|
458 | 458 | def psource(self,obj,oname=''): |
|
459 | 459 | """Print the source code for an object.""" |
|
460 | 460 | |
|
461 | 461 | # Flush the source cache because inspect can return out-of-date source |
|
462 | 462 | linecache.checkcache() |
|
463 | 463 | try: |
|
464 | 464 | src = getsource(obj) |
|
465 | 465 | except: |
|
466 | 466 | self.noinfo('source',oname) |
|
467 | 467 | else: |
|
468 | 468 | page.page(self.format(src)) |
|
469 | 469 | |
|
470 | 470 | def pfile(self, obj, oname=''): |
|
471 | 471 | """Show the whole file where an object was defined.""" |
|
472 | 472 | |
|
473 | 473 | lineno = find_source_lines(obj) |
|
474 | 474 | if lineno is None: |
|
475 | 475 | self.noinfo('file', oname) |
|
476 | 476 | return |
|
477 | 477 | |
|
478 | 478 | ofile = find_file(obj) |
|
479 | 479 | # run contents of file through pager starting at line where the object |
|
480 | 480 | # is defined, as long as the file isn't binary and is actually on the |
|
481 | 481 | # filesystem. |
|
482 | 482 | if ofile.endswith(('.so', '.dll', '.pyd')): |
|
483 | 483 | print('File %r is binary, not printing.' % ofile) |
|
484 | 484 | elif not os.path.isfile(ofile): |
|
485 | 485 | print('File %r does not exist, not printing.' % ofile) |
|
486 | 486 | else: |
|
487 | 487 | # Print only text files, not extension binaries. Note that |
|
488 | 488 | # getsourcelines returns lineno with 1-offset and page() uses |
|
489 | 489 | # 0-offset, so we must adjust. |
|
490 | 490 | page.page(self.format(openpy.read_py_file(ofile, skip_encoding_cookie=False)), lineno - 1) |
|
491 | 491 | |
|
492 | 492 | def _format_fields(self, fields, title_width=12): |
|
493 | 493 | """Formats a list of fields for display. |
|
494 | 494 | |
|
495 | 495 | Parameters |
|
496 | 496 | ---------- |
|
497 | 497 | fields : list |
|
498 | 498 | A list of 2-tuples: (field_title, field_content) |
|
499 | 499 | title_width : int |
|
500 | 500 | How many characters to pad titles to. Default 12. |
|
501 | 501 | """ |
|
502 | 502 | out = [] |
|
503 | 503 | header = self.__head |
|
504 | 504 | for title, content in fields: |
|
505 | 505 | if len(content.splitlines()) > 1: |
|
506 | 506 | title = header(title + ":") + "\n" |
|
507 | 507 | else: |
|
508 | 508 | title = header((title+":").ljust(title_width)) |
|
509 | 509 | out.append(cast_unicode(title) + cast_unicode(content)) |
|
510 | 510 | return "\n".join(out) |
|
511 | 511 | |
|
512 | 512 | # The fields to be displayed by pinfo: (fancy_name, key_in_info_dict) |
|
513 | 513 | pinfo_fields1 = [("Type", "type_name"), |
|
514 | 514 | ] |
|
515 | 515 | |
|
516 | 516 | pinfo_fields2 = [("String Form", "string_form"), |
|
517 | 517 | ] |
|
518 | 518 | |
|
519 | 519 | pinfo_fields3 = [("Length", "length"), |
|
520 | 520 | ("File", "file"), |
|
521 | 521 | ("Definition", "definition"), |
|
522 | 522 | ] |
|
523 | 523 | |
|
524 | 524 | pinfo_fields_obj = [("Class Docstring", "class_docstring"), |
|
525 | 525 | ("Constructor Docstring","init_docstring"), |
|
526 | 526 | ("Call def", "call_def"), |
|
527 | 527 | ("Call docstring", "call_docstring")] |
|
528 | 528 | |
|
529 | 529 | def pinfo(self,obj,oname='',formatter=None,info=None,detail_level=0): |
|
530 | 530 | """Show detailed information about an object. |
|
531 | 531 | |
|
532 | 532 | Optional arguments: |
|
533 | 533 | |
|
534 | 534 | - oname: name of the variable pointing to the object. |
|
535 | 535 | |
|
536 | 536 | - formatter: special formatter for docstrings (see pdoc) |
|
537 | 537 | |
|
538 | 538 | - info: a structure with some information fields which may have been |
|
539 | 539 | precomputed already. |
|
540 | 540 | |
|
541 | 541 | - detail_level: if set to 1, more information is given. |
|
542 | 542 | """ |
|
543 | 543 | info = self.info(obj, oname=oname, formatter=formatter, |
|
544 | 544 | info=info, detail_level=detail_level) |
|
545 | 545 | displayfields = [] |
|
546 | 546 | def add_fields(fields): |
|
547 | 547 | for title, key in fields: |
|
548 | 548 | field = info[key] |
|
549 | 549 | if field is not None: |
|
550 | 550 | displayfields.append((title, field.rstrip())) |
|
551 | 551 | |
|
552 | 552 | add_fields(self.pinfo_fields1) |
|
553 | 553 | |
|
554 | 554 | # Base class for old-style instances |
|
555 | 555 | if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']: |
|
556 | 556 | displayfields.append(("Base Class", info['base_class'].rstrip())) |
|
557 | 557 | |
|
558 | 558 | add_fields(self.pinfo_fields2) |
|
559 | 559 | |
|
560 | 560 | # Namespace |
|
561 | 561 | if info['namespace'] != 'Interactive': |
|
562 | 562 | displayfields.append(("Namespace", info['namespace'].rstrip())) |
|
563 | 563 | |
|
564 | 564 | add_fields(self.pinfo_fields3) |
|
565 | 565 | |
|
566 | 566 | # Source or docstring, depending on detail level and whether |
|
567 | 567 | # source found. |
|
568 | 568 | if detail_level > 0 and info['source'] is not None: |
|
569 | 569 | displayfields.append(("Source", |
|
570 | 570 | self.format(cast_unicode(info['source'])))) |
|
571 | 571 | elif info['docstring'] is not None: |
|
572 | 572 | displayfields.append(("Docstring", info["docstring"])) |
|
573 | 573 | |
|
574 | 574 | # Constructor info for classes |
|
575 | 575 | if info['isclass']: |
|
576 | 576 | if info['init_definition'] or info['init_docstring']: |
|
577 | 577 | displayfields.append(("Constructor information", "")) |
|
578 | 578 | if info['init_definition'] is not None: |
|
579 | 579 | displayfields.append((" Definition", |
|
580 | 580 | info['init_definition'].rstrip())) |
|
581 | 581 | if info['init_docstring'] is not None: |
|
582 | 582 | displayfields.append((" Docstring", |
|
583 | 583 | indent(info['init_docstring']))) |
|
584 | 584 | |
|
585 | 585 | # Info for objects: |
|
586 | 586 | else: |
|
587 | 587 | add_fields(self.pinfo_fields_obj) |
|
588 | 588 | |
|
589 | 589 | # Finally send to printer/pager: |
|
590 | 590 | if displayfields: |
|
591 | 591 | page.page(self._format_fields(displayfields)) |
|
592 | 592 | |
|
593 | 593 | def info(self, obj, oname='', formatter=None, info=None, detail_level=0): |
|
594 | 594 | """Compute a dict with detailed information about an object. |
|
595 | 595 | |
|
596 | 596 | Optional arguments: |
|
597 | 597 | |
|
598 | 598 | - oname: name of the variable pointing to the object. |
|
599 | 599 | |
|
600 | 600 | - formatter: special formatter for docstrings (see pdoc) |
|
601 | 601 | |
|
602 | 602 | - info: a structure with some information fields which may have been |
|
603 | 603 | precomputed already. |
|
604 | 604 | |
|
605 | 605 | - detail_level: if set to 1, more information is given. |
|
606 | 606 | """ |
|
607 | 607 | |
|
608 | 608 | obj_type = type(obj) |
|
609 | 609 | |
|
610 | 610 | header = self.__head |
|
611 | 611 | if info is None: |
|
612 | 612 | ismagic = 0 |
|
613 | 613 | isalias = 0 |
|
614 | 614 | ospace = '' |
|
615 | 615 | else: |
|
616 | 616 | ismagic = info.ismagic |
|
617 | 617 | isalias = info.isalias |
|
618 | 618 | ospace = info.namespace |
|
619 | 619 | |
|
620 | 620 | # Get docstring, special-casing aliases: |
|
621 | 621 | if isalias: |
|
622 | 622 | if not callable(obj): |
|
623 | 623 | try: |
|
624 | 624 | ds = "Alias to the system command:\n %s" % obj[1] |
|
625 | 625 | except: |
|
626 | 626 | ds = "Alias: " + str(obj) |
|
627 | 627 | else: |
|
628 | 628 | ds = "Alias to " + str(obj) |
|
629 | 629 | if obj.__doc__: |
|
630 | 630 | ds += "\nDocstring:\n" + obj.__doc__ |
|
631 | 631 | else: |
|
632 | 632 | ds = getdoc(obj) |
|
633 | 633 | if ds is None: |
|
634 | 634 | ds = '<no docstring>' |
|
635 | 635 | if formatter is not None: |
|
636 | 636 | ds = formatter(ds) |
|
637 | 637 | |
|
638 | 638 | # store output in a dict, we initialize it here and fill it as we go |
|
639 | 639 | out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic) |
|
640 | 640 | |
|
641 | 641 | string_max = 200 # max size of strings to show (snipped if longer) |
|
642 | 642 | shalf = int((string_max -5)/2) |
|
643 | 643 | |
|
644 | 644 | if ismagic: |
|
645 | 645 | obj_type_name = 'Magic function' |
|
646 | 646 | elif isalias: |
|
647 | 647 | obj_type_name = 'System alias' |
|
648 | 648 | else: |
|
649 | 649 | obj_type_name = obj_type.__name__ |
|
650 | 650 | out['type_name'] = obj_type_name |
|
651 | 651 | |
|
652 | 652 | try: |
|
653 | 653 | bclass = obj.__class__ |
|
654 | 654 | out['base_class'] = str(bclass) |
|
655 | 655 | except: pass |
|
656 | 656 | |
|
657 | 657 | # String form, but snip if too long in ? form (full in ??) |
|
658 | 658 | if detail_level >= self.str_detail_level: |
|
659 | 659 | try: |
|
660 | 660 | ostr = str(obj) |
|
661 | 661 | str_head = 'string_form' |
|
662 | 662 | if not detail_level and len(ostr)>string_max: |
|
663 | 663 | ostr = ostr[:shalf] + ' <...> ' + ostr[-shalf:] |
|
664 | 664 | ostr = ("\n" + " " * len(str_head.expandtabs())).\ |
|
665 | 665 | join(q.strip() for q in ostr.split("\n")) |
|
666 | 666 | out[str_head] = ostr |
|
667 | 667 | except: |
|
668 | 668 | pass |
|
669 | 669 | |
|
670 | 670 | if ospace: |
|
671 | 671 | out['namespace'] = ospace |
|
672 | 672 | |
|
673 | 673 | # Length (for strings and lists) |
|
674 | 674 | try: |
|
675 | 675 | out['length'] = str(len(obj)) |
|
676 | 676 | except: pass |
|
677 | 677 | |
|
678 | 678 | # Filename where object was defined |
|
679 | 679 | binary_file = False |
|
680 | 680 | fname = find_file(obj) |
|
681 | 681 | if fname is None: |
|
682 | 682 | # if anything goes wrong, we don't want to show source, so it's as |
|
683 | 683 | # if the file was binary |
|
684 | 684 | binary_file = True |
|
685 | 685 | else: |
|
686 | 686 | if fname.endswith(('.so', '.dll', '.pyd')): |
|
687 | 687 | binary_file = True |
|
688 | 688 | elif fname.endswith('<string>'): |
|
689 | 689 | fname = 'Dynamically generated function. No source code available.' |
|
690 | 690 | out['file'] = fname |
|
691 | 691 | |
|
692 | 692 | # reconstruct the function definition and print it: |
|
693 | 693 | defln = self._getdef(obj, oname) |
|
694 | 694 | if defln: |
|
695 | 695 | out['definition'] = self.format(defln) |
|
696 | 696 | |
|
697 | 697 | # Docstrings only in detail 0 mode, since source contains them (we |
|
698 | 698 | # avoid repetitions). If source fails, we add them back, see below. |
|
699 | 699 | if ds and detail_level == 0: |
|
700 | 700 | out['docstring'] = ds |
|
701 | 701 | |
|
702 | 702 | # Original source code for any callable |
|
703 | 703 | if detail_level: |
|
704 | 704 | # Flush the source cache because inspect can return out-of-date |
|
705 | 705 | # source |
|
706 | 706 | linecache.checkcache() |
|
707 | 707 | source = None |
|
708 | 708 | try: |
|
709 | 709 | try: |
|
710 | 710 | source = getsource(obj, binary_file) |
|
711 | 711 | except TypeError: |
|
712 | 712 | if hasattr(obj, '__class__'): |
|
713 | 713 | source = getsource(obj.__class__, binary_file) |
|
714 | 714 | if source is not None: |
|
715 | 715 | out['source'] = source.rstrip() |
|
716 | 716 | except Exception: |
|
717 | 717 | pass |
|
718 | 718 | |
|
719 | 719 | if ds and source is None: |
|
720 | 720 | out['docstring'] = ds |
|
721 | 721 | |
|
722 | 722 | |
|
723 | 723 | # Constructor docstring for classes |
|
724 | 724 | if inspect.isclass(obj): |
|
725 | 725 | out['isclass'] = True |
|
726 | 726 | # reconstruct the function definition and print it: |
|
727 | 727 | try: |
|
728 | 728 | obj_init = obj.__init__ |
|
729 | 729 | except AttributeError: |
|
730 | 730 | init_def = init_ds = None |
|
731 | 731 | else: |
|
732 | 732 | init_def = self._getdef(obj_init,oname) |
|
733 | 733 | init_ds = getdoc(obj_init) |
|
734 | 734 | # Skip Python's auto-generated docstrings |
|
735 | 735 | if init_ds and \ |
|
736 | 736 | init_ds.startswith('x.__init__(...) initializes'): |
|
737 | 737 | init_ds = None |
|
738 | 738 | |
|
739 | 739 | if init_def or init_ds: |
|
740 | 740 | if init_def: |
|
741 | 741 | out['init_definition'] = self.format(init_def) |
|
742 | 742 | if init_ds: |
|
743 | 743 | out['init_docstring'] = init_ds |
|
744 | 744 | |
|
745 | 745 | # and class docstring for instances: |
|
746 | 746 | else: |
|
747 | 747 | # First, check whether the instance docstring is identical to the |
|
748 | 748 | # class one, and print it separately if they don't coincide. In |
|
749 | 749 | # most cases they will, but it's nice to print all the info for |
|
750 | 750 | # objects which use instance-customized docstrings. |
|
751 | 751 | if ds: |
|
752 | 752 | try: |
|
753 | 753 | cls = getattr(obj,'__class__') |
|
754 | 754 | except: |
|
755 | 755 | class_ds = None |
|
756 | 756 | else: |
|
757 | 757 | class_ds = getdoc(cls) |
|
758 | 758 | # Skip Python's auto-generated docstrings |
|
759 | 759 | if class_ds and \ |
|
760 | 760 | (class_ds.startswith('function(code, globals[,') or \ |
|
761 | 761 | class_ds.startswith('instancemethod(function, instance,') or \ |
|
762 | 762 | class_ds.startswith('module(name[,') ): |
|
763 | 763 | class_ds = None |
|
764 | 764 | if class_ds and ds != class_ds: |
|
765 | 765 | out['class_docstring'] = class_ds |
|
766 | 766 | |
|
767 | 767 | # Next, try to show constructor docstrings |
|
768 | 768 | try: |
|
769 | 769 | init_ds = getdoc(obj.__init__) |
|
770 | 770 | # Skip Python's auto-generated docstrings |
|
771 | 771 | if init_ds and \ |
|
772 | 772 | init_ds.startswith('x.__init__(...) initializes'): |
|
773 | 773 | init_ds = None |
|
774 | 774 | except AttributeError: |
|
775 | 775 | init_ds = None |
|
776 | 776 | if init_ds: |
|
777 | 777 | out['init_docstring'] = init_ds |
|
778 | 778 | |
|
779 | 779 | # Call form docstring for callable instances |
|
780 | 780 | if hasattr(obj, '__call__'): |
|
781 | 781 | call_def = self._getdef(obj.__call__, oname) |
|
782 | 782 | if call_def is not None: |
|
783 | 783 | out['call_def'] = self.format(call_def) |
|
784 | 784 | call_ds = getdoc(obj.__call__) |
|
785 | 785 | # Skip Python's auto-generated docstrings |
|
786 | 786 | if call_ds and call_ds.startswith('x.__call__(...) <==> x(...)'): |
|
787 | 787 | call_ds = None |
|
788 | 788 | if call_ds: |
|
789 | 789 | out['call_docstring'] = call_ds |
|
790 | 790 | |
|
791 | 791 | # Compute the object's argspec as a callable. The key is to decide |
|
792 | 792 | # whether to pull it from the object itself, from its __init__ or |
|
793 | 793 | # from its __call__ method. |
|
794 | 794 | |
|
795 | 795 | if inspect.isclass(obj): |
|
796 | 796 | # Old-style classes need not have an __init__ |
|
797 | 797 | callable_obj = getattr(obj, "__init__", None) |
|
798 | 798 | elif callable(obj): |
|
799 | 799 | callable_obj = obj |
|
800 | 800 | else: |
|
801 | 801 | callable_obj = None |
|
802 | 802 | |
|
803 | 803 | if callable_obj: |
|
804 | 804 | try: |
|
805 | 805 | args, varargs, varkw, defaults = getargspec(callable_obj) |
|
806 | 806 | except (TypeError, AttributeError): |
|
807 | 807 | # For extensions/builtins we can't retrieve the argspec |
|
808 | 808 | pass |
|
809 | 809 | else: |
|
810 | 810 | out['argspec'] = dict(args=args, varargs=varargs, |
|
811 | 811 | varkw=varkw, defaults=defaults) |
|
812 | 812 | |
|
813 | 813 | return object_info(**out) |
|
814 | 814 | |
|
815 | 815 | |
|
816 | 816 | def psearch(self,pattern,ns_table,ns_search=[], |
|
817 | 817 | ignore_case=False,show_all=False): |
|
818 | 818 | """Search namespaces with wildcards for objects. |
|
819 | 819 | |
|
820 | 820 | Arguments: |
|
821 | 821 | |
|
822 | 822 | - pattern: string containing shell-like wildcards to use in namespace |
|
823 | 823 | searches and optionally a type specification to narrow the search to |
|
824 | 824 | objects of that type. |
|
825 | 825 | |
|
826 | 826 | - ns_table: dict of name->namespaces for search. |
|
827 | 827 | |
|
828 | 828 | Optional arguments: |
|
829 | 829 | |
|
830 | 830 | - ns_search: list of namespace names to include in search. |
|
831 | 831 | |
|
832 | 832 | - ignore_case(False): make the search case-insensitive. |
|
833 | 833 | |
|
834 | 834 | - show_all(False): show all names, including those starting with |
|
835 | 835 | underscores. |
|
836 | 836 | """ |
|
837 | 837 | #print 'ps pattern:<%r>' % pattern # dbg |
|
838 | 838 | |
|
839 | 839 | # defaults |
|
840 | 840 | type_pattern = 'all' |
|
841 | 841 | filter = '' |
|
842 | 842 | |
|
843 | 843 | cmds = pattern.split() |
|
844 | 844 | len_cmds = len(cmds) |
|
845 | 845 | if len_cmds == 1: |
|
846 | 846 | # Only filter pattern given |
|
847 | 847 | filter = cmds[0] |
|
848 | 848 | elif len_cmds == 2: |
|
849 | 849 | # Both filter and type specified |
|
850 | 850 | filter,type_pattern = cmds |
|
851 | 851 | else: |
|
852 | 852 | raise ValueError('invalid argument string for psearch: <%s>' % |
|
853 | 853 | pattern) |
|
854 | 854 | |
|
855 | 855 | # filter search namespaces |
|
856 | 856 | for name in ns_search: |
|
857 | 857 | if name not in ns_table: |
|
858 | 858 | raise ValueError('invalid namespace <%s>. Valid names: %s' % |
|
859 | 859 | (name,ns_table.keys())) |
|
860 | 860 | |
|
861 | 861 | #print 'type_pattern:',type_pattern # dbg |
|
862 | 862 | search_result, namespaces_seen = set(), set() |
|
863 | 863 | for ns_name in ns_search: |
|
864 | 864 | ns = ns_table[ns_name] |
|
865 | 865 | # Normally, locals and globals are the same, so we just check one. |
|
866 | 866 | if id(ns) in namespaces_seen: |
|
867 | 867 | continue |
|
868 | 868 | namespaces_seen.add(id(ns)) |
|
869 | 869 | tmp_res = list_namespace(ns, type_pattern, filter, |
|
870 | 870 | ignore_case=ignore_case, show_all=show_all) |
|
871 | 871 | search_result.update(tmp_res) |
|
872 | 872 | |
|
873 | 873 | page.page('\n'.join(sorted(search_result))) |
@@ -1,1150 +1,1150 b'' | |||
|
1 | 1 | ================= |
|
2 | 2 | IPython reference |
|
3 | 3 | ================= |
|
4 | 4 | |
|
5 | 5 | .. _command_line_options: |
|
6 | 6 | |
|
7 | 7 | Command-line usage |
|
8 | 8 | ================== |
|
9 | 9 | |
|
10 | 10 | You start IPython with the command:: |
|
11 | 11 | |
|
12 | 12 | $ ipython [options] files |
|
13 | 13 | |
|
14 | 14 | .. note:: |
|
15 | 15 | |
|
16 | 16 | For IPython on Python 3, use ``ipython3`` in place of ``ipython``. |
|
17 | 17 | |
|
18 | 18 | If invoked with no options, it executes all the files listed in sequence |
|
19 | 19 | and drops you into the interpreter while still acknowledging any options |
|
20 | 20 | you may have set in your ipython_config.py. This behavior is different from |
|
21 | 21 | standard Python, which when called as python -i will only execute one |
|
22 | 22 | file and ignore your configuration setup. |
|
23 | 23 | |
|
24 | 24 | Please note that some of the configuration options are not available at |
|
25 | 25 | the command line, simply because they are not practical here. Look into |
|
26 | 26 | your configuration files for details on those. There are separate configuration |
|
27 | 27 | files for each profile, and the files look like "ipython_config.py" or |
|
28 | 28 | "ipython_config_<frontendname>.py". Profile directories look like |
|
29 | 29 | "profile_profilename" and are typically installed in the IPYTHONDIR directory. |
|
30 | 30 | For Linux users, this will be $HOME/.config/ipython, and for other users it |
|
31 | 31 | will be $HOME/.ipython. For Windows users, $HOME resolves to C:\\Documents and |
|
32 | 32 | Settings\\YourUserName in most instances. |
|
33 | 33 | |
|
34 | 34 | |
|
35 | 35 | Eventloop integration |
|
36 | 36 | --------------------- |
|
37 | 37 | |
|
38 | 38 | Previously IPython had command line options for controlling GUI event loop |
|
39 | 39 | integration (-gthread, -qthread, -q4thread, -wthread, -pylab). As of IPython |
|
40 | 40 | version 0.11, these have been removed. Please see the new ``%gui`` |
|
41 | 41 | magic command or :ref:`this section <gui_support>` for details on the new |
|
42 | 42 | interface, or specify the gui at the commandline:: |
|
43 | 43 | |
|
44 | 44 | $ ipython --gui=qt |
|
45 | 45 | |
|
46 | 46 | |
|
47 | 47 | Command-line Options |
|
48 | 48 | -------------------- |
|
49 | 49 | |
|
50 | 50 | To see the options IPython accepts, use ``ipython --help`` (and you probably |
|
51 | 51 | should run the output through a pager such as ``ipython --help | less`` for |
|
52 | 52 | more convenient reading). This shows all the options that have a single-word |
|
53 | 53 | alias to control them, but IPython lets you configure all of its objects from |
|
54 | 54 | the command-line by passing the full class name and a corresponding value; type |
|
55 | 55 | ``ipython --help-all`` to see this full list. For example:: |
|
56 | 56 | |
|
57 | 57 | ipython --pylab qt |
|
58 | 58 | |
|
59 | 59 | is equivalent to:: |
|
60 | 60 | |
|
61 | 61 | ipython --TerminalIPythonApp.pylab='qt' |
|
62 | 62 | |
|
63 | 63 | Note that in the second form, you *must* use the equal sign, as the expression |
|
64 | 64 | is evaluated as an actual Python assignment. While in the above example the |
|
65 | 65 | short form is more convenient, only the most common options have a short form, |
|
66 | 66 | while any configurable variable in IPython can be set at the command-line by |
|
67 | 67 | using the long form. This long form is the same syntax used in the |
|
68 | 68 | configuration files, if you want to set these options permanently. |
|
69 | 69 | |
|
70 | 70 | |
|
71 | 71 | Interactive use |
|
72 | 72 | =============== |
|
73 | 73 | |
|
74 | 74 | IPython is meant to work as a drop-in replacement for the standard interactive |
|
75 | 75 | interpreter. As such, any code which is valid python should execute normally |
|
76 | 76 | under IPython (cases where this is not true should be reported as bugs). It |
|
77 | 77 | does, however, offer many features which are not available at a standard python |
|
78 | 78 | prompt. What follows is a list of these. |
|
79 | 79 | |
|
80 | 80 | |
|
81 | 81 | Caution for Windows users |
|
82 | 82 | ------------------------- |
|
83 | 83 | |
|
84 | 84 | Windows, unfortunately, uses the '\\' character as a path separator. This is a |
|
85 | 85 | terrible choice, because '\\' also represents the escape character in most |
|
86 | 86 | modern programming languages, including Python. For this reason, using '/' |
|
87 | 87 | character is recommended if you have problems with ``\``. However, in Windows |
|
88 | 88 | commands '/' flags options, so you can not use it for the root directory. This |
|
89 | 89 | means that paths beginning at the root must be typed in a contrived manner |
|
90 | 90 | like: ``%copy \opt/foo/bar.txt \tmp`` |
|
91 | 91 | |
|
92 | 92 | .. _magic: |
|
93 | 93 | |
|
94 | 94 | Magic command system |
|
95 | 95 | -------------------- |
|
96 | 96 | |
|
97 | 97 | IPython will treat any line whose first character is a % as a special |
|
98 | 98 | call to a 'magic' function. These allow you to control the behavior of |
|
99 | 99 | IPython itself, plus a lot of system-type features. They are all |
|
100 | 100 | prefixed with a % character, but parameters are given without |
|
101 | 101 | parentheses or quotes. |
|
102 | 102 | |
|
103 | 103 | Lines that begin with ``%%`` signal a *cell magic*: they take as arguments not |
|
104 | 104 | only the rest of the current line, but all lines below them as well, in the |
|
105 | 105 | current execution block. Cell magics can in fact make arbitrary modifications |
|
106 | 106 | to the input they receive, which need not even be valid Python code at all. |
|
107 | 107 | They receive the whole block as a single string. |
|
108 | 108 | |
|
109 | 109 | As a line magic example, the ``%cd`` magic works just like the OS command of |
|
110 | 110 | the same name:: |
|
111 | 111 | |
|
112 | 112 | In [8]: %cd |
|
113 | 113 | /home/fperez |
|
114 | 114 | |
|
115 | 115 | The following uses the builtin ``timeit`` in cell mode:: |
|
116 | 116 | |
|
117 | 117 | In [10]: %%timeit x = range(10000) |
|
118 | 118 | ...: min(x) |
|
119 | 119 | ...: max(x) |
|
120 | 120 | ...: |
|
121 | 121 | 1000 loops, best of 3: 438 us per loop |
|
122 | 122 | |
|
123 | 123 | In this case, ``x = range(10000)`` is called as the line argument, and the |
|
124 | 124 | block with ``min(x)`` and ``max(x)`` is called as the cell body. The |
|
125 | 125 | ``timeit`` magic receives both. |
|
126 | 126 | |
|
127 | 127 | If you have 'automagic' enabled (as it by default), you don't need to type in |
|
128 | 128 | the single ``%`` explicitly for line magics; IPython will scan its internal |
|
129 | 129 | list of magic functions and call one if it exists. With automagic on you can |
|
130 | 130 | then just type ``cd mydir`` to go to directory 'mydir':: |
|
131 | 131 | |
|
132 | 132 | In [9]: cd mydir |
|
133 | 133 | /home/fperez/mydir |
|
134 | 134 | |
|
135 | 135 | Note that cell magics *always* require an explicit ``%%`` prefix, automagic |
|
136 | 136 | calling only works for line magics. |
|
137 | 137 | |
|
138 | 138 | The automagic system has the lowest possible precedence in name searches, so |
|
139 | 139 | defining an identifier with the same name as an existing magic function will |
|
140 | 140 | shadow it for automagic use. You can still access the shadowed magic function |
|
141 | 141 | by explicitly using the ``%`` character at the beginning of the line. |
|
142 | 142 | |
|
143 | 143 | An example (with automagic on) should clarify all this: |
|
144 | 144 | |
|
145 | 145 | .. sourcecode:: ipython |
|
146 | 146 | |
|
147 | 147 | In [1]: cd ipython # %cd is called by automagic |
|
148 | 148 | /home/fperez/ipython |
|
149 | 149 | |
|
150 | 150 | In [2]: cd=1 # now cd is just a variable |
|
151 | 151 | |
|
152 | 152 | In [3]: cd .. # and doesn't work as a function anymore |
|
153 | 153 | File "<ipython-input-3-9fedb3aff56c>", line 1 |
|
154 | 154 | cd .. |
|
155 | 155 | ^ |
|
156 | 156 | SyntaxError: invalid syntax |
|
157 | 157 | |
|
158 | 158 | |
|
159 | 159 | In [4]: %cd .. # but %cd always works |
|
160 | 160 | /home/fperez |
|
161 | 161 | |
|
162 | 162 | In [5]: del cd # if you remove the cd variable, automagic works again |
|
163 | 163 | |
|
164 | 164 | In [6]: cd ipython |
|
165 | 165 | |
|
166 | 166 | /home/fperez/ipython |
|
167 | 167 | |
|
168 | 168 | Defining your own magics |
|
169 | 169 | ~~~~~~~~~~~~~~~~~~~~~~~~ |
|
170 | 170 | |
|
171 | 171 | There are two main ways to define your own magic functions: from standalone |
|
172 | 172 | functions and by inheriting from a base class provided by IPython: |
|
173 | 173 | :class:`IPython.core.magic.Magics`. Below we show code you can place in a file |
|
174 | 174 | that you load from your configuration, such as any file in the ``startup`` |
|
175 | 175 | subdirectory of your default IPython profile. |
|
176 | 176 | |
|
177 | 177 | First, let us see the simplest case. The following shows how to create a line |
|
178 | 178 | magic, a cell one and one that works in both modes, using just plain functions: |
|
179 | 179 | |
|
180 | 180 | .. sourcecode:: python |
|
181 | 181 | |
|
182 | 182 | from IPython.core.magic import (register_line_magic, register_cell_magic, |
|
183 | 183 | register_line_cell_magic) |
|
184 | 184 | |
|
185 | 185 | @register_line_magic |
|
186 | 186 | def lmagic(line): |
|
187 | 187 | "my line magic" |
|
188 | 188 | return line |
|
189 | 189 | |
|
190 | 190 | @register_cell_magic |
|
191 | 191 | def cmagic(line, cell): |
|
192 | 192 | "my cell magic" |
|
193 | 193 | return line, cell |
|
194 | 194 | |
|
195 | 195 | @register_line_cell_magic |
|
196 | 196 | def lcmagic(line, cell=None): |
|
197 | 197 | "Magic that works both as %lcmagic and as %%lcmagic" |
|
198 | 198 | if cell is None: |
|
199 | 199 | print "Called as line magic" |
|
200 | 200 | return line |
|
201 | 201 | else: |
|
202 | 202 | print "Called as cell magic" |
|
203 | 203 | return line, cell |
|
204 | 204 | |
|
205 | 205 | # We delete these to avoid name conflicts for automagic to work |
|
206 | 206 | del lmagic, lcmagic |
|
207 | 207 | |
|
208 | 208 | |
|
209 | 209 | You can also create magics of all three kinds by inheriting from the |
|
210 | 210 | :class:`IPython.core.magic.Magics` class. This lets you create magics that can |
|
211 | 211 | potentially hold state in between calls, and that have full access to the main |
|
212 | 212 | IPython object: |
|
213 | 213 | |
|
214 | 214 | .. sourcecode:: python |
|
215 | 215 | |
|
216 | 216 | # This code can be put in any Python module, it does not require IPython |
|
217 | 217 | # itself to be running already. It only creates the magics subclass but |
|
218 | 218 | # doesn't instantiate it yet. |
|
219 | 219 | from IPython.core.magic import (Magics, magics_class, line_magic, |
|
220 | 220 | cell_magic, line_cell_magic) |
|
221 | 221 | |
|
222 | 222 | # The class MUST call this class decorator at creation time |
|
223 | 223 | @magics_class |
|
224 | 224 | class MyMagics(Magics): |
|
225 | 225 | |
|
226 | 226 | @line_magic |
|
227 | 227 | def lmagic(self, line): |
|
228 | 228 | "my line magic" |
|
229 | 229 | print "Full access to the main IPython object:", self.shell |
|
230 | 230 | print "Variables in the user namespace:", self.user_ns.keys() |
|
231 | 231 | return line |
|
232 | 232 | |
|
233 | 233 | @cell_magic |
|
234 | 234 | def cmagic(self, line, cell): |
|
235 | 235 | "my cell magic" |
|
236 | 236 | return line, cell |
|
237 | 237 | |
|
238 | 238 | @line_cell_magic |
|
239 | 239 | def lcmagic(self, line, cell=None): |
|
240 | 240 | "Magic that works both as %lcmagic and as %%lcmagic" |
|
241 | 241 | if cell is None: |
|
242 | 242 | print "Called as line magic" |
|
243 | 243 | return line |
|
244 | 244 | else: |
|
245 | 245 | print "Called as cell magic" |
|
246 | 246 | return line, cell |
|
247 | 247 | |
|
248 | 248 | |
|
249 | 249 | # In order to actually use these magics, you must register them with a |
|
250 | 250 | # running IPython. This code must be placed in a file that is loaded once |
|
251 | 251 | # IPython is up and running: |
|
252 | 252 | ip = get_ipython() |
|
253 | 253 | # You can register the class itself without instantiating it. IPython will |
|
254 | 254 | # call the default constructor on it. |
|
255 | 255 | ip.register_magics(MyMagics) |
|
256 | 256 | |
|
257 | 257 | If you want to create a class with a different constructor that holds |
|
258 | 258 | additional state, then you should always call the parent constructor and |
|
259 | 259 | instantiate the class yourself before registration: |
|
260 | 260 | |
|
261 | 261 | .. sourcecode:: python |
|
262 | 262 | |
|
263 | 263 | @magics_class |
|
264 | 264 | class StatefulMagics(Magics): |
|
265 | 265 | "Magics that hold additional state" |
|
266 | 266 | |
|
267 | 267 | def __init__(self, shell, data): |
|
268 | 268 | # You must call the parent constructor |
|
269 | 269 | super(StatefulMagics, self).__init__(shell) |
|
270 | 270 | self.data = data |
|
271 | 271 | |
|
272 | 272 | # etc... |
|
273 | 273 | |
|
274 | 274 | # This class must then be registered with a manually created instance, |
|
275 | 275 | # since its constructor has different arguments from the default: |
|
276 | 276 | ip = get_ipython() |
|
277 | 277 | magics = StatefulMagics(ip, some_data) |
|
278 | 278 | ip.register_magics(magics) |
|
279 | 279 | |
|
280 | 280 | |
|
281 | 281 | In earlier versions, IPython had an API for the creation of line magics (cell |
|
282 | 282 | magics did not exist at the time) that required you to create functions with a |
|
283 | 283 | method-looking signature and to manually pass both the function and the name. |
|
284 | 284 | While this API is no longer recommended, it remains indefinitely supported for |
|
285 | 285 | backwards compatibility purposes. With the old API, you'd create a magic as |
|
286 | 286 | follows: |
|
287 | 287 | |
|
288 | 288 | .. sourcecode:: python |
|
289 | 289 | |
|
290 | 290 | def func(self, line): |
|
291 | 291 | print "Line magic called with line:", line |
|
292 | 292 | print "IPython object:", self.shell |
|
293 | 293 | |
|
294 | 294 | ip = get_ipython() |
|
295 | 295 | # Declare this function as the magic %mycommand |
|
296 | 296 | ip.define_magic('mycommand', func) |
|
297 | 297 | |
|
298 | 298 | Type ``%magic`` for more information, including a list of all available magic |
|
299 | 299 | functions at any time and their docstrings. You can also type |
|
300 | 300 | ``%magic_function_name?`` (see :ref:`below <dynamic_object_info>` for |
|
301 | 301 | information on the '?' system) to get information about any particular magic |
|
302 | 302 | function you are interested in. |
|
303 | 303 | |
|
304 | 304 | The API documentation for the :mod:`IPython.core.magic` module contains the full |
|
305 | 305 | docstrings of all currently available magic commands. |
|
306 | 306 | |
|
307 | 307 | |
|
308 | 308 | Access to the standard Python help |
|
309 | 309 | ---------------------------------- |
|
310 | 310 | |
|
311 | 311 | Simply type ``help()`` to access Python's standard help system. You can |
|
312 | 312 | also type ``help(object)`` for information about a given object, or |
|
313 | 313 | ``help('keyword')`` for information on a keyword. You may need to configure your |
|
314 | 314 | PYTHONDOCS environment variable for this feature to work correctly. |
|
315 | 315 | |
|
316 | 316 | .. _dynamic_object_info: |
|
317 | 317 | |
|
318 | 318 | Dynamic object information |
|
319 | 319 | -------------------------- |
|
320 | 320 | |
|
321 | 321 | Typing ``?word`` or ``word?`` prints detailed information about an object. If |
|
322 | 322 | certain strings in the object are too long (e.g. function signatures) they get |
|
323 | 323 | snipped in the center for brevity. This system gives access variable types and |
|
324 | 324 | values, docstrings, function prototypes and other useful information. |
|
325 | 325 | |
|
326 | 326 | If the information will not fit in the terminal, it is displayed in a pager |
|
327 | 327 | (``less`` if available, otherwise a basic internal pager). |
|
328 | 328 | |
|
329 | 329 | Typing ``??word`` or ``word??`` gives access to the full information, including |
|
330 | 330 | the source code where possible. Long strings are not snipped. |
|
331 | 331 | |
|
332 | 332 | The following magic functions are particularly useful for gathering |
|
333 | 333 | information about your working environment. You can get more details by |
|
334 | 334 | typing ``%magic`` or querying them individually (``%function_name?``); |
|
335 | 335 | this is just a summary: |
|
336 | 336 | |
|
337 | 337 | * **%pdoc <object>**: Print (or run through a pager if too long) the |
|
338 | 338 | docstring for an object. If the given object is a class, it will |
|
339 | 339 | print both the class and the constructor docstrings. |
|
340 |
* **%pdef <object>**: Print the |
|
|
340 | * **%pdef <object>**: Print the call signature for any callable | |
|
341 | 341 | object. If the object is a class, print the constructor information. |
|
342 | 342 | * **%psource <object>**: Print (or run through a pager if too long) |
|
343 | 343 | the source code for an object. |
|
344 | 344 | * **%pfile <object>**: Show the entire source file where an object was |
|
345 | 345 | defined via a pager, opening it at the line where the object |
|
346 | 346 | definition begins. |
|
347 | 347 | * **%who/%whos**: These functions give information about identifiers |
|
348 | 348 | you have defined interactively (not things you loaded or defined |
|
349 | 349 | in your configuration files). %who just prints a list of |
|
350 | 350 | identifiers and %whos prints a table with some basic details about |
|
351 | 351 | each identifier. |
|
352 | 352 | |
|
353 | 353 | Note that the dynamic object information functions (?/??, ``%pdoc``, |
|
354 | 354 | ``%pfile``, ``%pdef``, ``%psource``) work on object attributes, as well as |
|
355 | 355 | directly on variables. For example, after doing ``import os``, you can use |
|
356 | 356 | ``os.path.abspath??``. |
|
357 | 357 | |
|
358 | 358 | .. _readline: |
|
359 | 359 | |
|
360 | 360 | Readline-based features |
|
361 | 361 | ----------------------- |
|
362 | 362 | |
|
363 | 363 | These features require the GNU readline library, so they won't work if your |
|
364 | 364 | Python installation lacks readline support. We will first describe the default |
|
365 | 365 | behavior IPython uses, and then how to change it to suit your preferences. |
|
366 | 366 | |
|
367 | 367 | |
|
368 | 368 | Command line completion |
|
369 | 369 | +++++++++++++++++++++++ |
|
370 | 370 | |
|
371 | 371 | At any time, hitting TAB will complete any available python commands or |
|
372 | 372 | variable names, and show you a list of the possible completions if |
|
373 | 373 | there's no unambiguous one. It will also complete filenames in the |
|
374 | 374 | current directory if no python names match what you've typed so far. |
|
375 | 375 | |
|
376 | 376 | |
|
377 | 377 | Search command history |
|
378 | 378 | ++++++++++++++++++++++ |
|
379 | 379 | |
|
380 | 380 | IPython provides two ways for searching through previous input and thus |
|
381 | 381 | reduce the need for repetitive typing: |
|
382 | 382 | |
|
383 | 383 | 1. Start typing, and then use Ctrl-p (previous,up) and Ctrl-n |
|
384 | 384 | (next,down) to search through only the history items that match |
|
385 | 385 | what you've typed so far. If you use Ctrl-p/Ctrl-n at a blank |
|
386 | 386 | prompt, they just behave like normal arrow keys. |
|
387 | 387 | 2. Hit Ctrl-r: opens a search prompt. Begin typing and the system |
|
388 | 388 | searches your history for lines that contain what you've typed so |
|
389 | 389 | far, completing as much as it can. |
|
390 | 390 | |
|
391 | 391 | |
|
392 | 392 | Persistent command history across sessions |
|
393 | 393 | ++++++++++++++++++++++++++++++++++++++++++ |
|
394 | 394 | |
|
395 | 395 | IPython will save your input history when it leaves and reload it next |
|
396 | 396 | time you restart it. By default, the history file is named |
|
397 | 397 | $IPYTHONDIR/profile_<name>/history.sqlite. This allows you to keep |
|
398 | 398 | separate histories related to various tasks: commands related to |
|
399 | 399 | numerical work will not be clobbered by a system shell history, for |
|
400 | 400 | example. |
|
401 | 401 | |
|
402 | 402 | |
|
403 | 403 | Autoindent |
|
404 | 404 | ++++++++++ |
|
405 | 405 | |
|
406 | 406 | IPython can recognize lines ending in ':' and indent the next line, |
|
407 | 407 | while also un-indenting automatically after 'raise' or 'return'. |
|
408 | 408 | |
|
409 | 409 | This feature uses the readline library, so it will honor your |
|
410 | 410 | :file:`~/.inputrc` configuration (or whatever file your INPUTRC variable points |
|
411 | 411 | to). Adding the following lines to your :file:`.inputrc` file can make |
|
412 | 412 | indenting/unindenting more convenient (M-i indents, M-u unindents):: |
|
413 | 413 | |
|
414 | 414 | $if Python |
|
415 | 415 | "\M-i": " " |
|
416 | 416 | "\M-u": "\d\d\d\d" |
|
417 | 417 | $endif |
|
418 | 418 | |
|
419 | 419 | Note that there are 4 spaces between the quote marks after "M-i" above. |
|
420 | 420 | |
|
421 | 421 | .. warning:: |
|
422 | 422 | |
|
423 | 423 | Setting the above indents will cause problems with unicode text entry in |
|
424 | 424 | the terminal. |
|
425 | 425 | |
|
426 | 426 | .. warning:: |
|
427 | 427 | |
|
428 | 428 | Autoindent is ON by default, but it can cause problems with the pasting of |
|
429 | 429 | multi-line indented code (the pasted code gets re-indented on each line). A |
|
430 | 430 | magic function %autoindent allows you to toggle it on/off at runtime. You |
|
431 | 431 | can also disable it permanently on in your :file:`ipython_config.py` file |
|
432 | 432 | (set TerminalInteractiveShell.autoindent=False). |
|
433 | 433 | |
|
434 | 434 | If you want to paste multiple lines in the terminal, it is recommended that |
|
435 | 435 | you use ``%paste``. |
|
436 | 436 | |
|
437 | 437 | |
|
438 | 438 | Customizing readline behavior |
|
439 | 439 | +++++++++++++++++++++++++++++ |
|
440 | 440 | |
|
441 | 441 | All these features are based on the GNU readline library, which has an |
|
442 | 442 | extremely customizable interface. Normally, readline is configured via a |
|
443 | 443 | file which defines the behavior of the library; the details of the |
|
444 | 444 | syntax for this can be found in the readline documentation available |
|
445 | 445 | with your system or on the Internet. IPython doesn't read this file (if |
|
446 | 446 | it exists) directly, but it does support passing to readline valid |
|
447 | 447 | options via a simple interface. In brief, you can customize readline by |
|
448 | 448 | setting the following options in your configuration file (note |
|
449 | 449 | that these options can not be specified at the command line): |
|
450 | 450 | |
|
451 | 451 | * **readline_parse_and_bind**: this holds a list of strings to be executed |
|
452 | 452 | via a readline.parse_and_bind() command. The syntax for valid commands |
|
453 | 453 | of this kind can be found by reading the documentation for the GNU |
|
454 | 454 | readline library, as these commands are of the kind which readline |
|
455 | 455 | accepts in its configuration file. |
|
456 | 456 | * **readline_remove_delims**: a string of characters to be removed |
|
457 | 457 | from the default word-delimiters list used by readline, so that |
|
458 | 458 | completions may be performed on strings which contain them. Do not |
|
459 | 459 | change the default value unless you know what you're doing. |
|
460 | 460 | |
|
461 | 461 | You will find the default values in your configuration file. |
|
462 | 462 | |
|
463 | 463 | |
|
464 | 464 | Session logging and restoring |
|
465 | 465 | ----------------------------- |
|
466 | 466 | |
|
467 | 467 | You can log all input from a session either by starting IPython with the |
|
468 | 468 | command line switch ``--logfile=foo.py`` (see :ref:`here <command_line_options>`) |
|
469 | 469 | or by activating the logging at any moment with the magic function %logstart. |
|
470 | 470 | |
|
471 | 471 | Log files can later be reloaded by running them as scripts and IPython |
|
472 | 472 | will attempt to 'replay' the log by executing all the lines in it, thus |
|
473 | 473 | restoring the state of a previous session. This feature is not quite |
|
474 | 474 | perfect, but can still be useful in many cases. |
|
475 | 475 | |
|
476 | 476 | The log files can also be used as a way to have a permanent record of |
|
477 | 477 | any code you wrote while experimenting. Log files are regular text files |
|
478 | 478 | which you can later open in your favorite text editor to extract code or |
|
479 | 479 | to 'clean them up' before using them to replay a session. |
|
480 | 480 | |
|
481 | 481 | The `%logstart` function for activating logging in mid-session is used as |
|
482 | 482 | follows:: |
|
483 | 483 | |
|
484 | 484 | %logstart [log_name [log_mode]] |
|
485 | 485 | |
|
486 | 486 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
487 | 487 | current working directory, in 'rotate' mode (see below). |
|
488 | 488 | |
|
489 | 489 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
490 | 490 | history up to that point and then continues logging. |
|
491 | 491 | |
|
492 | 492 | %logstart takes a second optional parameter: logging mode. This can be |
|
493 | 493 | one of (note that the modes are given unquoted): |
|
494 | 494 | |
|
495 | 495 | * [over:] overwrite existing log_name. |
|
496 | 496 | * [backup:] rename (if exists) to log_name~ and start log_name. |
|
497 | 497 | * [append:] well, that says it. |
|
498 | 498 | * [rotate:] create rotating logs log_name.1~, log_name.2~, etc. |
|
499 | 499 | |
|
500 | 500 | The %logoff and %logon functions allow you to temporarily stop and |
|
501 | 501 | resume logging to a file which had previously been started with |
|
502 | 502 | %logstart. They will fail (with an explanation) if you try to use them |
|
503 | 503 | before logging has been started. |
|
504 | 504 | |
|
505 | 505 | .. _system_shell_access: |
|
506 | 506 | |
|
507 | 507 | System shell access |
|
508 | 508 | ------------------- |
|
509 | 509 | |
|
510 | 510 | Any input line beginning with a ! character is passed verbatim (minus |
|
511 | 511 | the !, of course) to the underlying operating system. For example, |
|
512 | 512 | typing ``!ls`` will run 'ls' in the current directory. |
|
513 | 513 | |
|
514 | 514 | Manual capture of command output |
|
515 | 515 | -------------------------------- |
|
516 | 516 | |
|
517 | 517 | You can assign the result of a system command to a Python variable with the |
|
518 | 518 | syntax ``myfiles = !ls``. This gets machine readable output from stdout |
|
519 | 519 | (e.g. without colours), and splits on newlines. To explicitly get this sort of |
|
520 | 520 | output without assigning to a variable, use two exclamation marks (``!!ls``) or |
|
521 | 521 | the ``%sx`` magic command. |
|
522 | 522 | |
|
523 | 523 | The captured list has some convenience features. ``myfiles.n`` or ``myfiles.s`` |
|
524 | 524 | returns a string delimited by newlines or spaces, respectively. ``myfiles.p`` |
|
525 | 525 | produces `path objects <http://pypi.python.org/pypi/path.py>`_ from the list items. |
|
526 | 526 | See :ref:`string_lists` for details. |
|
527 | 527 | |
|
528 | 528 | IPython also allows you to expand the value of python variables when |
|
529 | 529 | making system calls. Wrap variables or expressions in {braces}:: |
|
530 | 530 | |
|
531 | 531 | In [1]: pyvar = 'Hello world' |
|
532 | 532 | In [2]: !echo "A python variable: {pyvar}" |
|
533 | 533 | A python variable: Hello world |
|
534 | 534 | In [3]: import math |
|
535 | 535 | In [4]: x = 8 |
|
536 | 536 | In [5]: !echo {math.factorial(x)} |
|
537 | 537 | 40320 |
|
538 | 538 | |
|
539 | 539 | For simple cases, you can alternatively prepend $ to a variable name:: |
|
540 | 540 | |
|
541 | 541 | In [6]: !echo $sys.argv |
|
542 | 542 | [/home/fperez/usr/bin/ipython] |
|
543 | 543 | In [7]: !echo "A system variable: $$HOME" # Use $$ for literal $ |
|
544 | 544 | A system variable: /home/fperez |
|
545 | 545 | |
|
546 | 546 | System command aliases |
|
547 | 547 | ---------------------- |
|
548 | 548 | |
|
549 | 549 | The %alias magic function allows you to define magic functions which are in fact |
|
550 | 550 | system shell commands. These aliases can have parameters. |
|
551 | 551 | |
|
552 | 552 | ``%alias alias_name cmd`` defines 'alias_name' as an alias for 'cmd' |
|
553 | 553 | |
|
554 | 554 | Then, typing ``alias_name params`` will execute the system command 'cmd |
|
555 | 555 | params' (from your underlying operating system). |
|
556 | 556 | |
|
557 | 557 | You can also define aliases with parameters using %s specifiers (one per |
|
558 | 558 | parameter). The following example defines the parts function as an |
|
559 | 559 | alias to the command 'echo first %s second %s' where each %s will be |
|
560 | 560 | replaced by a positional parameter to the call to %parts:: |
|
561 | 561 | |
|
562 | 562 | In [1]: %alias parts echo first %s second %s |
|
563 | 563 | In [2]: parts A B |
|
564 | 564 | first A second B |
|
565 | 565 | In [3]: parts A |
|
566 | 566 | ERROR: Alias <parts> requires 2 arguments, 1 given. |
|
567 | 567 | |
|
568 | 568 | If called with no parameters, %alias prints the table of currently |
|
569 | 569 | defined aliases. |
|
570 | 570 | |
|
571 | 571 | The %rehashx magic allows you to load your entire $PATH as |
|
572 | 572 | ipython aliases. See its docstring for further details. |
|
573 | 573 | |
|
574 | 574 | |
|
575 | 575 | .. _dreload: |
|
576 | 576 | |
|
577 | 577 | Recursive reload |
|
578 | 578 | ---------------- |
|
579 | 579 | |
|
580 | 580 | The :mod:`IPython.lib.deepreload` module allows you to recursively reload a |
|
581 | 581 | module: changes made to any of its dependencies will be reloaded without |
|
582 | 582 | having to exit. To start using it, do:: |
|
583 | 583 | |
|
584 | 584 | from IPython.lib.deepreload import reload as dreload |
|
585 | 585 | |
|
586 | 586 | |
|
587 | 587 | Verbose and colored exception traceback printouts |
|
588 | 588 | ------------------------------------------------- |
|
589 | 589 | |
|
590 | 590 | IPython provides the option to see very detailed exception tracebacks, |
|
591 | 591 | which can be especially useful when debugging large programs. You can |
|
592 | 592 | run any Python file with the %run function to benefit from these |
|
593 | 593 | detailed tracebacks. Furthermore, both normal and verbose tracebacks can |
|
594 | 594 | be colored (if your terminal supports it) which makes them much easier |
|
595 | 595 | to parse visually. |
|
596 | 596 | |
|
597 | 597 | See the magic xmode and colors functions for details (just type %magic). |
|
598 | 598 | |
|
599 | 599 | These features are basically a terminal version of Ka-Ping Yee's cgitb |
|
600 | 600 | module, now part of the standard Python library. |
|
601 | 601 | |
|
602 | 602 | |
|
603 | 603 | .. _input_caching: |
|
604 | 604 | |
|
605 | 605 | Input caching system |
|
606 | 606 | -------------------- |
|
607 | 607 | |
|
608 | 608 | IPython offers numbered prompts (In/Out) with input and output caching |
|
609 | 609 | (also referred to as 'input history'). All input is saved and can be |
|
610 | 610 | retrieved as variables (besides the usual arrow key recall), in |
|
611 | 611 | addition to the %rep magic command that brings a history entry |
|
612 | 612 | up for editing on the next command line. |
|
613 | 613 | |
|
614 | 614 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
615 | 615 | |
|
616 | 616 | * _i, _ii, _iii: store previous, next previous and next-next previous inputs. |
|
617 | 617 | * In, _ih : a list of all inputs; _ih[n] is the input from line n. If you |
|
618 | 618 | overwrite In with a variable of your own, you can remake the assignment to the |
|
619 | 619 | internal list with a simple ``In=_ih``. |
|
620 | 620 | |
|
621 | 621 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
622 | 622 | being the prompt counter), so ``_i<n> == _ih[<n>] == In[<n>]``. |
|
623 | 623 | |
|
624 | 624 | For example, what you typed at prompt 14 is available as _i14, _ih[14] |
|
625 | 625 | and In[14]. |
|
626 | 626 | |
|
627 | 627 | This allows you to easily cut and paste multi line interactive prompts |
|
628 | 628 | by printing them out: they print like a clean string, without prompt |
|
629 | 629 | characters. You can also manipulate them like regular variables (they |
|
630 | 630 | are strings), modify or exec them (typing ``exec _i9`` will re-execute the |
|
631 | 631 | contents of input prompt 9. |
|
632 | 632 | |
|
633 | 633 | You can also re-execute multiple lines of input easily by using the |
|
634 | 634 | magic %rerun or %macro functions. The macro system also allows you to re-execute |
|
635 | 635 | previous lines which include magic function calls (which require special |
|
636 | 636 | processing). Type %macro? for more details on the macro system. |
|
637 | 637 | |
|
638 | 638 | A history function %hist allows you to see any part of your input |
|
639 | 639 | history by printing a range of the _i variables. |
|
640 | 640 | |
|
641 | 641 | You can also search ('grep') through your history by typing |
|
642 | 642 | ``%hist -g somestring``. This is handy for searching for URLs, IP addresses, |
|
643 | 643 | etc. You can bring history entries listed by '%hist -g' up for editing |
|
644 | 644 | with the %recall command, or run them immediately with %rerun. |
|
645 | 645 | |
|
646 | 646 | .. _output_caching: |
|
647 | 647 | |
|
648 | 648 | Output caching system |
|
649 | 649 | --------------------- |
|
650 | 650 | |
|
651 | 651 | For output that is returned from actions, a system similar to the input |
|
652 | 652 | cache exists but using _ instead of _i. Only actions that produce a |
|
653 | 653 | result (NOT assignments, for example) are cached. If you are familiar |
|
654 | 654 | with Mathematica, IPython's _ variables behave exactly like |
|
655 | 655 | Mathematica's % variables. |
|
656 | 656 | |
|
657 | 657 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
658 | 658 | |
|
659 | 659 | * [_] (a single underscore) : stores previous output, like Python's |
|
660 | 660 | default interpreter. |
|
661 | 661 | * [__] (two underscores): next previous. |
|
662 | 662 | * [___] (three underscores): next-next previous. |
|
663 | 663 | |
|
664 | 664 | Additionally, global variables named _<n> are dynamically created (<n> |
|
665 | 665 | being the prompt counter), such that the result of output <n> is always |
|
666 | 666 | available as _<n> (don't use the angle brackets, just the number, e.g. |
|
667 | 667 | _21). |
|
668 | 668 | |
|
669 | 669 | These variables are also stored in a global dictionary (not a |
|
670 | 670 | list, since it only has entries for lines which returned a result) |
|
671 | 671 | available under the names _oh and Out (similar to _ih and In). So the |
|
672 | 672 | output from line 12 can be obtained as _12, Out[12] or _oh[12]. If you |
|
673 | 673 | accidentally overwrite the Out variable you can recover it by typing |
|
674 | 674 | 'Out=_oh' at the prompt. |
|
675 | 675 | |
|
676 | 676 | This system obviously can potentially put heavy memory demands on your |
|
677 | 677 | system, since it prevents Python's garbage collector from removing any |
|
678 | 678 | previously computed results. You can control how many results are kept |
|
679 | 679 | in memory with the option (at the command line or in your configuration |
|
680 | 680 | file) cache_size. If you set it to 0, the whole system is completely |
|
681 | 681 | disabled and the prompts revert to the classic '>>>' of normal Python. |
|
682 | 682 | |
|
683 | 683 | |
|
684 | 684 | Directory history |
|
685 | 685 | ----------------- |
|
686 | 686 | |
|
687 | 687 | Your history of visited directories is kept in the global list _dh, and |
|
688 | 688 | the magic %cd command can be used to go to any entry in that list. The |
|
689 | 689 | %dhist command allows you to view this history. Do ``cd -<TAB>`` to |
|
690 | 690 | conveniently view the directory history. |
|
691 | 691 | |
|
692 | 692 | |
|
693 | 693 | Automatic parentheses and quotes |
|
694 | 694 | -------------------------------- |
|
695 | 695 | |
|
696 | 696 | These features were adapted from Nathan Gray's LazyPython. They are |
|
697 | 697 | meant to allow less typing for common situations. |
|
698 | 698 | |
|
699 | 699 | |
|
700 | 700 | Automatic parentheses |
|
701 | 701 | +++++++++++++++++++++ |
|
702 | 702 | |
|
703 | 703 | Callable objects (i.e. functions, methods, etc) can be invoked like this |
|
704 | 704 | (notice the commas between the arguments):: |
|
705 | 705 | |
|
706 | 706 | In [1]: callable_ob arg1, arg2, arg3 |
|
707 | 707 | ------> callable_ob(arg1, arg2, arg3) |
|
708 | 708 | |
|
709 | 709 | You can force automatic parentheses by using '/' as the first character |
|
710 | 710 | of a line. For example:: |
|
711 | 711 | |
|
712 | 712 | In [2]: /globals # becomes 'globals()' |
|
713 | 713 | |
|
714 | 714 | Note that the '/' MUST be the first character on the line! This won't work:: |
|
715 | 715 | |
|
716 | 716 | In [3]: print /globals # syntax error |
|
717 | 717 | |
|
718 | 718 | In most cases the automatic algorithm should work, so you should rarely |
|
719 | 719 | need to explicitly invoke /. One notable exception is if you are trying |
|
720 | 720 | to call a function with a list of tuples as arguments (the parenthesis |
|
721 | 721 | will confuse IPython):: |
|
722 | 722 | |
|
723 | 723 | In [4]: zip (1,2,3),(4,5,6) # won't work |
|
724 | 724 | |
|
725 | 725 | but this will work:: |
|
726 | 726 | |
|
727 | 727 | In [5]: /zip (1,2,3),(4,5,6) |
|
728 | 728 | ------> zip ((1,2,3),(4,5,6)) |
|
729 | 729 | Out[5]: [(1, 4), (2, 5), (3, 6)] |
|
730 | 730 | |
|
731 | 731 | IPython tells you that it has altered your command line by displaying |
|
732 | 732 | the new command line preceded by ->. e.g.:: |
|
733 | 733 | |
|
734 | 734 | In [6]: callable list |
|
735 | 735 | ------> callable(list) |
|
736 | 736 | |
|
737 | 737 | |
|
738 | 738 | Automatic quoting |
|
739 | 739 | +++++++++++++++++ |
|
740 | 740 | |
|
741 | 741 | You can force automatic quoting of a function's arguments by using ',' |
|
742 | 742 | or ';' as the first character of a line. For example:: |
|
743 | 743 | |
|
744 | 744 | In [1]: ,my_function /home/me # becomes my_function("/home/me") |
|
745 | 745 | |
|
746 | 746 | If you use ';' the whole argument is quoted as a single string, while ',' splits |
|
747 | 747 | on whitespace:: |
|
748 | 748 | |
|
749 | 749 | In [2]: ,my_function a b c # becomes my_function("a","b","c") |
|
750 | 750 | |
|
751 | 751 | In [3]: ;my_function a b c # becomes my_function("a b c") |
|
752 | 752 | |
|
753 | 753 | Note that the ',' or ';' MUST be the first character on the line! This |
|
754 | 754 | won't work:: |
|
755 | 755 | |
|
756 | 756 | In [4]: x = ,my_function /home/me # syntax error |
|
757 | 757 | |
|
758 | 758 | IPython as your default Python environment |
|
759 | 759 | ========================================== |
|
760 | 760 | |
|
761 | 761 | Python honors the environment variable PYTHONSTARTUP and will execute at |
|
762 | 762 | startup the file referenced by this variable. If you put the following code at |
|
763 | 763 | the end of that file, then IPython will be your working environment anytime you |
|
764 | 764 | start Python:: |
|
765 | 765 | |
|
766 | 766 | from IPython.frontend.terminal.ipapp import launch_new_instance |
|
767 | 767 | launch_new_instance() |
|
768 | 768 | raise SystemExit |
|
769 | 769 | |
|
770 | 770 | The ``raise SystemExit`` is needed to exit Python when |
|
771 | 771 | it finishes, otherwise you'll be back at the normal Python '>>>' |
|
772 | 772 | prompt. |
|
773 | 773 | |
|
774 | 774 | This is probably useful to developers who manage multiple Python |
|
775 | 775 | versions and don't want to have correspondingly multiple IPython |
|
776 | 776 | versions. Note that in this mode, there is no way to pass IPython any |
|
777 | 777 | command-line options, as those are trapped first by Python itself. |
|
778 | 778 | |
|
779 | 779 | .. _Embedding: |
|
780 | 780 | |
|
781 | 781 | Embedding IPython |
|
782 | 782 | ================= |
|
783 | 783 | |
|
784 | 784 | It is possible to start an IPython instance inside your own Python |
|
785 | 785 | programs. This allows you to evaluate dynamically the state of your |
|
786 | 786 | code, operate with your variables, analyze them, etc. Note however that |
|
787 | 787 | any changes you make to values while in the shell do not propagate back |
|
788 | 788 | to the running code, so it is safe to modify your values because you |
|
789 | 789 | won't break your code in bizarre ways by doing so. |
|
790 | 790 | |
|
791 | 791 | .. note:: |
|
792 | 792 | |
|
793 | 793 | At present, trying to embed IPython from inside IPython causes problems. Run |
|
794 | 794 | the code samples below outside IPython. |
|
795 | 795 | |
|
796 | 796 | This feature allows you to easily have a fully functional python |
|
797 | 797 | environment for doing object introspection anywhere in your code with a |
|
798 | 798 | simple function call. In some cases a simple print statement is enough, |
|
799 | 799 | but if you need to do more detailed analysis of a code fragment this |
|
800 | 800 | feature can be very valuable. |
|
801 | 801 | |
|
802 | 802 | It can also be useful in scientific computing situations where it is |
|
803 | 803 | common to need to do some automatic, computationally intensive part and |
|
804 | 804 | then stop to look at data, plots, etc. |
|
805 | 805 | Opening an IPython instance will give you full access to your data and |
|
806 | 806 | functions, and you can resume program execution once you are done with |
|
807 | 807 | the interactive part (perhaps to stop again later, as many times as |
|
808 | 808 | needed). |
|
809 | 809 | |
|
810 | 810 | The following code snippet is the bare minimum you need to include in |
|
811 | 811 | your Python programs for this to work (detailed examples follow later):: |
|
812 | 812 | |
|
813 | 813 | from IPython import embed |
|
814 | 814 | |
|
815 | 815 | embed() # this call anywhere in your program will start IPython |
|
816 | 816 | |
|
817 | 817 | .. note:: |
|
818 | 818 | |
|
819 | 819 | As of 0.13, you can embed an IPython *kernel*, for use with qtconsole, |
|
820 | 820 | etc. via ``IPython.embed_kernel()`` instead of ``IPython.embed()``. |
|
821 | 821 | It should function just the same as regular embed, but you connect |
|
822 | 822 | an external frontend rather than IPython starting up in the local |
|
823 | 823 | terminal. |
|
824 | 824 | |
|
825 | 825 | You can run embedded instances even in code which is itself being run at |
|
826 | 826 | the IPython interactive prompt with '%run <filename>'. Since it's easy |
|
827 | 827 | to get lost as to where you are (in your top-level IPython or in your |
|
828 | 828 | embedded one), it's a good idea in such cases to set the in/out prompts |
|
829 | 829 | to something different for the embedded instances. The code examples |
|
830 | 830 | below illustrate this. |
|
831 | 831 | |
|
832 | 832 | You can also have multiple IPython instances in your program and open |
|
833 | 833 | them separately, for example with different options for data |
|
834 | 834 | presentation. If you close and open the same instance multiple times, |
|
835 | 835 | its prompt counters simply continue from each execution to the next. |
|
836 | 836 | |
|
837 | 837 | Please look at the docstrings in the :mod:`~IPython.frontend.terminal.embed` |
|
838 | 838 | module for more details on the use of this system. |
|
839 | 839 | |
|
840 | 840 | The following sample file illustrating how to use the embedding |
|
841 | 841 | functionality is provided in the examples directory as example-embed.py. |
|
842 | 842 | It should be fairly self-explanatory: |
|
843 | 843 | |
|
844 | 844 | .. literalinclude:: ../../examples/core/example-embed.py |
|
845 | 845 | :language: python |
|
846 | 846 | |
|
847 | 847 | Once you understand how the system functions, you can use the following |
|
848 | 848 | code fragments in your programs which are ready for cut and paste: |
|
849 | 849 | |
|
850 | 850 | .. literalinclude:: ../../examples/core/example-embed-short.py |
|
851 | 851 | :language: python |
|
852 | 852 | |
|
853 | 853 | Using the Python debugger (pdb) |
|
854 | 854 | =============================== |
|
855 | 855 | |
|
856 | 856 | Running entire programs via pdb |
|
857 | 857 | ------------------------------- |
|
858 | 858 | |
|
859 | 859 | pdb, the Python debugger, is a powerful interactive debugger which |
|
860 | 860 | allows you to step through code, set breakpoints, watch variables, |
|
861 | 861 | etc. IPython makes it very easy to start any script under the control |
|
862 | 862 | of pdb, regardless of whether you have wrapped it into a 'main()' |
|
863 | 863 | function or not. For this, simply type '%run -d myscript' at an |
|
864 | 864 | IPython prompt. See the %run command's documentation (via '%run?' or |
|
865 | 865 | in Sec. magic_ for more details, including how to control where pdb |
|
866 | 866 | will stop execution first. |
|
867 | 867 | |
|
868 | 868 | For more information on the use of the pdb debugger, read the included |
|
869 | 869 | pdb.doc file (part of the standard Python distribution). On a stock |
|
870 | 870 | Linux system it is located at /usr/lib/python2.3/pdb.doc, but the |
|
871 | 871 | easiest way to read it is by using the help() function of the pdb module |
|
872 | 872 | as follows (in an IPython prompt):: |
|
873 | 873 | |
|
874 | 874 | In [1]: import pdb |
|
875 | 875 | In [2]: pdb.help() |
|
876 | 876 | |
|
877 | 877 | This will load the pdb.doc document in a file viewer for you automatically. |
|
878 | 878 | |
|
879 | 879 | |
|
880 | 880 | Automatic invocation of pdb on exceptions |
|
881 | 881 | ----------------------------------------- |
|
882 | 882 | |
|
883 | 883 | IPython, if started with the ``--pdb`` option (or if the option is set in |
|
884 | 884 | your config file) can call the Python pdb debugger every time your code |
|
885 | 885 | triggers an uncaught exception. This feature |
|
886 | 886 | can also be toggled at any time with the %pdb magic command. This can be |
|
887 | 887 | extremely useful in order to find the origin of subtle bugs, because pdb |
|
888 | 888 | opens up at the point in your code which triggered the exception, and |
|
889 | 889 | while your program is at this point 'dead', all the data is still |
|
890 | 890 | available and you can walk up and down the stack frame and understand |
|
891 | 891 | the origin of the problem. |
|
892 | 892 | |
|
893 | 893 | Furthermore, you can use these debugging facilities both with the |
|
894 | 894 | embedded IPython mode and without IPython at all. For an embedded shell |
|
895 | 895 | (see sec. Embedding_), simply call the constructor with |
|
896 | 896 | ``--pdb`` in the argument string and pdb will automatically be called if an |
|
897 | 897 | uncaught exception is triggered by your code. |
|
898 | 898 | |
|
899 | 899 | For stand-alone use of the feature in your programs which do not use |
|
900 | 900 | IPython at all, put the following lines toward the top of your 'main' |
|
901 | 901 | routine:: |
|
902 | 902 | |
|
903 | 903 | import sys |
|
904 | 904 | from IPython.core import ultratb |
|
905 | 905 | sys.excepthook = ultratb.FormattedTB(mode='Verbose', |
|
906 | 906 | color_scheme='Linux', call_pdb=1) |
|
907 | 907 | |
|
908 | 908 | The mode keyword can be either 'Verbose' or 'Plain', giving either very |
|
909 | 909 | detailed or normal tracebacks respectively. The color_scheme keyword can |
|
910 | 910 | be one of 'NoColor', 'Linux' (default) or 'LightBG'. These are the same |
|
911 | 911 | options which can be set in IPython with ``--colors`` and ``--xmode``. |
|
912 | 912 | |
|
913 | 913 | This will give any of your programs detailed, colored tracebacks with |
|
914 | 914 | automatic invocation of pdb. |
|
915 | 915 | |
|
916 | 916 | |
|
917 | 917 | Extensions for syntax processing |
|
918 | 918 | ================================ |
|
919 | 919 | |
|
920 | 920 | This isn't for the faint of heart, because the potential for breaking |
|
921 | 921 | things is quite high. But it can be a very powerful and useful feature. |
|
922 | 922 | In a nutshell, you can redefine the way IPython processes the user input |
|
923 | 923 | line to accept new, special extensions to the syntax without needing to |
|
924 | 924 | change any of IPython's own code. |
|
925 | 925 | |
|
926 | 926 | In the IPython/extensions directory you will find some examples |
|
927 | 927 | supplied, which we will briefly describe now. These can be used 'as is' |
|
928 | 928 | (and both provide very useful functionality), or you can use them as a |
|
929 | 929 | starting point for writing your own extensions. |
|
930 | 930 | |
|
931 | 931 | .. _pasting_with_prompts: |
|
932 | 932 | |
|
933 | 933 | Pasting of code starting with Python or IPython prompts |
|
934 | 934 | ------------------------------------------------------- |
|
935 | 935 | |
|
936 | 936 | IPython is smart enough to filter out input prompts, be they plain Python ones |
|
937 | 937 | (``>>>`` and ``...``) or IPython ones (``In [N]:`` and `` ...:``). You can |
|
938 | 938 | therefore copy and paste from existing interactive sessions without worry. |
|
939 | 939 | |
|
940 | 940 | The following is a 'screenshot' of how things work, copying an example from the |
|
941 | 941 | standard Python tutorial:: |
|
942 | 942 | |
|
943 | 943 | In [1]: >>> # Fibonacci series: |
|
944 | 944 | |
|
945 | 945 | In [2]: ... # the sum of two elements defines the next |
|
946 | 946 | |
|
947 | 947 | In [3]: ... a, b = 0, 1 |
|
948 | 948 | |
|
949 | 949 | In [4]: >>> while b < 10: |
|
950 | 950 | ...: ... print b |
|
951 | 951 | ...: ... a, b = b, a+b |
|
952 | 952 | ...: |
|
953 | 953 | 1 |
|
954 | 954 | 1 |
|
955 | 955 | 2 |
|
956 | 956 | 3 |
|
957 | 957 | 5 |
|
958 | 958 | 8 |
|
959 | 959 | |
|
960 | 960 | And pasting from IPython sessions works equally well:: |
|
961 | 961 | |
|
962 | 962 | In [1]: In [5]: def f(x): |
|
963 | 963 | ...: ...: "A simple function" |
|
964 | 964 | ...: ...: return x**2 |
|
965 | 965 | ...: ...: |
|
966 | 966 | |
|
967 | 967 | In [2]: f(3) |
|
968 | 968 | Out[2]: 9 |
|
969 | 969 | |
|
970 | 970 | .. _gui_support: |
|
971 | 971 | |
|
972 | 972 | GUI event loop support |
|
973 | 973 | ====================== |
|
974 | 974 | |
|
975 | 975 | .. versionadded:: 0.11 |
|
976 | 976 | The ``%gui`` magic and :mod:`IPython.lib.inputhook`. |
|
977 | 977 | |
|
978 | 978 | IPython has excellent support for working interactively with Graphical User |
|
979 | 979 | Interface (GUI) toolkits, such as wxPython, PyQt4/PySide, PyGTK and Tk. This is |
|
980 | 980 | implemented using Python's builtin ``PyOSInputHook`` hook. This implementation |
|
981 | 981 | is extremely robust compared to our previous thread-based version. The |
|
982 | 982 | advantages of this are: |
|
983 | 983 | |
|
984 | 984 | * GUIs can be enabled and disabled dynamically at runtime. |
|
985 | 985 | * The active GUI can be switched dynamically at runtime. |
|
986 | 986 | * In some cases, multiple GUIs can run simultaneously with no problems. |
|
987 | 987 | * There is a developer API in :mod:`IPython.lib.inputhook` for customizing |
|
988 | 988 | all of these things. |
|
989 | 989 | |
|
990 | 990 | For users, enabling GUI event loop integration is simple. You simple use the |
|
991 | 991 | ``%gui`` magic as follows:: |
|
992 | 992 | |
|
993 | 993 | %gui [GUINAME] |
|
994 | 994 | |
|
995 | 995 | With no arguments, ``%gui`` removes all GUI support. Valid ``GUINAME`` |
|
996 | 996 | arguments are ``wx``, ``qt``, ``gtk`` and ``tk``. |
|
997 | 997 | |
|
998 | 998 | Thus, to use wxPython interactively and create a running :class:`wx.App` |
|
999 | 999 | object, do:: |
|
1000 | 1000 | |
|
1001 | 1001 | %gui wx |
|
1002 | 1002 | |
|
1003 | 1003 | For information on IPython's Matplotlib integration (and the ``pylab`` mode) |
|
1004 | 1004 | see :ref:`this section <matplotlib_support>`. |
|
1005 | 1005 | |
|
1006 | 1006 | For developers that want to use IPython's GUI event loop integration in the |
|
1007 | 1007 | form of a library, these capabilities are exposed in library form in the |
|
1008 | 1008 | :mod:`IPython.lib.inputhook` and :mod:`IPython.lib.guisupport` modules. |
|
1009 | 1009 | Interested developers should see the module docstrings for more information, |
|
1010 | 1010 | but there are a few points that should be mentioned here. |
|
1011 | 1011 | |
|
1012 | 1012 | First, the ``PyOSInputHook`` approach only works in command line settings |
|
1013 | 1013 | where readline is activated. The integration with various eventloops |
|
1014 | 1014 | is handled somewhat differently (and more simply) when using the standalone |
|
1015 | 1015 | kernel, as in the qtconsole and notebook. |
|
1016 | 1016 | |
|
1017 | 1017 | Second, when using the ``PyOSInputHook`` approach, a GUI application should |
|
1018 | 1018 | *not* start its event loop. Instead all of this is handled by the |
|
1019 | 1019 | ``PyOSInputHook``. This means that applications that are meant to be used both |
|
1020 | 1020 | in IPython and as standalone apps need to have special code to detects how the |
|
1021 | 1021 | application is being run. We highly recommend using IPython's support for this. |
|
1022 | 1022 | Since the details vary slightly between toolkits, we point you to the various |
|
1023 | 1023 | examples in our source directory :file:`docs/examples/lib` that demonstrate |
|
1024 | 1024 | these capabilities. |
|
1025 | 1025 | |
|
1026 | 1026 | Third, unlike previous versions of IPython, we no longer "hijack" (replace |
|
1027 | 1027 | them with no-ops) the event loops. This is done to allow applications that |
|
1028 | 1028 | actually need to run the real event loops to do so. This is often needed to |
|
1029 | 1029 | process pending events at critical points. |
|
1030 | 1030 | |
|
1031 | 1031 | Finally, we also have a number of examples in our source directory |
|
1032 | 1032 | :file:`docs/examples/lib` that demonstrate these capabilities. |
|
1033 | 1033 | |
|
1034 | 1034 | PyQt and PySide |
|
1035 | 1035 | --------------- |
|
1036 | 1036 | |
|
1037 | 1037 | .. attempt at explanation of the complete mess that is Qt support |
|
1038 | 1038 | |
|
1039 | 1039 | When you use ``--gui=qt`` or ``--pylab=qt``, IPython can work with either |
|
1040 | 1040 | PyQt4 or PySide. There are three options for configuration here, because |
|
1041 | 1041 | PyQt4 has two APIs for QString and QVariant - v1, which is the default on |
|
1042 | 1042 | Python 2, and the more natural v2, which is the only API supported by PySide. |
|
1043 | 1043 | v2 is also the default for PyQt4 on Python 3. IPython's code for the QtConsole |
|
1044 | 1044 | uses v2, but you can still use any interface in your code, since the |
|
1045 | 1045 | Qt frontend is in a different process. |
|
1046 | 1046 | |
|
1047 | 1047 | The default will be to import PyQt4 without configuration of the APIs, thus |
|
1048 | 1048 | matching what most applications would expect. It will fall back of PySide if |
|
1049 | 1049 | PyQt4 is unavailable. |
|
1050 | 1050 | |
|
1051 | 1051 | If specified, IPython will respect the environment variable ``QT_API`` used |
|
1052 | 1052 | by ETS. ETS 4.0 also works with both PyQt4 and PySide, but it requires |
|
1053 | 1053 | PyQt4 to use its v2 API. So if ``QT_API=pyside`` PySide will be used, |
|
1054 | 1054 | and if ``QT_API=pyqt`` then PyQt4 will be used *with the v2 API* for |
|
1055 | 1055 | QString and QVariant, so ETS codes like MayaVi will also work with IPython. |
|
1056 | 1056 | |
|
1057 | 1057 | If you launch IPython in pylab mode with ``ipython --pylab=qt``, then IPython |
|
1058 | 1058 | will ask matplotlib which Qt library to use (only if QT_API is *not set*), via |
|
1059 | 1059 | the 'backend.qt4' rcParam. If matplotlib is version 1.0.1 or older, then |
|
1060 | 1060 | IPython will always use PyQt4 without setting the v2 APIs, since neither v2 |
|
1061 | 1061 | PyQt nor PySide work. |
|
1062 | 1062 | |
|
1063 | 1063 | .. warning:: |
|
1064 | 1064 | |
|
1065 | 1065 | Note that this means for ETS 4 to work with PyQt4, ``QT_API`` *must* be set |
|
1066 | 1066 | to work with IPython's qt integration, because otherwise PyQt4 will be |
|
1067 | 1067 | loaded in an incompatible mode. |
|
1068 | 1068 | |
|
1069 | 1069 | It also means that you must *not* have ``QT_API`` set if you want to |
|
1070 | 1070 | use ``--gui=qt`` with code that requires PyQt4 API v1. |
|
1071 | 1071 | |
|
1072 | 1072 | |
|
1073 | 1073 | .. _matplotlib_support: |
|
1074 | 1074 | |
|
1075 | 1075 | Plotting with matplotlib |
|
1076 | 1076 | ======================== |
|
1077 | 1077 | |
|
1078 | 1078 | `Matplotlib`_ provides high quality 2D and 3D plotting for Python. Matplotlib |
|
1079 | 1079 | can produce plots on screen using a variety of GUI toolkits, including Tk, |
|
1080 | 1080 | PyGTK, PyQt4 and wxPython. It also provides a number of commands useful for |
|
1081 | 1081 | scientific computing, all with a syntax compatible with that of the popular |
|
1082 | 1082 | Matlab program. |
|
1083 | 1083 | |
|
1084 | 1084 | To start IPython with matplotlib support, use the ``--pylab`` switch. If no |
|
1085 | 1085 | arguments are given, IPython will automatically detect your choice of |
|
1086 | 1086 | matplotlib backend. You can also request a specific backend with ``--pylab |
|
1087 | 1087 | backend``, where ``backend`` must be one of: 'tk', 'qt', 'wx', 'gtk', 'osx'. |
|
1088 | 1088 | In the web notebook and Qt console, 'inline' is also a valid backend value, |
|
1089 | 1089 | which produces static figures inlined inside the application window instead of |
|
1090 | 1090 | matplotlib's interactive figures that live in separate windows. |
|
1091 | 1091 | |
|
1092 | 1092 | .. _Matplotlib: http://matplotlib.sourceforge.net |
|
1093 | 1093 | |
|
1094 | 1094 | .. _interactive_demos: |
|
1095 | 1095 | |
|
1096 | 1096 | Interactive demos with IPython |
|
1097 | 1097 | ============================== |
|
1098 | 1098 | |
|
1099 | 1099 | IPython ships with a basic system for running scripts interactively in |
|
1100 | 1100 | sections, useful when presenting code to audiences. A few tags embedded |
|
1101 | 1101 | in comments (so that the script remains valid Python code) divide a file |
|
1102 | 1102 | into separate blocks, and the demo can be run one block at a time, with |
|
1103 | 1103 | IPython printing (with syntax highlighting) the block before executing |
|
1104 | 1104 | it, and returning to the interactive prompt after each block. The |
|
1105 | 1105 | interactive namespace is updated after each block is run with the |
|
1106 | 1106 | contents of the demo's namespace. |
|
1107 | 1107 | |
|
1108 | 1108 | This allows you to show a piece of code, run it and then execute |
|
1109 | 1109 | interactively commands based on the variables just created. Once you |
|
1110 | 1110 | want to continue, you simply execute the next block of the demo. The |
|
1111 | 1111 | following listing shows the markup necessary for dividing a script into |
|
1112 | 1112 | sections for execution as a demo: |
|
1113 | 1113 | |
|
1114 | 1114 | .. literalinclude:: ../../examples/lib/example-demo.py |
|
1115 | 1115 | :language: python |
|
1116 | 1116 | |
|
1117 | 1117 | In order to run a file as a demo, you must first make a Demo object out |
|
1118 | 1118 | of it. If the file is named myscript.py, the following code will make a |
|
1119 | 1119 | demo:: |
|
1120 | 1120 | |
|
1121 | 1121 | from IPython.lib.demo import Demo |
|
1122 | 1122 | |
|
1123 | 1123 | mydemo = Demo('myscript.py') |
|
1124 | 1124 | |
|
1125 | 1125 | This creates the mydemo object, whose blocks you run one at a time by |
|
1126 | 1126 | simply calling the object with no arguments. If you have autocall active |
|
1127 | 1127 | in IPython (the default), all you need to do is type:: |
|
1128 | 1128 | |
|
1129 | 1129 | mydemo |
|
1130 | 1130 | |
|
1131 | 1131 | and IPython will call it, executing each block. Demo objects can be |
|
1132 | 1132 | restarted, you can move forward or back skipping blocks, re-execute the |
|
1133 | 1133 | last block, etc. Simply use the Tab key on a demo object to see its |
|
1134 | 1134 | methods, and call '?' on them to see their docstrings for more usage |
|
1135 | 1135 | details. In addition, the demo module itself contains a comprehensive |
|
1136 | 1136 | docstring, which you can access via:: |
|
1137 | 1137 | |
|
1138 | 1138 | from IPython.lib import demo |
|
1139 | 1139 | |
|
1140 | 1140 | demo? |
|
1141 | 1141 | |
|
1142 | 1142 | Limitations: It is important to note that these demos are limited to |
|
1143 | 1143 | fairly simple uses. In particular, you cannot break up sections within |
|
1144 | 1144 | indented code (loops, if statements, function definitions, etc.) |
|
1145 | 1145 | Supporting something like this would basically require tracking the |
|
1146 | 1146 | internal execution state of the Python interpreter, so only top-level |
|
1147 | 1147 | divisions are allowed. If you want to be able to open an IPython |
|
1148 | 1148 | instance at an arbitrary point in a program, you can use IPython's |
|
1149 | 1149 | embedding facilities, see :func:`IPython.embed` for details. |
|
1150 | 1150 |
General Comments 0
You need to be logged in to leave comments.
Login now