Show More
@@ -1,535 +1,544 | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """ |
|
2 | """ | |
3 | Pdb debugger class. |
|
3 | Pdb debugger class. | |
4 |
|
4 | |||
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that |
|
5 | Modified from the standard pdb.Pdb class to avoid including readline, so that | |
6 | the command line completion of other programs which include this isn't |
|
6 | the command line completion of other programs which include this isn't | |
7 | damaged. |
|
7 | damaged. | |
8 |
|
8 | |||
9 | In the future, this class will be expanded with improvements over the standard |
|
9 | In the future, this class will be expanded with improvements over the standard | |
10 | pdb. |
|
10 | pdb. | |
11 |
|
11 | |||
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor |
|
12 | The code in this file is mainly lifted out of cmd.py in Python 2.2, with minor | |
13 | changes. Licensing should therefore be under the standard Python terms. For |
|
13 | changes. Licensing should therefore be under the standard Python terms. For | |
14 | details on the PSF (Python Software Foundation) standard license, see: |
|
14 | details on the PSF (Python Software Foundation) standard license, see: | |
15 |
|
15 | |||
16 | http://www.python.org/2.2.3/license.html""" |
|
16 | http://www.python.org/2.2.3/license.html""" | |
17 |
|
17 | |||
18 | #***************************************************************************** |
|
18 | #***************************************************************************** | |
19 | # |
|
19 | # | |
20 | # This file is licensed under the PSF license. |
|
20 | # This file is licensed under the PSF license. | |
21 | # |
|
21 | # | |
22 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
22 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> |
|
23 | # Copyright (C) 2005-2006 Fernando Perez. <fperez@colorado.edu> | |
24 | # |
|
24 | # | |
25 | # |
|
25 | # | |
26 | #***************************************************************************** |
|
26 | #***************************************************************************** | |
27 | from __future__ import print_function |
|
27 | from __future__ import print_function | |
28 |
|
28 | |||
29 | import bdb |
|
29 | import bdb | |
30 | import linecache |
|
30 | import linecache | |
31 | import sys |
|
31 | import sys | |
32 |
|
32 | |||
33 | from IPython.utils import PyColorize, ulinecache |
|
33 | from IPython.utils import PyColorize, ulinecache | |
34 | from IPython.core import ipapi |
|
34 | from IPython.core import ipapi | |
35 | from IPython.utils import coloransi, io, openpy, py3compat |
|
35 | from IPython.utils import coloransi, io, openpy, py3compat | |
36 | from IPython.core.excolors import exception_colors |
|
36 | from IPython.core.excolors import exception_colors | |
37 |
|
37 | |||
38 | # See if we can use pydb. |
|
38 | # See if we can use pydb. | |
39 | has_pydb = False |
|
39 | has_pydb = False | |
40 | prompt = 'ipdb> ' |
|
40 | prompt = 'ipdb> ' | |
41 | #We have to check this directly from sys.argv, config struct not yet available |
|
41 | #We have to check this directly from sys.argv, config struct not yet available | |
42 | if '--pydb' in sys.argv: |
|
42 | if '--pydb' in sys.argv: | |
43 | try: |
|
43 | try: | |
44 | import pydb |
|
44 | import pydb | |
45 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': |
|
45 | if hasattr(pydb.pydb, "runl") and pydb.version>'1.17': | |
46 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we |
|
46 | # Version 1.17 is broken, and that's what ships with Ubuntu Edgy, so we | |
47 | # better protect against it. |
|
47 | # better protect against it. | |
48 | has_pydb = True |
|
48 | has_pydb = True | |
49 | except ImportError: |
|
49 | except ImportError: | |
50 | print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available") |
|
50 | print("Pydb (http://bashdb.sourceforge.net/pydb/) does not seem to be available") | |
51 |
|
51 | |||
52 | if has_pydb: |
|
52 | if has_pydb: | |
53 | from pydb import Pdb as OldPdb |
|
53 | from pydb import Pdb as OldPdb | |
54 | #print "Using pydb for %run -d and post-mortem" #dbg |
|
54 | #print "Using pydb for %run -d and post-mortem" #dbg | |
55 | prompt = 'ipydb> ' |
|
55 | prompt = 'ipydb> ' | |
56 | else: |
|
56 | else: | |
57 | from pdb import Pdb as OldPdb |
|
57 | from pdb import Pdb as OldPdb | |
58 |
|
58 | |||
59 | # Allow the set_trace code to operate outside of an ipython instance, even if |
|
59 | # Allow the set_trace code to operate outside of an ipython instance, even if | |
60 | # it does so with some limitations. The rest of this support is implemented in |
|
60 | # it does so with some limitations. The rest of this support is implemented in | |
61 | # the Tracer constructor. |
|
61 | # the Tracer constructor. | |
62 | def BdbQuit_excepthook(et,ev,tb): |
|
62 | def BdbQuit_excepthook(et,ev,tb): | |
63 | if et==bdb.BdbQuit: |
|
63 | if et==bdb.BdbQuit: | |
64 | print('Exiting Debugger.') |
|
64 | print('Exiting Debugger.') | |
65 | else: |
|
65 | else: | |
66 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) |
|
66 | BdbQuit_excepthook.excepthook_ori(et,ev,tb) | |
67 |
|
67 | |||
68 | def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): |
|
68 | def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None): | |
69 | print('Exiting Debugger.') |
|
69 | print('Exiting Debugger.') | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | class Tracer(object): |
|
72 | class Tracer(object): | |
73 | """Class for local debugging, similar to pdb.set_trace. |
|
73 | """Class for local debugging, similar to pdb.set_trace. | |
74 |
|
74 | |||
75 | Instances of this class, when called, behave like pdb.set_trace, but |
|
75 | Instances of this class, when called, behave like pdb.set_trace, but | |
76 | providing IPython's enhanced capabilities. |
|
76 | providing IPython's enhanced capabilities. | |
77 |
|
77 | |||
78 | This is implemented as a class which must be initialized in your own code |
|
78 | This is implemented as a class which must be initialized in your own code | |
79 | and not as a standalone function because we need to detect at runtime |
|
79 | and not as a standalone function because we need to detect at runtime | |
80 | whether IPython is already active or not. That detection is done in the |
|
80 | whether IPython is already active or not. That detection is done in the | |
81 | constructor, ensuring that this code plays nicely with a running IPython, |
|
81 | constructor, ensuring that this code plays nicely with a running IPython, | |
82 | while functioning acceptably (though with limitations) if outside of it. |
|
82 | while functioning acceptably (though with limitations) if outside of it. | |
83 | """ |
|
83 | """ | |
84 |
|
84 | |||
85 | def __init__(self,colors=None): |
|
85 | def __init__(self,colors=None): | |
86 | """Create a local debugger instance. |
|
86 | """Create a local debugger instance. | |
87 |
|
87 | |||
88 | :Parameters: |
|
88 | :Parameters: | |
89 |
|
89 | |||
90 | - `colors` (None): a string containing the name of the color scheme to |
|
90 | - `colors` (None): a string containing the name of the color scheme to | |
91 | use, it must be one of IPython's valid color schemes. If not given, the |
|
91 | use, it must be one of IPython's valid color schemes. If not given, the | |
92 | function will default to the current IPython scheme when running inside |
|
92 | function will default to the current IPython scheme when running inside | |
93 | IPython, and to 'NoColor' otherwise. |
|
93 | IPython, and to 'NoColor' otherwise. | |
94 |
|
94 | |||
95 | Usage example: |
|
95 | Usage example: | |
96 |
|
96 | |||
97 | from IPython.core.debugger import Tracer; debug_here = Tracer() |
|
97 | from IPython.core.debugger import Tracer; debug_here = Tracer() | |
98 |
|
98 | |||
99 | ... later in your code |
|
99 | ... later in your code | |
100 | debug_here() # -> will open up the debugger at that point. |
|
100 | debug_here() # -> will open up the debugger at that point. | |
101 |
|
101 | |||
102 | Once the debugger activates, you can use all of its regular commands to |
|
102 | Once the debugger activates, you can use all of its regular commands to | |
103 | step through code, set breakpoints, etc. See the pdb documentation |
|
103 | step through code, set breakpoints, etc. See the pdb documentation | |
104 | from the Python standard library for usage details. |
|
104 | from the Python standard library for usage details. | |
105 | """ |
|
105 | """ | |
106 |
|
106 | |||
107 | try: |
|
107 | try: | |
108 | ip = get_ipython() |
|
108 | ip = get_ipython() | |
109 | except NameError: |
|
109 | except NameError: | |
110 | # Outside of ipython, we set our own exception hook manually |
|
110 | # Outside of ipython, we set our own exception hook manually | |
111 | BdbQuit_excepthook.excepthook_ori = sys.excepthook |
|
111 | BdbQuit_excepthook.excepthook_ori = sys.excepthook | |
112 | sys.excepthook = BdbQuit_excepthook |
|
112 | sys.excepthook = BdbQuit_excepthook | |
113 | def_colors = 'NoColor' |
|
113 | def_colors = 'NoColor' | |
114 | try: |
|
114 | try: | |
115 | # Limited tab completion support |
|
115 | # Limited tab completion support | |
116 | import readline |
|
116 | import readline | |
117 | readline.parse_and_bind('tab: complete') |
|
117 | readline.parse_and_bind('tab: complete') | |
118 | except ImportError: |
|
118 | except ImportError: | |
119 | pass |
|
119 | pass | |
120 | else: |
|
120 | else: | |
121 | # In ipython, we use its custom exception handler mechanism |
|
121 | # In ipython, we use its custom exception handler mechanism | |
122 | def_colors = ip.colors |
|
122 | def_colors = ip.colors | |
123 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) |
|
123 | ip.set_custom_exc((bdb.BdbQuit,), BdbQuit_IPython_excepthook) | |
124 |
|
124 | |||
125 | if colors is None: |
|
125 | if colors is None: | |
126 | colors = def_colors |
|
126 | colors = def_colors | |
127 |
|
127 | |||
128 | # The stdlib debugger internally uses a modified repr from the `repr` |
|
128 | # The stdlib debugger internally uses a modified repr from the `repr` | |
129 | # module, that limits the length of printed strings to a hardcoded |
|
129 | # module, that limits the length of printed strings to a hardcoded | |
130 | # limit of 30 characters. That much trimming is too aggressive, let's |
|
130 | # limit of 30 characters. That much trimming is too aggressive, let's | |
131 | # at least raise that limit to 80 chars, which should be enough for |
|
131 | # at least raise that limit to 80 chars, which should be enough for | |
132 | # most interactive uses. |
|
132 | # most interactive uses. | |
133 | try: |
|
133 | try: | |
134 | from repr import aRepr |
|
134 | from repr import aRepr | |
135 | aRepr.maxstring = 80 |
|
135 | aRepr.maxstring = 80 | |
136 | except: |
|
136 | except: | |
137 | # This is only a user-facing convenience, so any error we encounter |
|
137 | # This is only a user-facing convenience, so any error we encounter | |
138 | # here can be warned about but can be otherwise ignored. These |
|
138 | # here can be warned about but can be otherwise ignored. These | |
139 | # printouts will tell us about problems if this API changes |
|
139 | # printouts will tell us about problems if this API changes | |
140 | import traceback |
|
140 | import traceback | |
141 | traceback.print_exc() |
|
141 | traceback.print_exc() | |
142 |
|
142 | |||
143 | self.debugger = Pdb(colors) |
|
143 | self.debugger = Pdb(colors) | |
144 |
|
144 | |||
145 | def __call__(self): |
|
145 | def __call__(self): | |
146 | """Starts an interactive debugger at the point where called. |
|
146 | """Starts an interactive debugger at the point where called. | |
147 |
|
147 | |||
148 | This is similar to the pdb.set_trace() function from the std lib, but |
|
148 | This is similar to the pdb.set_trace() function from the std lib, but | |
149 | using IPython's enhanced debugger.""" |
|
149 | using IPython's enhanced debugger.""" | |
150 |
|
150 | |||
151 | self.debugger.set_trace(sys._getframe().f_back) |
|
151 | self.debugger.set_trace(sys._getframe().f_back) | |
152 |
|
152 | |||
153 |
|
153 | |||
154 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): |
|
154 | def decorate_fn_with_doc(new_fn, old_fn, additional_text=""): | |
155 | """Make new_fn have old_fn's doc string. This is particularly useful |
|
155 | """Make new_fn have old_fn's doc string. This is particularly useful | |
156 | for the do_... commands that hook into the help system. |
|
156 | for the do_... commands that hook into the help system. | |
157 | Adapted from from a comp.lang.python posting |
|
157 | Adapted from from a comp.lang.python posting | |
158 | by Duncan Booth.""" |
|
158 | by Duncan Booth.""" | |
159 | def wrapper(*args, **kw): |
|
159 | def wrapper(*args, **kw): | |
160 | return new_fn(*args, **kw) |
|
160 | return new_fn(*args, **kw) | |
161 | if old_fn.__doc__: |
|
161 | if old_fn.__doc__: | |
162 | wrapper.__doc__ = old_fn.__doc__ + additional_text |
|
162 | wrapper.__doc__ = old_fn.__doc__ + additional_text | |
163 | return wrapper |
|
163 | return wrapper | |
164 |
|
164 | |||
165 |
|
165 | |||
166 | def _file_lines(fname): |
|
166 | def _file_lines(fname): | |
167 | """Return the contents of a named file as a list of lines. |
|
167 | """Return the contents of a named file as a list of lines. | |
168 |
|
168 | |||
169 | This function never raises an IOError exception: if the file can't be |
|
169 | This function never raises an IOError exception: if the file can't be | |
170 | read, it simply returns an empty list.""" |
|
170 | read, it simply returns an empty list.""" | |
171 |
|
171 | |||
172 | try: |
|
172 | try: | |
173 | outfile = open(fname) |
|
173 | outfile = open(fname) | |
174 | except IOError: |
|
174 | except IOError: | |
175 | return [] |
|
175 | return [] | |
176 | else: |
|
176 | else: | |
177 | out = outfile.readlines() |
|
177 | out = outfile.readlines() | |
178 | outfile.close() |
|
178 | outfile.close() | |
179 | return out |
|
179 | return out | |
180 |
|
180 | |||
181 |
|
181 | |||
182 | class Pdb(OldPdb): |
|
182 | class Pdb(OldPdb): | |
183 | """Modified Pdb class, does not load readline.""" |
|
183 | """Modified Pdb class, does not load readline.""" | |
184 |
|
184 | |||
185 | def __init__(self,color_scheme='NoColor',completekey=None, |
|
185 | def __init__(self,color_scheme='NoColor',completekey=None, | |
186 | stdin=None, stdout=None): |
|
186 | stdin=None, stdout=None): | |
187 |
|
187 | |||
188 | # Parent constructor: |
|
188 | # Parent constructor: | |
189 | if has_pydb and completekey is None: |
|
189 | if has_pydb and completekey is None: | |
190 | OldPdb.__init__(self,stdin=stdin,stdout=io.stdout) |
|
190 | OldPdb.__init__(self,stdin=stdin,stdout=io.stdout) | |
191 | else: |
|
191 | else: | |
192 | OldPdb.__init__(self,completekey,stdin,stdout) |
|
192 | OldPdb.__init__(self,completekey,stdin,stdout) | |
193 |
|
193 | |||
194 | self.prompt = prompt # The default prompt is '(Pdb)' |
|
194 | self.prompt = prompt # The default prompt is '(Pdb)' | |
195 |
|
195 | |||
196 | # IPython changes... |
|
196 | # IPython changes... | |
197 | self.is_pydb = has_pydb |
|
197 | self.is_pydb = has_pydb | |
198 |
|
198 | |||
199 | self.shell = ipapi.get() |
|
199 | self.shell = ipapi.get() | |
200 |
|
200 | |||
201 | if self.is_pydb: |
|
201 | if self.is_pydb: | |
202 |
|
202 | |||
203 | # interactiveshell.py's ipalias seems to want pdb's checkline |
|
203 | # interactiveshell.py's ipalias seems to want pdb's checkline | |
204 | # which located in pydb.fn |
|
204 | # which located in pydb.fn | |
205 | import pydb.fns |
|
205 | import pydb.fns | |
206 | self.checkline = lambda filename, lineno: \ |
|
206 | self.checkline = lambda filename, lineno: \ | |
207 | pydb.fns.checkline(self, filename, lineno) |
|
207 | pydb.fns.checkline(self, filename, lineno) | |
208 |
|
208 | |||
209 | self.curframe = None |
|
209 | self.curframe = None | |
210 | self.do_restart = self.new_do_restart |
|
210 | self.do_restart = self.new_do_restart | |
211 |
|
211 | |||
212 | self.old_all_completions = self.shell.Completer.all_completions |
|
212 | self.old_all_completions = self.shell.Completer.all_completions | |
213 | self.shell.Completer.all_completions=self.all_completions |
|
213 | self.shell.Completer.all_completions=self.all_completions | |
214 |
|
214 | |||
215 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, |
|
215 | self.do_list = decorate_fn_with_doc(self.list_command_pydb, | |
216 | OldPdb.do_list) |
|
216 | OldPdb.do_list) | |
217 | self.do_l = self.do_list |
|
217 | self.do_l = self.do_list | |
218 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, |
|
218 | self.do_frame = decorate_fn_with_doc(self.new_do_frame, | |
219 | OldPdb.do_frame) |
|
219 | OldPdb.do_frame) | |
220 |
|
220 | |||
221 | self.aliases = {} |
|
221 | self.aliases = {} | |
222 |
|
222 | |||
223 | # Create color table: we copy the default one from the traceback |
|
223 | # Create color table: we copy the default one from the traceback | |
224 | # module and add a few attributes needed for debugging |
|
224 | # module and add a few attributes needed for debugging | |
225 | self.color_scheme_table = exception_colors() |
|
225 | self.color_scheme_table = exception_colors() | |
226 |
|
226 | |||
227 | # shorthands |
|
227 | # shorthands | |
228 | C = coloransi.TermColors |
|
228 | C = coloransi.TermColors | |
229 | cst = self.color_scheme_table |
|
229 | cst = self.color_scheme_table | |
230 |
|
230 | |||
231 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor |
|
231 | cst['NoColor'].colors.breakpoint_enabled = C.NoColor | |
232 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor |
|
232 | cst['NoColor'].colors.breakpoint_disabled = C.NoColor | |
233 |
|
233 | |||
234 | cst['Linux'].colors.breakpoint_enabled = C.LightRed |
|
234 | cst['Linux'].colors.breakpoint_enabled = C.LightRed | |
235 | cst['Linux'].colors.breakpoint_disabled = C.Red |
|
235 | cst['Linux'].colors.breakpoint_disabled = C.Red | |
236 |
|
236 | |||
237 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed |
|
237 | cst['LightBG'].colors.breakpoint_enabled = C.LightRed | |
238 | cst['LightBG'].colors.breakpoint_disabled = C.Red |
|
238 | cst['LightBG'].colors.breakpoint_disabled = C.Red | |
239 |
|
239 | |||
240 | self.set_colors(color_scheme) |
|
240 | self.set_colors(color_scheme) | |
241 |
|
241 | |||
242 | # Add a python parser so we can syntax highlight source while |
|
242 | # Add a python parser so we can syntax highlight source while | |
243 | # debugging. |
|
243 | # debugging. | |
244 | self.parser = PyColorize.Parser() |
|
244 | self.parser = PyColorize.Parser() | |
245 |
|
245 | |||
246 | def set_colors(self, scheme): |
|
246 | def set_colors(self, scheme): | |
247 | """Shorthand access to the color table scheme selector method.""" |
|
247 | """Shorthand access to the color table scheme selector method.""" | |
248 | self.color_scheme_table.set_active_scheme(scheme) |
|
248 | self.color_scheme_table.set_active_scheme(scheme) | |
249 |
|
249 | |||
250 | def interaction(self, frame, traceback): |
|
250 | def interaction(self, frame, traceback): | |
251 | self.shell.set_completer_frame(frame) |
|
251 | self.shell.set_completer_frame(frame) | |
252 | OldPdb.interaction(self, frame, traceback) |
|
252 | OldPdb.interaction(self, frame, traceback) | |
253 |
|
253 | |||
254 | def new_do_up(self, arg): |
|
254 | def new_do_up(self, arg): | |
255 | OldPdb.do_up(self, arg) |
|
255 | OldPdb.do_up(self, arg) | |
256 | self.shell.set_completer_frame(self.curframe) |
|
256 | self.shell.set_completer_frame(self.curframe) | |
257 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) |
|
257 | do_u = do_up = decorate_fn_with_doc(new_do_up, OldPdb.do_up) | |
258 |
|
258 | |||
259 | def new_do_down(self, arg): |
|
259 | def new_do_down(self, arg): | |
260 | OldPdb.do_down(self, arg) |
|
260 | OldPdb.do_down(self, arg) | |
261 | self.shell.set_completer_frame(self.curframe) |
|
261 | self.shell.set_completer_frame(self.curframe) | |
262 |
|
262 | |||
263 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) |
|
263 | do_d = do_down = decorate_fn_with_doc(new_do_down, OldPdb.do_down) | |
264 |
|
264 | |||
265 | def new_do_frame(self, arg): |
|
265 | def new_do_frame(self, arg): | |
266 | OldPdb.do_frame(self, arg) |
|
266 | OldPdb.do_frame(self, arg) | |
267 | self.shell.set_completer_frame(self.curframe) |
|
267 | self.shell.set_completer_frame(self.curframe) | |
268 |
|
268 | |||
269 | def new_do_quit(self, arg): |
|
269 | def new_do_quit(self, arg): | |
270 |
|
270 | |||
271 | if hasattr(self, 'old_all_completions'): |
|
271 | if hasattr(self, 'old_all_completions'): | |
272 | self.shell.Completer.all_completions=self.old_all_completions |
|
272 | self.shell.Completer.all_completions=self.old_all_completions | |
273 |
|
273 | |||
274 |
|
274 | |||
275 | return OldPdb.do_quit(self, arg) |
|
275 | return OldPdb.do_quit(self, arg) | |
276 |
|
276 | |||
277 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) |
|
277 | do_q = do_quit = decorate_fn_with_doc(new_do_quit, OldPdb.do_quit) | |
278 |
|
278 | |||
279 | def new_do_restart(self, arg): |
|
279 | def new_do_restart(self, arg): | |
280 | """Restart command. In the context of ipython this is exactly the same |
|
280 | """Restart command. In the context of ipython this is exactly the same | |
281 | thing as 'quit'.""" |
|
281 | thing as 'quit'.""" | |
282 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") |
|
282 | self.msg("Restart doesn't make sense here. Using 'quit' instead.") | |
283 | return self.do_quit(arg) |
|
283 | return self.do_quit(arg) | |
284 |
|
284 | |||
285 | def postloop(self): |
|
285 | def postloop(self): | |
286 | self.shell.set_completer_frame(None) |
|
286 | self.shell.set_completer_frame(None) | |
287 |
|
287 | |||
288 | def print_stack_trace(self): |
|
288 | def print_stack_trace(self): | |
289 | try: |
|
289 | try: | |
290 | for frame_lineno in self.stack: |
|
290 | for frame_lineno in self.stack: | |
291 | self.print_stack_entry(frame_lineno, context = 5) |
|
291 | self.print_stack_entry(frame_lineno, context = 5) | |
292 | except KeyboardInterrupt: |
|
292 | except KeyboardInterrupt: | |
293 | pass |
|
293 | pass | |
294 |
|
294 | |||
295 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', |
|
295 | def print_stack_entry(self,frame_lineno,prompt_prefix='\n-> ', | |
296 | context = 3): |
|
296 | context = 3): | |
297 | #frame, lineno = frame_lineno |
|
297 | #frame, lineno = frame_lineno | |
298 | print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout) |
|
298 | print(self.format_stack_entry(frame_lineno, '', context), file=io.stdout) | |
299 |
|
299 | |||
300 | # vds: >> |
|
300 | # vds: >> | |
301 | frame, lineno = frame_lineno |
|
301 | frame, lineno = frame_lineno | |
302 | filename = frame.f_code.co_filename |
|
302 | filename = frame.f_code.co_filename | |
303 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
303 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
304 | # vds: << |
|
304 | # vds: << | |
305 |
|
305 | |||
306 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): |
|
306 | def format_stack_entry(self, frame_lineno, lprefix=': ', context = 3): | |
307 | import repr |
|
307 | import repr | |
308 |
|
308 | |||
309 | ret = [] |
|
309 | ret = [] | |
310 |
|
310 | |||
311 | Colors = self.color_scheme_table.active_colors |
|
311 | Colors = self.color_scheme_table.active_colors | |
312 | ColorsNormal = Colors.Normal |
|
312 | ColorsNormal = Colors.Normal | |
313 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) |
|
313 | tpl_link = u'%s%%s%s' % (Colors.filenameEm, ColorsNormal) | |
314 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) |
|
314 | tpl_call = u'%s%%s%s%%s%s' % (Colors.vName, Colors.valEm, ColorsNormal) | |
315 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
315 | tpl_line = u'%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
316 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, |
|
316 | tpl_line_em = u'%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, | |
317 | ColorsNormal) |
|
317 | ColorsNormal) | |
318 |
|
318 | |||
319 | frame, lineno = frame_lineno |
|
319 | frame, lineno = frame_lineno | |
320 |
|
320 | |||
321 | return_value = '' |
|
321 | return_value = '' | |
322 | if '__return__' in frame.f_locals: |
|
322 | if '__return__' in frame.f_locals: | |
323 | rv = frame.f_locals['__return__'] |
|
323 | rv = frame.f_locals['__return__'] | |
324 | #return_value += '->' |
|
324 | #return_value += '->' | |
325 | return_value += repr.repr(rv) + '\n' |
|
325 | return_value += repr.repr(rv) + '\n' | |
326 | ret.append(return_value) |
|
326 | ret.append(return_value) | |
327 |
|
327 | |||
328 | #s = filename + '(' + `lineno` + ')' |
|
328 | #s = filename + '(' + `lineno` + ')' | |
329 | filename = self.canonic(frame.f_code.co_filename) |
|
329 | filename = self.canonic(frame.f_code.co_filename) | |
330 | link = tpl_link % py3compat.cast_unicode(filename) |
|
330 | link = tpl_link % py3compat.cast_unicode(filename) | |
331 |
|
331 | |||
332 | if frame.f_code.co_name: |
|
332 | if frame.f_code.co_name: | |
333 | func = frame.f_code.co_name |
|
333 | func = frame.f_code.co_name | |
334 | else: |
|
334 | else: | |
335 | func = "<lambda>" |
|
335 | func = "<lambda>" | |
336 |
|
336 | |||
337 | call = '' |
|
337 | call = '' | |
338 | if func != '?': |
|
338 | if func != '?': | |
339 | if '__args__' in frame.f_locals: |
|
339 | if '__args__' in frame.f_locals: | |
340 | args = repr.repr(frame.f_locals['__args__']) |
|
340 | args = repr.repr(frame.f_locals['__args__']) | |
341 | else: |
|
341 | else: | |
342 | args = '()' |
|
342 | args = '()' | |
343 | call = tpl_call % (func, args) |
|
343 | call = tpl_call % (func, args) | |
344 |
|
344 | |||
345 | # The level info should be generated in the same format pdb uses, to |
|
345 | # The level info should be generated in the same format pdb uses, to | |
346 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. |
|
346 | # avoid breaking the pdbtrack functionality of python-mode in *emacs. | |
347 | if frame is self.curframe: |
|
347 | if frame is self.curframe: | |
348 | ret.append('> ') |
|
348 | ret.append('> ') | |
349 | else: |
|
349 | else: | |
350 | ret.append(' ') |
|
350 | ret.append(' ') | |
351 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) |
|
351 | ret.append(u'%s(%s)%s\n' % (link,lineno,call)) | |
352 |
|
352 | |||
353 | start = lineno - 1 - context//2 |
|
353 | start = lineno - 1 - context//2 | |
354 | lines = ulinecache.getlines(filename) |
|
354 | lines = ulinecache.getlines(filename) | |
355 | start = max(start, 0) |
|
355 | start = max(start, 0) | |
356 | start = min(start, len(lines) - context) |
|
356 | start = min(start, len(lines) - context) | |
357 | lines = lines[start : start + context] |
|
357 | lines = lines[start : start + context] | |
358 |
|
358 | |||
359 | for i,line in enumerate(lines): |
|
359 | for i,line in enumerate(lines): | |
360 | show_arrow = (start + 1 + i == lineno) |
|
360 | show_arrow = (start + 1 + i == lineno) | |
361 | linetpl = (frame is self.curframe or show_arrow) \ |
|
361 | linetpl = (frame is self.curframe or show_arrow) \ | |
362 | and tpl_line_em \ |
|
362 | and tpl_line_em \ | |
363 | or tpl_line |
|
363 | or tpl_line | |
364 | ret.append(self.__format_line(linetpl, filename, |
|
364 | ret.append(self.__format_line(linetpl, filename, | |
365 | start + 1 + i, line, |
|
365 | start + 1 + i, line, | |
366 | arrow = show_arrow) ) |
|
366 | arrow = show_arrow) ) | |
367 | return ''.join(ret) |
|
367 | return ''.join(ret) | |
368 |
|
368 | |||
369 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): |
|
369 | def __format_line(self, tpl_line, filename, lineno, line, arrow = False): | |
370 | bp_mark = "" |
|
370 | bp_mark = "" | |
371 | bp_mark_color = "" |
|
371 | bp_mark_color = "" | |
372 |
|
372 | |||
373 | scheme = self.color_scheme_table.active_scheme_name |
|
373 | scheme = self.color_scheme_table.active_scheme_name | |
374 | new_line, err = self.parser.format2(line, 'str', scheme) |
|
374 | new_line, err = self.parser.format2(line, 'str', scheme) | |
375 | if not err: line = new_line |
|
375 | if not err: line = new_line | |
376 |
|
376 | |||
377 | bp = None |
|
377 | bp = None | |
378 | if lineno in self.get_file_breaks(filename): |
|
378 | if lineno in self.get_file_breaks(filename): | |
379 | bps = self.get_breaks(filename, lineno) |
|
379 | bps = self.get_breaks(filename, lineno) | |
380 | bp = bps[-1] |
|
380 | bp = bps[-1] | |
381 |
|
381 | |||
382 | if bp: |
|
382 | if bp: | |
383 | Colors = self.color_scheme_table.active_colors |
|
383 | Colors = self.color_scheme_table.active_colors | |
384 | bp_mark = str(bp.number) |
|
384 | bp_mark = str(bp.number) | |
385 | bp_mark_color = Colors.breakpoint_enabled |
|
385 | bp_mark_color = Colors.breakpoint_enabled | |
386 | if not bp.enabled: |
|
386 | if not bp.enabled: | |
387 | bp_mark_color = Colors.breakpoint_disabled |
|
387 | bp_mark_color = Colors.breakpoint_disabled | |
388 |
|
388 | |||
389 | numbers_width = 7 |
|
389 | numbers_width = 7 | |
390 | if arrow: |
|
390 | if arrow: | |
391 | # This is the line with the error |
|
391 | # This is the line with the error | |
392 | pad = numbers_width - len(str(lineno)) - len(bp_mark) |
|
392 | pad = numbers_width - len(str(lineno)) - len(bp_mark) | |
393 | if pad >= 3: |
|
393 | if pad >= 3: | |
394 | marker = '-'*(pad-3) + '-> ' |
|
394 | marker = '-'*(pad-3) + '-> ' | |
395 | elif pad == 2: |
|
395 | elif pad == 2: | |
396 | marker = '> ' |
|
396 | marker = '> ' | |
397 | elif pad == 1: |
|
397 | elif pad == 1: | |
398 | marker = '>' |
|
398 | marker = '>' | |
399 | else: |
|
399 | else: | |
400 | marker = '' |
|
400 | marker = '' | |
401 | num = '%s%s' % (marker, str(lineno)) |
|
401 | num = '%s%s' % (marker, str(lineno)) | |
402 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
402 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
403 | else: |
|
403 | else: | |
404 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) |
|
404 | num = '%*s' % (numbers_width - len(bp_mark), str(lineno)) | |
405 | line = tpl_line % (bp_mark_color + bp_mark, num, line) |
|
405 | line = tpl_line % (bp_mark_color + bp_mark, num, line) | |
406 |
|
406 | |||
407 | return line |
|
407 | return line | |
408 |
|
408 | |||
409 | def list_command_pydb(self, arg): |
|
409 | def list_command_pydb(self, arg): | |
410 | """List command to use if we have a newer pydb installed""" |
|
410 | """List command to use if we have a newer pydb installed""" | |
411 | filename, first, last = OldPdb.parse_list_cmd(self, arg) |
|
411 | filename, first, last = OldPdb.parse_list_cmd(self, arg) | |
412 | if filename is not None: |
|
412 | if filename is not None: | |
413 | self.print_list_lines(filename, first, last) |
|
413 | self.print_list_lines(filename, first, last) | |
414 |
|
414 | |||
415 | def print_list_lines(self, filename, first, last): |
|
415 | def print_list_lines(self, filename, first, last): | |
416 | """The printing (as opposed to the parsing part of a 'list' |
|
416 | """The printing (as opposed to the parsing part of a 'list' | |
417 | command.""" |
|
417 | command.""" | |
418 | try: |
|
418 | try: | |
419 | Colors = self.color_scheme_table.active_colors |
|
419 | Colors = self.color_scheme_table.active_colors | |
420 | ColorsNormal = Colors.Normal |
|
420 | ColorsNormal = Colors.Normal | |
421 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) |
|
421 | tpl_line = '%%s%s%%s %s%%s' % (Colors.lineno, ColorsNormal) | |
422 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) |
|
422 | tpl_line_em = '%%s%s%%s %s%%s%s' % (Colors.linenoEm, Colors.line, ColorsNormal) | |
423 | src = [] |
|
423 | src = [] | |
424 | if filename == "<string>" and hasattr(self, "_exec_filename"): |
|
424 | if filename == "<string>" and hasattr(self, "_exec_filename"): | |
425 | filename = self._exec_filename |
|
425 | filename = self._exec_filename | |
426 |
|
426 | |||
427 | for lineno in range(first, last+1): |
|
427 | for lineno in range(first, last+1): | |
428 | line = ulinecache.getline(filename, lineno) |
|
428 | line = ulinecache.getline(filename, lineno) | |
429 | if not line: |
|
429 | if not line: | |
430 | break |
|
430 | break | |
431 |
|
431 | |||
432 | if lineno == self.curframe.f_lineno: |
|
432 | if lineno == self.curframe.f_lineno: | |
433 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) |
|
433 | line = self.__format_line(tpl_line_em, filename, lineno, line, arrow = True) | |
434 | else: |
|
434 | else: | |
435 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) |
|
435 | line = self.__format_line(tpl_line, filename, lineno, line, arrow = False) | |
436 |
|
436 | |||
437 | src.append(line) |
|
437 | src.append(line) | |
438 | self.lineno = lineno |
|
438 | self.lineno = lineno | |
439 |
|
439 | |||
440 | print(''.join(src), file=io.stdout) |
|
440 | print(''.join(src), file=io.stdout) | |
441 |
|
441 | |||
442 | except KeyboardInterrupt: |
|
442 | except KeyboardInterrupt: | |
443 | pass |
|
443 | pass | |
444 |
|
444 | |||
445 | def do_list(self, arg): |
|
445 | def do_list(self, arg): | |
446 | self.lastcmd = 'list' |
|
446 | self.lastcmd = 'list' | |
447 | last = None |
|
447 | last = None | |
448 | if arg: |
|
448 | if arg: | |
449 | try: |
|
449 | try: | |
450 | x = eval(arg, {}, {}) |
|
450 | x = eval(arg, {}, {}) | |
451 | if type(x) == type(()): |
|
451 | if type(x) == type(()): | |
452 | first, last = x |
|
452 | first, last = x | |
453 | first = int(first) |
|
453 | first = int(first) | |
454 | last = int(last) |
|
454 | last = int(last) | |
455 | if last < first: |
|
455 | if last < first: | |
456 | # Assume it's a count |
|
456 | # Assume it's a count | |
457 | last = first + last |
|
457 | last = first + last | |
458 | else: |
|
458 | else: | |
459 | first = max(1, int(x) - 5) |
|
459 | first = max(1, int(x) - 5) | |
460 | except: |
|
460 | except: | |
461 | print('*** Error in argument:', repr(arg)) |
|
461 | print('*** Error in argument:', repr(arg)) | |
462 | return |
|
462 | return | |
463 | elif self.lineno is None: |
|
463 | elif self.lineno is None: | |
464 | first = max(1, self.curframe.f_lineno - 5) |
|
464 | first = max(1, self.curframe.f_lineno - 5) | |
465 | else: |
|
465 | else: | |
466 | first = self.lineno + 1 |
|
466 | first = self.lineno + 1 | |
467 | if last is None: |
|
467 | if last is None: | |
468 | last = first + 10 |
|
468 | last = first + 10 | |
469 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) |
|
469 | self.print_list_lines(self.curframe.f_code.co_filename, first, last) | |
470 |
|
470 | |||
471 | # vds: >> |
|
471 | # vds: >> | |
472 | lineno = first |
|
472 | lineno = first | |
473 | filename = self.curframe.f_code.co_filename |
|
473 | filename = self.curframe.f_code.co_filename | |
474 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) |
|
474 | self.shell.hooks.synchronize_with_editor(filename, lineno, 0) | |
475 | # vds: << |
|
475 | # vds: << | |
476 |
|
476 | |||
477 | do_l = do_list |
|
477 | do_l = do_list | |
478 |
|
478 | |||
479 | def do_pdef(self, arg): |
|
479 | def do_pdef(self, arg): | |
480 | """Print the definition header for any callable object. |
|
480 | """Print the definition header for any callable object. | |
481 |
|
481 | |||
482 | The debugger interface to %pdef""" |
|
482 | The debugger interface to %pdef""" | |
483 | namespaces = [('Locals', self.curframe.f_locals), |
|
483 | namespaces = [('Locals', self.curframe.f_locals), | |
484 | ('Globals', self.curframe.f_globals)] |
|
484 | ('Globals', self.curframe.f_globals)] | |
485 | self.shell.find_line_magic('pdef')(arg, namespaces=namespaces) |
|
485 | self.shell.find_line_magic('pdef')(arg, namespaces=namespaces) | |
486 |
|
486 | |||
487 | def do_pdoc(self, arg): |
|
487 | def do_pdoc(self, arg): | |
488 | """Print the docstring for an object. |
|
488 | """Print the docstring for an object. | |
489 |
|
489 | |||
490 | The debugger interface to %pdoc.""" |
|
490 | The debugger interface to %pdoc.""" | |
491 | namespaces = [('Locals', self.curframe.f_locals), |
|
491 | namespaces = [('Locals', self.curframe.f_locals), | |
492 | ('Globals', self.curframe.f_globals)] |
|
492 | ('Globals', self.curframe.f_globals)] | |
493 | self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces) |
|
493 | self.shell.find_line_magic('pdoc')(arg, namespaces=namespaces) | |
494 |
|
494 | |||
|
495 | def do_pfile(self, arg): | |||
|
496 | """Print (or run through pager) the file where an object is defined. | |||
|
497 | ||||
|
498 | The debugger interface to %pfile. | |||
|
499 | """ | |||
|
500 | namespaces = [('Locals', self.curframe.f_locals), | |||
|
501 | ('Globals', self.curframe.f_globals)] | |||
|
502 | self.shell.find_line_magic('pfile')(arg, namespaces=namespaces) | |||
|
503 | ||||
495 | def do_pinfo(self, arg): |
|
504 | def do_pinfo(self, arg): | |
496 | """Provide detailed information about an object. |
|
505 | """Provide detailed information about an object. | |
497 |
|
506 | |||
498 | The debugger interface to %pinfo, i.e., obj?.""" |
|
507 | The debugger interface to %pinfo, i.e., obj?.""" | |
499 | namespaces = [('Locals', self.curframe.f_locals), |
|
508 | namespaces = [('Locals', self.curframe.f_locals), | |
500 | ('Globals', self.curframe.f_globals)] |
|
509 | ('Globals', self.curframe.f_globals)] | |
501 | self.shell.find_line_magic('pinfo')("pinfo %s" % arg, |
|
510 | self.shell.find_line_magic('pinfo')("pinfo %s" % arg, | |
502 | namespaces=namespaces) |
|
511 | namespaces=namespaces) | |
503 |
|
512 | |||
504 | def checkline(self, filename, lineno): |
|
513 | def checkline(self, filename, lineno): | |
505 | """Check whether specified line seems to be executable. |
|
514 | """Check whether specified line seems to be executable. | |
506 |
|
515 | |||
507 | Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank |
|
516 | Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank | |
508 | line or EOF). Warning: testing is not comprehensive. |
|
517 | line or EOF). Warning: testing is not comprehensive. | |
509 | """ |
|
518 | """ | |
510 | ####################################################################### |
|
519 | ####################################################################### | |
511 | # XXX Hack! Use python-2.5 compatible code for this call, because with |
|
520 | # XXX Hack! Use python-2.5 compatible code for this call, because with | |
512 | # all of our changes, we've drifted from the pdb api in 2.6. For now, |
|
521 | # all of our changes, we've drifted from the pdb api in 2.6. For now, | |
513 | # changing: |
|
522 | # changing: | |
514 | # |
|
523 | # | |
515 | #line = linecache.getline(filename, lineno, self.curframe.f_globals) |
|
524 | #line = linecache.getline(filename, lineno, self.curframe.f_globals) | |
516 | # to: |
|
525 | # to: | |
517 | # |
|
526 | # | |
518 | line = linecache.getline(filename, lineno) |
|
527 | line = linecache.getline(filename, lineno) | |
519 | # |
|
528 | # | |
520 | # does the trick. But in reality, we need to fix this by reconciling |
|
529 | # does the trick. But in reality, we need to fix this by reconciling | |
521 | # our updates with the new Pdb APIs in Python 2.6. |
|
530 | # our updates with the new Pdb APIs in Python 2.6. | |
522 | # |
|
531 | # | |
523 | # End hack. The rest of this method is copied verbatim from 2.6 pdb.py |
|
532 | # End hack. The rest of this method is copied verbatim from 2.6 pdb.py | |
524 | ####################################################################### |
|
533 | ####################################################################### | |
525 |
|
534 | |||
526 | if not line: |
|
535 | if not line: | |
527 | print('End of file', file=self.stdout) |
|
536 | print('End of file', file=self.stdout) | |
528 | return 0 |
|
537 | return 0 | |
529 | line = line.strip() |
|
538 | line = line.strip() | |
530 | # Don't allow setting breakpoint at a blank line |
|
539 | # Don't allow setting breakpoint at a blank line | |
531 | if (not line or (line[0] == '#') or |
|
540 | if (not line or (line[0] == '#') or | |
532 | (line[:3] == '"""') or line[:3] == "'''"): |
|
541 | (line[:3] == '"""') or line[:3] == "'''"): | |
533 | print('*** Blank or comment', file=self.stdout) |
|
542 | print('*** Blank or comment', file=self.stdout) | |
534 | return 0 |
|
543 | return 0 | |
535 | return lineno |
|
544 | return lineno |
@@ -1,703 +1,703 | |||||
1 | """Implementation of namespace-related magic functions. |
|
1 | """Implementation of namespace-related magic functions. | |
2 | """ |
|
2 | """ | |
3 | #----------------------------------------------------------------------------- |
|
3 | #----------------------------------------------------------------------------- | |
4 | # Copyright (c) 2012 The IPython Development Team. |
|
4 | # Copyright (c) 2012 The IPython Development Team. | |
5 | # |
|
5 | # | |
6 | # Distributed under the terms of the Modified BSD License. |
|
6 | # Distributed under the terms of the Modified BSD License. | |
7 | # |
|
7 | # | |
8 | # The full license is in the file COPYING.txt, distributed with this software. |
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 | # Stdlib |
|
15 | # Stdlib | |
16 | import gc |
|
16 | import gc | |
17 | import re |
|
17 | import re | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | # Our own packages |
|
20 | # Our own packages | |
21 | from IPython.core import page |
|
21 | from IPython.core import page | |
22 | from IPython.core.error import StdinNotImplementedError, UsageError |
|
22 | from IPython.core.error import StdinNotImplementedError, UsageError | |
23 | from IPython.core.magic import Magics, magics_class, line_magic |
|
23 | from IPython.core.magic import Magics, magics_class, line_magic | |
24 | from IPython.testing.skipdoctest import skip_doctest |
|
24 | from IPython.testing.skipdoctest import skip_doctest | |
25 | from IPython.utils.encoding import DEFAULT_ENCODING |
|
25 | from IPython.utils.encoding import DEFAULT_ENCODING | |
26 | from IPython.utils.openpy import read_py_file |
|
26 | from IPython.utils.openpy import read_py_file | |
27 | from IPython.utils.path import get_py_filename |
|
27 | from IPython.utils.path import get_py_filename | |
28 |
|
28 | |||
29 | #----------------------------------------------------------------------------- |
|
29 | #----------------------------------------------------------------------------- | |
30 | # Magic implementation classes |
|
30 | # Magic implementation classes | |
31 | #----------------------------------------------------------------------------- |
|
31 | #----------------------------------------------------------------------------- | |
32 |
|
32 | |||
33 | @magics_class |
|
33 | @magics_class | |
34 | class NamespaceMagics(Magics): |
|
34 | class NamespaceMagics(Magics): | |
35 | """Magics to manage various aspects of the user's namespace. |
|
35 | """Magics to manage various aspects of the user's namespace. | |
36 |
|
36 | |||
37 | These include listing variables, introspecting into them, etc. |
|
37 | These include listing variables, introspecting into them, etc. | |
38 | """ |
|
38 | """ | |
39 |
|
39 | |||
40 | @line_magic |
|
40 | @line_magic | |
41 | def pinfo(self, parameter_s='', namespaces=None): |
|
41 | def pinfo(self, parameter_s='', namespaces=None): | |
42 | """Provide detailed information about an object. |
|
42 | """Provide detailed information about an object. | |
43 |
|
43 | |||
44 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
44 | '%pinfo object' is just a synonym for object? or ?object.""" | |
45 |
|
45 | |||
46 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
46 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
47 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
47 | # detail_level: 0 -> obj? , 1 -> obj?? | |
48 | detail_level = 0 |
|
48 | detail_level = 0 | |
49 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
49 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
50 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
50 | # happen if the user types 'pinfo foo?' at the cmd line. | |
51 | pinfo,qmark1,oname,qmark2 = \ |
|
51 | pinfo,qmark1,oname,qmark2 = \ | |
52 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
52 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
53 | if pinfo or qmark1 or qmark2: |
|
53 | if pinfo or qmark1 or qmark2: | |
54 | detail_level = 1 |
|
54 | detail_level = 1 | |
55 | if "*" in oname: |
|
55 | if "*" in oname: | |
56 | self.psearch(oname) |
|
56 | self.psearch(oname) | |
57 | else: |
|
57 | else: | |
58 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
58 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
59 | namespaces=namespaces) |
|
59 | namespaces=namespaces) | |
60 |
|
60 | |||
61 | @line_magic |
|
61 | @line_magic | |
62 | def pinfo2(self, parameter_s='', namespaces=None): |
|
62 | def pinfo2(self, parameter_s='', namespaces=None): | |
63 | """Provide extra detailed information about an object. |
|
63 | """Provide extra detailed information about an object. | |
64 |
|
64 | |||
65 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
65 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
66 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
66 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
67 | namespaces=namespaces) |
|
67 | namespaces=namespaces) | |
68 |
|
68 | |||
69 | @skip_doctest |
|
69 | @skip_doctest | |
70 | @line_magic |
|
70 | @line_magic | |
71 | def pdef(self, parameter_s='', namespaces=None): |
|
71 | def pdef(self, parameter_s='', namespaces=None): | |
72 | """Print the definition header for any callable object. |
|
72 | """Print the definition header for any callable object. | |
73 |
|
73 | |||
74 | If the object is a class, print the constructor information. |
|
74 | If the object is a class, print the constructor information. | |
75 |
|
75 | |||
76 | Examples |
|
76 | Examples | |
77 | -------- |
|
77 | -------- | |
78 | :: |
|
78 | :: | |
79 |
|
79 | |||
80 | In [3]: %pdef urllib.urlopen |
|
80 | In [3]: %pdef urllib.urlopen | |
81 | urllib.urlopen(url, data=None, proxies=None) |
|
81 | urllib.urlopen(url, data=None, proxies=None) | |
82 | """ |
|
82 | """ | |
83 | self.shell._inspect('pdef',parameter_s, namespaces) |
|
83 | self.shell._inspect('pdef',parameter_s, namespaces) | |
84 |
|
84 | |||
85 | @line_magic |
|
85 | @line_magic | |
86 | def pdoc(self, parameter_s='', namespaces=None): |
|
86 | def pdoc(self, parameter_s='', namespaces=None): | |
87 | """Print the docstring for an object. |
|
87 | """Print the docstring for an object. | |
88 |
|
88 | |||
89 | If the given object is a class, it will print both the class and the |
|
89 | If the given object is a class, it will print both the class and the | |
90 | constructor docstrings.""" |
|
90 | constructor docstrings.""" | |
91 | self.shell._inspect('pdoc',parameter_s, namespaces) |
|
91 | self.shell._inspect('pdoc',parameter_s, namespaces) | |
92 |
|
92 | |||
93 | @line_magic |
|
93 | @line_magic | |
94 | def psource(self, parameter_s='', namespaces=None): |
|
94 | def psource(self, parameter_s='', namespaces=None): | |
95 | """Print (or run through pager) the source code for an object.""" |
|
95 | """Print (or run through pager) the source code for an object.""" | |
96 | if not parameter_s: |
|
96 | if not parameter_s: | |
97 | raise UsageError('Missing object name.') |
|
97 | raise UsageError('Missing object name.') | |
98 | self.shell._inspect('psource',parameter_s, namespaces) |
|
98 | self.shell._inspect('psource',parameter_s, namespaces) | |
99 |
|
99 | |||
100 | @line_magic |
|
100 | @line_magic | |
101 | def pfile(self, parameter_s=''): |
|
101 | def pfile(self, parameter_s='', namespaces=None): | |
102 | """Print (or run through pager) the file where an object is defined. |
|
102 | """Print (or run through pager) the file where an object is defined. | |
103 |
|
103 | |||
104 | The file opens at the line where the object definition begins. IPython |
|
104 | The file opens at the line where the object definition begins. IPython | |
105 | will honor the environment variable PAGER if set, and otherwise will |
|
105 | will honor the environment variable PAGER if set, and otherwise will | |
106 | do its best to print the file in a convenient form. |
|
106 | do its best to print the file in a convenient form. | |
107 |
|
107 | |||
108 | If the given argument is not an object currently defined, IPython will |
|
108 | If the given argument is not an object currently defined, IPython will | |
109 | try to interpret it as a filename (automatically adding a .py extension |
|
109 | try to interpret it as a filename (automatically adding a .py extension | |
110 | if needed). You can thus use %pfile as a syntax highlighting code |
|
110 | if needed). You can thus use %pfile as a syntax highlighting code | |
111 | viewer.""" |
|
111 | viewer.""" | |
112 |
|
112 | |||
113 | # first interpret argument as an object name |
|
113 | # first interpret argument as an object name | |
114 | out = self.shell._inspect('pfile',parameter_s) |
|
114 | out = self.shell._inspect('pfile',parameter_s, namespaces) | |
115 | # if not, try the input as a filename |
|
115 | # if not, try the input as a filename | |
116 | if out == 'not found': |
|
116 | if out == 'not found': | |
117 | try: |
|
117 | try: | |
118 | filename = get_py_filename(parameter_s) |
|
118 | filename = get_py_filename(parameter_s) | |
119 | except IOError as msg: |
|
119 | except IOError as msg: | |
120 | print msg |
|
120 | print msg | |
121 | return |
|
121 | return | |
122 | page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False))) |
|
122 | page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False))) | |
123 |
|
123 | |||
124 | @line_magic |
|
124 | @line_magic | |
125 | def psearch(self, parameter_s=''): |
|
125 | def psearch(self, parameter_s=''): | |
126 | """Search for object in namespaces by wildcard. |
|
126 | """Search for object in namespaces by wildcard. | |
127 |
|
127 | |||
128 | %psearch [options] PATTERN [OBJECT TYPE] |
|
128 | %psearch [options] PATTERN [OBJECT TYPE] | |
129 |
|
129 | |||
130 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
130 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
131 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
131 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
132 | rest of the command line must be unchanged (options come first), so |
|
132 | rest of the command line must be unchanged (options come first), so | |
133 | for example the following forms are equivalent |
|
133 | for example the following forms are equivalent | |
134 |
|
134 | |||
135 | %psearch -i a* function |
|
135 | %psearch -i a* function | |
136 | -i a* function? |
|
136 | -i a* function? | |
137 | ?-i a* function |
|
137 | ?-i a* function | |
138 |
|
138 | |||
139 | Arguments: |
|
139 | Arguments: | |
140 |
|
140 | |||
141 | PATTERN |
|
141 | PATTERN | |
142 |
|
142 | |||
143 | where PATTERN is a string containing * as a wildcard similar to its |
|
143 | where PATTERN is a string containing * as a wildcard similar to its | |
144 | use in a shell. The pattern is matched in all namespaces on the |
|
144 | use in a shell. The pattern is matched in all namespaces on the | |
145 | search path. By default objects starting with a single _ are not |
|
145 | search path. By default objects starting with a single _ are not | |
146 | matched, many IPython generated objects have a single |
|
146 | matched, many IPython generated objects have a single | |
147 | underscore. The default is case insensitive matching. Matching is |
|
147 | underscore. The default is case insensitive matching. Matching is | |
148 | also done on the attributes of objects and not only on the objects |
|
148 | also done on the attributes of objects and not only on the objects | |
149 | in a module. |
|
149 | in a module. | |
150 |
|
150 | |||
151 | [OBJECT TYPE] |
|
151 | [OBJECT TYPE] | |
152 |
|
152 | |||
153 | Is the name of a python type from the types module. The name is |
|
153 | Is the name of a python type from the types module. The name is | |
154 | given in lowercase without the ending type, ex. StringType is |
|
154 | given in lowercase without the ending type, ex. StringType is | |
155 | written string. By adding a type here only objects matching the |
|
155 | written string. By adding a type here only objects matching the | |
156 | given type are matched. Using all here makes the pattern match all |
|
156 | given type are matched. Using all here makes the pattern match all | |
157 | types (this is the default). |
|
157 | types (this is the default). | |
158 |
|
158 | |||
159 | Options: |
|
159 | Options: | |
160 |
|
160 | |||
161 | -a: makes the pattern match even objects whose names start with a |
|
161 | -a: makes the pattern match even objects whose names start with a | |
162 | single underscore. These names are normally omitted from the |
|
162 | single underscore. These names are normally omitted from the | |
163 | search. |
|
163 | search. | |
164 |
|
164 | |||
165 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
165 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
166 | these options are given, the default is read from your configuration |
|
166 | these options are given, the default is read from your configuration | |
167 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
167 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |
168 | If this option is not specified in your configuration file, IPython's |
|
168 | If this option is not specified in your configuration file, IPython's | |
169 | internal default is to do a case sensitive search. |
|
169 | internal default is to do a case sensitive search. | |
170 |
|
170 | |||
171 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
171 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
172 | specify can be searched in any of the following namespaces: |
|
172 | specify can be searched in any of the following namespaces: | |
173 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
173 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
174 | 'builtin' and 'user' are the search defaults. Note that you should |
|
174 | 'builtin' and 'user' are the search defaults. Note that you should | |
175 | not use quotes when specifying namespaces. |
|
175 | not use quotes when specifying namespaces. | |
176 |
|
176 | |||
177 | 'Builtin' contains the python module builtin, 'user' contains all |
|
177 | 'Builtin' contains the python module builtin, 'user' contains all | |
178 | user data, 'alias' only contain the shell aliases and no python |
|
178 | user data, 'alias' only contain the shell aliases and no python | |
179 | objects, 'internal' contains objects used by IPython. The |
|
179 | objects, 'internal' contains objects used by IPython. The | |
180 | 'user_global' namespace is only used by embedded IPython instances, |
|
180 | 'user_global' namespace is only used by embedded IPython instances, | |
181 | and it contains module-level globals. You can add namespaces to the |
|
181 | and it contains module-level globals. You can add namespaces to the | |
182 | search with -s or exclude them with -e (these options can be given |
|
182 | search with -s or exclude them with -e (these options can be given | |
183 | more than once). |
|
183 | more than once). | |
184 |
|
184 | |||
185 | Examples |
|
185 | Examples | |
186 | -------- |
|
186 | -------- | |
187 | :: |
|
187 | :: | |
188 |
|
188 | |||
189 | %psearch a* -> objects beginning with an a |
|
189 | %psearch a* -> objects beginning with an a | |
190 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
190 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
191 | %psearch a* function -> all functions beginning with an a |
|
191 | %psearch a* function -> all functions beginning with an a | |
192 | %psearch re.e* -> objects beginning with an e in module re |
|
192 | %psearch re.e* -> objects beginning with an e in module re | |
193 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
193 | %psearch r*.e* -> objects that start with e in modules starting in r | |
194 | %psearch r*.* string -> all strings in modules beginning with r |
|
194 | %psearch r*.* string -> all strings in modules beginning with r | |
195 |
|
195 | |||
196 | Case sensitive search:: |
|
196 | Case sensitive search:: | |
197 |
|
197 | |||
198 | %psearch -c a* list all object beginning with lower case a |
|
198 | %psearch -c a* list all object beginning with lower case a | |
199 |
|
199 | |||
200 | Show objects beginning with a single _:: |
|
200 | Show objects beginning with a single _:: | |
201 |
|
201 | |||
202 | %psearch -a _* list objects beginning with a single underscore |
|
202 | %psearch -a _* list objects beginning with a single underscore | |
203 | """ |
|
203 | """ | |
204 | try: |
|
204 | try: | |
205 | parameter_s.encode('ascii') |
|
205 | parameter_s.encode('ascii') | |
206 | except UnicodeEncodeError: |
|
206 | except UnicodeEncodeError: | |
207 | print 'Python identifiers can only contain ascii characters.' |
|
207 | print 'Python identifiers can only contain ascii characters.' | |
208 | return |
|
208 | return | |
209 |
|
209 | |||
210 | # default namespaces to be searched |
|
210 | # default namespaces to be searched | |
211 | def_search = ['user_local', 'user_global', 'builtin'] |
|
211 | def_search = ['user_local', 'user_global', 'builtin'] | |
212 |
|
212 | |||
213 | # Process options/args |
|
213 | # Process options/args | |
214 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
214 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
215 | opt = opts.get |
|
215 | opt = opts.get | |
216 | shell = self.shell |
|
216 | shell = self.shell | |
217 | psearch = shell.inspector.psearch |
|
217 | psearch = shell.inspector.psearch | |
218 |
|
218 | |||
219 | # select case options |
|
219 | # select case options | |
220 | if 'i' in opts: |
|
220 | if 'i' in opts: | |
221 | ignore_case = True |
|
221 | ignore_case = True | |
222 | elif 'c' in opts: |
|
222 | elif 'c' in opts: | |
223 | ignore_case = False |
|
223 | ignore_case = False | |
224 | else: |
|
224 | else: | |
225 | ignore_case = not shell.wildcards_case_sensitive |
|
225 | ignore_case = not shell.wildcards_case_sensitive | |
226 |
|
226 | |||
227 | # Build list of namespaces to search from user options |
|
227 | # Build list of namespaces to search from user options | |
228 | def_search.extend(opt('s',[])) |
|
228 | def_search.extend(opt('s',[])) | |
229 | ns_exclude = ns_exclude=opt('e',[]) |
|
229 | ns_exclude = ns_exclude=opt('e',[]) | |
230 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
230 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
231 |
|
231 | |||
232 | # Call the actual search |
|
232 | # Call the actual search | |
233 | try: |
|
233 | try: | |
234 | psearch(args,shell.ns_table,ns_search, |
|
234 | psearch(args,shell.ns_table,ns_search, | |
235 | show_all=opt('a'),ignore_case=ignore_case) |
|
235 | show_all=opt('a'),ignore_case=ignore_case) | |
236 | except: |
|
236 | except: | |
237 | shell.showtraceback() |
|
237 | shell.showtraceback() | |
238 |
|
238 | |||
239 | @skip_doctest |
|
239 | @skip_doctest | |
240 | @line_magic |
|
240 | @line_magic | |
241 | def who_ls(self, parameter_s=''): |
|
241 | def who_ls(self, parameter_s=''): | |
242 | """Return a sorted list of all interactive variables. |
|
242 | """Return a sorted list of all interactive variables. | |
243 |
|
243 | |||
244 | If arguments are given, only variables of types matching these |
|
244 | If arguments are given, only variables of types matching these | |
245 | arguments are returned. |
|
245 | arguments are returned. | |
246 |
|
246 | |||
247 | Examples |
|
247 | Examples | |
248 | -------- |
|
248 | -------- | |
249 |
|
249 | |||
250 | Define two variables and list them with who_ls:: |
|
250 | Define two variables and list them with who_ls:: | |
251 |
|
251 | |||
252 | In [1]: alpha = 123 |
|
252 | In [1]: alpha = 123 | |
253 |
|
253 | |||
254 | In [2]: beta = 'test' |
|
254 | In [2]: beta = 'test' | |
255 |
|
255 | |||
256 | In [3]: %who_ls |
|
256 | In [3]: %who_ls | |
257 | Out[3]: ['alpha', 'beta'] |
|
257 | Out[3]: ['alpha', 'beta'] | |
258 |
|
258 | |||
259 | In [4]: %who_ls int |
|
259 | In [4]: %who_ls int | |
260 | Out[4]: ['alpha'] |
|
260 | Out[4]: ['alpha'] | |
261 |
|
261 | |||
262 | In [5]: %who_ls str |
|
262 | In [5]: %who_ls str | |
263 | Out[5]: ['beta'] |
|
263 | Out[5]: ['beta'] | |
264 | """ |
|
264 | """ | |
265 |
|
265 | |||
266 | user_ns = self.shell.user_ns |
|
266 | user_ns = self.shell.user_ns | |
267 | user_ns_hidden = self.shell.user_ns_hidden |
|
267 | user_ns_hidden = self.shell.user_ns_hidden | |
268 | out = [ i for i in user_ns |
|
268 | out = [ i for i in user_ns | |
269 | if not i.startswith('_') \ |
|
269 | if not i.startswith('_') \ | |
270 | and not i in user_ns_hidden ] |
|
270 | and not i in user_ns_hidden ] | |
271 |
|
271 | |||
272 | typelist = parameter_s.split() |
|
272 | typelist = parameter_s.split() | |
273 | if typelist: |
|
273 | if typelist: | |
274 | typeset = set(typelist) |
|
274 | typeset = set(typelist) | |
275 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
275 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |
276 |
|
276 | |||
277 | out.sort() |
|
277 | out.sort() | |
278 | return out |
|
278 | return out | |
279 |
|
279 | |||
280 | @skip_doctest |
|
280 | @skip_doctest | |
281 | @line_magic |
|
281 | @line_magic | |
282 | def who(self, parameter_s=''): |
|
282 | def who(self, parameter_s=''): | |
283 | """Print all interactive variables, with some minimal formatting. |
|
283 | """Print all interactive variables, with some minimal formatting. | |
284 |
|
284 | |||
285 | If any arguments are given, only variables whose type matches one of |
|
285 | If any arguments are given, only variables whose type matches one of | |
286 | these are printed. For example:: |
|
286 | these are printed. For example:: | |
287 |
|
287 | |||
288 | %who function str |
|
288 | %who function str | |
289 |
|
289 | |||
290 | will only list functions and strings, excluding all other types of |
|
290 | will only list functions and strings, excluding all other types of | |
291 | variables. To find the proper type names, simply use type(var) at a |
|
291 | variables. To find the proper type names, simply use type(var) at a | |
292 | command line to see how python prints type names. For example: |
|
292 | command line to see how python prints type names. For example: | |
293 |
|
293 | |||
294 | :: |
|
294 | :: | |
295 |
|
295 | |||
296 | In [1]: type('hello')\\ |
|
296 | In [1]: type('hello')\\ | |
297 | Out[1]: <type 'str'> |
|
297 | Out[1]: <type 'str'> | |
298 |
|
298 | |||
299 | indicates that the type name for strings is 'str'. |
|
299 | indicates that the type name for strings is 'str'. | |
300 |
|
300 | |||
301 | ``%who`` always excludes executed names loaded through your configuration |
|
301 | ``%who`` always excludes executed names loaded through your configuration | |
302 | file and things which are internal to IPython. |
|
302 | file and things which are internal to IPython. | |
303 |
|
303 | |||
304 | This is deliberate, as typically you may load many modules and the |
|
304 | This is deliberate, as typically you may load many modules and the | |
305 | purpose of %who is to show you only what you've manually defined. |
|
305 | purpose of %who is to show you only what you've manually defined. | |
306 |
|
306 | |||
307 | Examples |
|
307 | Examples | |
308 | -------- |
|
308 | -------- | |
309 |
|
309 | |||
310 | Define two variables and list them with who:: |
|
310 | Define two variables and list them with who:: | |
311 |
|
311 | |||
312 | In [1]: alpha = 123 |
|
312 | In [1]: alpha = 123 | |
313 |
|
313 | |||
314 | In [2]: beta = 'test' |
|
314 | In [2]: beta = 'test' | |
315 |
|
315 | |||
316 | In [3]: %who |
|
316 | In [3]: %who | |
317 | alpha beta |
|
317 | alpha beta | |
318 |
|
318 | |||
319 | In [4]: %who int |
|
319 | In [4]: %who int | |
320 | alpha |
|
320 | alpha | |
321 |
|
321 | |||
322 | In [5]: %who str |
|
322 | In [5]: %who str | |
323 | beta |
|
323 | beta | |
324 | """ |
|
324 | """ | |
325 |
|
325 | |||
326 | varlist = self.who_ls(parameter_s) |
|
326 | varlist = self.who_ls(parameter_s) | |
327 | if not varlist: |
|
327 | if not varlist: | |
328 | if parameter_s: |
|
328 | if parameter_s: | |
329 | print 'No variables match your requested type.' |
|
329 | print 'No variables match your requested type.' | |
330 | else: |
|
330 | else: | |
331 | print 'Interactive namespace is empty.' |
|
331 | print 'Interactive namespace is empty.' | |
332 | return |
|
332 | return | |
333 |
|
333 | |||
334 | # if we have variables, move on... |
|
334 | # if we have variables, move on... | |
335 | count = 0 |
|
335 | count = 0 | |
336 | for i in varlist: |
|
336 | for i in varlist: | |
337 | print i+'\t', |
|
337 | print i+'\t', | |
338 | count += 1 |
|
338 | count += 1 | |
339 | if count > 8: |
|
339 | if count > 8: | |
340 | count = 0 |
|
340 | count = 0 | |
341 |
|
341 | |||
342 |
|
342 | |||
343 |
|
343 | |||
344 | @skip_doctest |
|
344 | @skip_doctest | |
345 | @line_magic |
|
345 | @line_magic | |
346 | def whos(self, parameter_s=''): |
|
346 | def whos(self, parameter_s=''): | |
347 | """Like %who, but gives some extra information about each variable. |
|
347 | """Like %who, but gives some extra information about each variable. | |
348 |
|
348 | |||
349 | The same type filtering of %who can be applied here. |
|
349 | The same type filtering of %who can be applied here. | |
350 |
|
350 | |||
351 | For all variables, the type is printed. Additionally it prints: |
|
351 | For all variables, the type is printed. Additionally it prints: | |
352 |
|
352 | |||
353 | - For {},[],(): their length. |
|
353 | - For {},[],(): their length. | |
354 |
|
354 | |||
355 | - For numpy arrays, a summary with shape, number of |
|
355 | - For numpy arrays, a summary with shape, number of | |
356 | elements, typecode and size in memory. |
|
356 | elements, typecode and size in memory. | |
357 |
|
357 | |||
358 | - Everything else: a string representation, snipping their middle if |
|
358 | - Everything else: a string representation, snipping their middle if | |
359 | too long. |
|
359 | too long. | |
360 |
|
360 | |||
361 | Examples |
|
361 | Examples | |
362 | -------- |
|
362 | -------- | |
363 |
|
363 | |||
364 | Define two variables and list them with whos:: |
|
364 | Define two variables and list them with whos:: | |
365 |
|
365 | |||
366 | In [1]: alpha = 123 |
|
366 | In [1]: alpha = 123 | |
367 |
|
367 | |||
368 | In [2]: beta = 'test' |
|
368 | In [2]: beta = 'test' | |
369 |
|
369 | |||
370 | In [3]: %whos |
|
370 | In [3]: %whos | |
371 | Variable Type Data/Info |
|
371 | Variable Type Data/Info | |
372 | -------------------------------- |
|
372 | -------------------------------- | |
373 | alpha int 123 |
|
373 | alpha int 123 | |
374 | beta str test |
|
374 | beta str test | |
375 | """ |
|
375 | """ | |
376 |
|
376 | |||
377 | varnames = self.who_ls(parameter_s) |
|
377 | varnames = self.who_ls(parameter_s) | |
378 | if not varnames: |
|
378 | if not varnames: | |
379 | if parameter_s: |
|
379 | if parameter_s: | |
380 | print 'No variables match your requested type.' |
|
380 | print 'No variables match your requested type.' | |
381 | else: |
|
381 | else: | |
382 | print 'Interactive namespace is empty.' |
|
382 | print 'Interactive namespace is empty.' | |
383 | return |
|
383 | return | |
384 |
|
384 | |||
385 | # if we have variables, move on... |
|
385 | # if we have variables, move on... | |
386 |
|
386 | |||
387 | # for these types, show len() instead of data: |
|
387 | # for these types, show len() instead of data: | |
388 | seq_types = ['dict', 'list', 'tuple'] |
|
388 | seq_types = ['dict', 'list', 'tuple'] | |
389 |
|
389 | |||
390 | # for numpy arrays, display summary info |
|
390 | # for numpy arrays, display summary info | |
391 | ndarray_type = None |
|
391 | ndarray_type = None | |
392 | if 'numpy' in sys.modules: |
|
392 | if 'numpy' in sys.modules: | |
393 | try: |
|
393 | try: | |
394 | from numpy import ndarray |
|
394 | from numpy import ndarray | |
395 | except ImportError: |
|
395 | except ImportError: | |
396 | pass |
|
396 | pass | |
397 | else: |
|
397 | else: | |
398 | ndarray_type = ndarray.__name__ |
|
398 | ndarray_type = ndarray.__name__ | |
399 |
|
399 | |||
400 | # Find all variable names and types so we can figure out column sizes |
|
400 | # Find all variable names and types so we can figure out column sizes | |
401 | def get_vars(i): |
|
401 | def get_vars(i): | |
402 | return self.shell.user_ns[i] |
|
402 | return self.shell.user_ns[i] | |
403 |
|
403 | |||
404 | # some types are well known and can be shorter |
|
404 | # some types are well known and can be shorter | |
405 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
405 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
406 | def type_name(v): |
|
406 | def type_name(v): | |
407 | tn = type(v).__name__ |
|
407 | tn = type(v).__name__ | |
408 | return abbrevs.get(tn,tn) |
|
408 | return abbrevs.get(tn,tn) | |
409 |
|
409 | |||
410 | varlist = map(get_vars,varnames) |
|
410 | varlist = map(get_vars,varnames) | |
411 |
|
411 | |||
412 | typelist = [] |
|
412 | typelist = [] | |
413 | for vv in varlist: |
|
413 | for vv in varlist: | |
414 | tt = type_name(vv) |
|
414 | tt = type_name(vv) | |
415 |
|
415 | |||
416 | if tt=='instance': |
|
416 | if tt=='instance': | |
417 | typelist.append( abbrevs.get(str(vv.__class__), |
|
417 | typelist.append( abbrevs.get(str(vv.__class__), | |
418 | str(vv.__class__))) |
|
418 | str(vv.__class__))) | |
419 | else: |
|
419 | else: | |
420 | typelist.append(tt) |
|
420 | typelist.append(tt) | |
421 |
|
421 | |||
422 | # column labels and # of spaces as separator |
|
422 | # column labels and # of spaces as separator | |
423 | varlabel = 'Variable' |
|
423 | varlabel = 'Variable' | |
424 | typelabel = 'Type' |
|
424 | typelabel = 'Type' | |
425 | datalabel = 'Data/Info' |
|
425 | datalabel = 'Data/Info' | |
426 | colsep = 3 |
|
426 | colsep = 3 | |
427 | # variable format strings |
|
427 | # variable format strings | |
428 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
428 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |
429 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
429 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
430 | # find the size of the columns to format the output nicely |
|
430 | # find the size of the columns to format the output nicely | |
431 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
431 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
432 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
432 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
433 | # table header |
|
433 | # table header | |
434 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
434 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
435 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
435 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
436 | # and the table itself |
|
436 | # and the table itself | |
437 | kb = 1024 |
|
437 | kb = 1024 | |
438 | Mb = 1048576 # kb**2 |
|
438 | Mb = 1048576 # kb**2 | |
439 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
439 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
440 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
440 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |
441 | if vtype in seq_types: |
|
441 | if vtype in seq_types: | |
442 | print "n="+str(len(var)) |
|
442 | print "n="+str(len(var)) | |
443 | elif vtype == ndarray_type: |
|
443 | elif vtype == ndarray_type: | |
444 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
444 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
445 | if vtype==ndarray_type: |
|
445 | if vtype==ndarray_type: | |
446 | # numpy |
|
446 | # numpy | |
447 | vsize = var.size |
|
447 | vsize = var.size | |
448 | vbytes = vsize*var.itemsize |
|
448 | vbytes = vsize*var.itemsize | |
449 | vdtype = var.dtype |
|
449 | vdtype = var.dtype | |
450 |
|
450 | |||
451 | if vbytes < 100000: |
|
451 | if vbytes < 100000: | |
452 | print aformat % (vshape, vsize, vdtype, vbytes) |
|
452 | print aformat % (vshape, vsize, vdtype, vbytes) | |
453 | else: |
|
453 | else: | |
454 | print aformat % (vshape, vsize, vdtype, vbytes), |
|
454 | print aformat % (vshape, vsize, vdtype, vbytes), | |
455 | if vbytes < Mb: |
|
455 | if vbytes < Mb: | |
456 | print '(%s kb)' % (vbytes/kb,) |
|
456 | print '(%s kb)' % (vbytes/kb,) | |
457 | else: |
|
457 | else: | |
458 | print '(%s Mb)' % (vbytes/Mb,) |
|
458 | print '(%s Mb)' % (vbytes/Mb,) | |
459 | else: |
|
459 | else: | |
460 | try: |
|
460 | try: | |
461 | vstr = str(var) |
|
461 | vstr = str(var) | |
462 | except UnicodeEncodeError: |
|
462 | except UnicodeEncodeError: | |
463 | vstr = unicode(var).encode(DEFAULT_ENCODING, |
|
463 | vstr = unicode(var).encode(DEFAULT_ENCODING, | |
464 | 'backslashreplace') |
|
464 | 'backslashreplace') | |
465 | except: |
|
465 | except: | |
466 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
466 | vstr = "<object with id %d (str() failed)>" % id(var) | |
467 | vstr = vstr.replace('\n', '\\n') |
|
467 | vstr = vstr.replace('\n', '\\n') | |
468 | if len(vstr) < 50: |
|
468 | if len(vstr) < 50: | |
469 | print vstr |
|
469 | print vstr | |
470 | else: |
|
470 | else: | |
471 | print vstr[:25] + "<...>" + vstr[-25:] |
|
471 | print vstr[:25] + "<...>" + vstr[-25:] | |
472 |
|
472 | |||
473 | @line_magic |
|
473 | @line_magic | |
474 | def reset(self, parameter_s=''): |
|
474 | def reset(self, parameter_s=''): | |
475 | """Resets the namespace by removing all names defined by the user, if |
|
475 | """Resets the namespace by removing all names defined by the user, if | |
476 | called without arguments, or by removing some types of objects, such |
|
476 | called without arguments, or by removing some types of objects, such | |
477 | as everything currently in IPython's In[] and Out[] containers (see |
|
477 | as everything currently in IPython's In[] and Out[] containers (see | |
478 | the parameters for details). |
|
478 | the parameters for details). | |
479 |
|
479 | |||
480 | Parameters |
|
480 | Parameters | |
481 | ---------- |
|
481 | ---------- | |
482 | -f : force reset without asking for confirmation. |
|
482 | -f : force reset without asking for confirmation. | |
483 |
|
483 | |||
484 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
484 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |
485 | References to objects may be kept. By default (without this option), |
|
485 | References to objects may be kept. By default (without this option), | |
486 | we do a 'hard' reset, giving you a new session and removing all |
|
486 | we do a 'hard' reset, giving you a new session and removing all | |
487 | references to objects from the current session. |
|
487 | references to objects from the current session. | |
488 |
|
488 | |||
489 | in : reset input history |
|
489 | in : reset input history | |
490 |
|
490 | |||
491 | out : reset output history |
|
491 | out : reset output history | |
492 |
|
492 | |||
493 | dhist : reset directory history |
|
493 | dhist : reset directory history | |
494 |
|
494 | |||
495 | array : reset only variables that are NumPy arrays |
|
495 | array : reset only variables that are NumPy arrays | |
496 |
|
496 | |||
497 | See Also |
|
497 | See Also | |
498 | -------- |
|
498 | -------- | |
499 | magic_reset_selective : invoked as ``%reset_selective`` |
|
499 | magic_reset_selective : invoked as ``%reset_selective`` | |
500 |
|
500 | |||
501 | Examples |
|
501 | Examples | |
502 | -------- |
|
502 | -------- | |
503 | :: |
|
503 | :: | |
504 |
|
504 | |||
505 | In [6]: a = 1 |
|
505 | In [6]: a = 1 | |
506 |
|
506 | |||
507 | In [7]: a |
|
507 | In [7]: a | |
508 | Out[7]: 1 |
|
508 | Out[7]: 1 | |
509 |
|
509 | |||
510 | In [8]: 'a' in _ip.user_ns |
|
510 | In [8]: 'a' in _ip.user_ns | |
511 | Out[8]: True |
|
511 | Out[8]: True | |
512 |
|
512 | |||
513 | In [9]: %reset -f |
|
513 | In [9]: %reset -f | |
514 |
|
514 | |||
515 | In [1]: 'a' in _ip.user_ns |
|
515 | In [1]: 'a' in _ip.user_ns | |
516 | Out[1]: False |
|
516 | Out[1]: False | |
517 |
|
517 | |||
518 | In [2]: %reset -f in |
|
518 | In [2]: %reset -f in | |
519 | Flushing input history |
|
519 | Flushing input history | |
520 |
|
520 | |||
521 | In [3]: %reset -f dhist in |
|
521 | In [3]: %reset -f dhist in | |
522 | Flushing directory history |
|
522 | Flushing directory history | |
523 | Flushing input history |
|
523 | Flushing input history | |
524 |
|
524 | |||
525 | Notes |
|
525 | Notes | |
526 | ----- |
|
526 | ----- | |
527 | Calling this magic from clients that do not implement standard input, |
|
527 | Calling this magic from clients that do not implement standard input, | |
528 | such as the ipython notebook interface, will reset the namespace |
|
528 | such as the ipython notebook interface, will reset the namespace | |
529 | without confirmation. |
|
529 | without confirmation. | |
530 | """ |
|
530 | """ | |
531 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
531 | opts, args = self.parse_options(parameter_s,'sf', mode='list') | |
532 | if 'f' in opts: |
|
532 | if 'f' in opts: | |
533 | ans = True |
|
533 | ans = True | |
534 | else: |
|
534 | else: | |
535 | try: |
|
535 | try: | |
536 | ans = self.shell.ask_yes_no( |
|
536 | ans = self.shell.ask_yes_no( | |
537 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", |
|
537 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", | |
538 | default='n') |
|
538 | default='n') | |
539 | except StdinNotImplementedError: |
|
539 | except StdinNotImplementedError: | |
540 | ans = True |
|
540 | ans = True | |
541 | if not ans: |
|
541 | if not ans: | |
542 | print 'Nothing done.' |
|
542 | print 'Nothing done.' | |
543 | return |
|
543 | return | |
544 |
|
544 | |||
545 | if 's' in opts: # Soft reset |
|
545 | if 's' in opts: # Soft reset | |
546 | user_ns = self.shell.user_ns |
|
546 | user_ns = self.shell.user_ns | |
547 | for i in self.who_ls(): |
|
547 | for i in self.who_ls(): | |
548 | del(user_ns[i]) |
|
548 | del(user_ns[i]) | |
549 | elif len(args) == 0: # Hard reset |
|
549 | elif len(args) == 0: # Hard reset | |
550 | self.shell.reset(new_session = False) |
|
550 | self.shell.reset(new_session = False) | |
551 |
|
551 | |||
552 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
552 | # reset in/out/dhist/array: previously extensinions/clearcmd.py | |
553 | ip = self.shell |
|
553 | ip = self.shell | |
554 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
554 | user_ns = self.shell.user_ns # local lookup, heavily used | |
555 |
|
555 | |||
556 | for target in args: |
|
556 | for target in args: | |
557 | target = target.lower() # make matches case insensitive |
|
557 | target = target.lower() # make matches case insensitive | |
558 | if target == 'out': |
|
558 | if target == 'out': | |
559 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
559 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |
560 | self.shell.displayhook.flush() |
|
560 | self.shell.displayhook.flush() | |
561 |
|
561 | |||
562 | elif target == 'in': |
|
562 | elif target == 'in': | |
563 | print "Flushing input history" |
|
563 | print "Flushing input history" | |
564 | pc = self.shell.displayhook.prompt_count + 1 |
|
564 | pc = self.shell.displayhook.prompt_count + 1 | |
565 | for n in range(1, pc): |
|
565 | for n in range(1, pc): | |
566 | key = '_i'+repr(n) |
|
566 | key = '_i'+repr(n) | |
567 | user_ns.pop(key,None) |
|
567 | user_ns.pop(key,None) | |
568 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
568 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |
569 | hm = ip.history_manager |
|
569 | hm = ip.history_manager | |
570 | # don't delete these, as %save and %macro depending on the |
|
570 | # don't delete these, as %save and %macro depending on the | |
571 | # length of these lists to be preserved |
|
571 | # length of these lists to be preserved | |
572 | hm.input_hist_parsed[:] = [''] * pc |
|
572 | hm.input_hist_parsed[:] = [''] * pc | |
573 | hm.input_hist_raw[:] = [''] * pc |
|
573 | hm.input_hist_raw[:] = [''] * pc | |
574 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
574 | # hm has internal machinery for _i,_ii,_iii, clear it out | |
575 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
575 | hm._i = hm._ii = hm._iii = hm._i00 = u'' | |
576 |
|
576 | |||
577 | elif target == 'array': |
|
577 | elif target == 'array': | |
578 | # Support cleaning up numpy arrays |
|
578 | # Support cleaning up numpy arrays | |
579 | try: |
|
579 | try: | |
580 | from numpy import ndarray |
|
580 | from numpy import ndarray | |
581 | # This must be done with items and not iteritems because |
|
581 | # This must be done with items and not iteritems because | |
582 | # we're going to modify the dict in-place. |
|
582 | # we're going to modify the dict in-place. | |
583 | for x,val in user_ns.items(): |
|
583 | for x,val in user_ns.items(): | |
584 | if isinstance(val,ndarray): |
|
584 | if isinstance(val,ndarray): | |
585 | del user_ns[x] |
|
585 | del user_ns[x] | |
586 | except ImportError: |
|
586 | except ImportError: | |
587 | print "reset array only works if Numpy is available." |
|
587 | print "reset array only works if Numpy is available." | |
588 |
|
588 | |||
589 | elif target == 'dhist': |
|
589 | elif target == 'dhist': | |
590 | print "Flushing directory history" |
|
590 | print "Flushing directory history" | |
591 | del user_ns['_dh'][:] |
|
591 | del user_ns['_dh'][:] | |
592 |
|
592 | |||
593 | else: |
|
593 | else: | |
594 | print "Don't know how to reset ", |
|
594 | print "Don't know how to reset ", | |
595 | print target + ", please run `%reset?` for details" |
|
595 | print target + ", please run `%reset?` for details" | |
596 |
|
596 | |||
597 | gc.collect() |
|
597 | gc.collect() | |
598 |
|
598 | |||
599 | @line_magic |
|
599 | @line_magic | |
600 | def reset_selective(self, parameter_s=''): |
|
600 | def reset_selective(self, parameter_s=''): | |
601 | """Resets the namespace by removing names defined by the user. |
|
601 | """Resets the namespace by removing names defined by the user. | |
602 |
|
602 | |||
603 | Input/Output history are left around in case you need them. |
|
603 | Input/Output history are left around in case you need them. | |
604 |
|
604 | |||
605 | %reset_selective [-f] regex |
|
605 | %reset_selective [-f] regex | |
606 |
|
606 | |||
607 | No action is taken if regex is not included |
|
607 | No action is taken if regex is not included | |
608 |
|
608 | |||
609 | Options |
|
609 | Options | |
610 | -f : force reset without asking for confirmation. |
|
610 | -f : force reset without asking for confirmation. | |
611 |
|
611 | |||
612 | See Also |
|
612 | See Also | |
613 | -------- |
|
613 | -------- | |
614 | magic_reset : invoked as ``%reset`` |
|
614 | magic_reset : invoked as ``%reset`` | |
615 |
|
615 | |||
616 | Examples |
|
616 | Examples | |
617 | -------- |
|
617 | -------- | |
618 |
|
618 | |||
619 | We first fully reset the namespace so your output looks identical to |
|
619 | We first fully reset the namespace so your output looks identical to | |
620 | this example for pedagogical reasons; in practice you do not need a |
|
620 | this example for pedagogical reasons; in practice you do not need a | |
621 | full reset:: |
|
621 | full reset:: | |
622 |
|
622 | |||
623 | In [1]: %reset -f |
|
623 | In [1]: %reset -f | |
624 |
|
624 | |||
625 | Now, with a clean namespace we can make a few variables and use |
|
625 | Now, with a clean namespace we can make a few variables and use | |
626 | ``%reset_selective`` to only delete names that match our regexp:: |
|
626 | ``%reset_selective`` to only delete names that match our regexp:: | |
627 |
|
627 | |||
628 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
628 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
629 |
|
629 | |||
630 | In [3]: who_ls |
|
630 | In [3]: who_ls | |
631 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
631 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
632 |
|
632 | |||
633 | In [4]: %reset_selective -f b[2-3]m |
|
633 | In [4]: %reset_selective -f b[2-3]m | |
634 |
|
634 | |||
635 | In [5]: who_ls |
|
635 | In [5]: who_ls | |
636 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
636 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
637 |
|
637 | |||
638 | In [6]: %reset_selective -f d |
|
638 | In [6]: %reset_selective -f d | |
639 |
|
639 | |||
640 | In [7]: who_ls |
|
640 | In [7]: who_ls | |
641 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
641 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
642 |
|
642 | |||
643 | In [8]: %reset_selective -f c |
|
643 | In [8]: %reset_selective -f c | |
644 |
|
644 | |||
645 | In [9]: who_ls |
|
645 | In [9]: who_ls | |
646 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
646 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
647 |
|
647 | |||
648 | In [10]: %reset_selective -f b |
|
648 | In [10]: %reset_selective -f b | |
649 |
|
649 | |||
650 | In [11]: who_ls |
|
650 | In [11]: who_ls | |
651 | Out[11]: ['a'] |
|
651 | Out[11]: ['a'] | |
652 |
|
652 | |||
653 | Notes |
|
653 | Notes | |
654 | ----- |
|
654 | ----- | |
655 | Calling this magic from clients that do not implement standard input, |
|
655 | Calling this magic from clients that do not implement standard input, | |
656 | such as the ipython notebook interface, will reset the namespace |
|
656 | such as the ipython notebook interface, will reset the namespace | |
657 | without confirmation. |
|
657 | without confirmation. | |
658 | """ |
|
658 | """ | |
659 |
|
659 | |||
660 | opts, regex = self.parse_options(parameter_s,'f') |
|
660 | opts, regex = self.parse_options(parameter_s,'f') | |
661 |
|
661 | |||
662 | if 'f' in opts: |
|
662 | if 'f' in opts: | |
663 | ans = True |
|
663 | ans = True | |
664 | else: |
|
664 | else: | |
665 | try: |
|
665 | try: | |
666 | ans = self.shell.ask_yes_no( |
|
666 | ans = self.shell.ask_yes_no( | |
667 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
667 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |
668 | default='n') |
|
668 | default='n') | |
669 | except StdinNotImplementedError: |
|
669 | except StdinNotImplementedError: | |
670 | ans = True |
|
670 | ans = True | |
671 | if not ans: |
|
671 | if not ans: | |
672 | print 'Nothing done.' |
|
672 | print 'Nothing done.' | |
673 | return |
|
673 | return | |
674 | user_ns = self.shell.user_ns |
|
674 | user_ns = self.shell.user_ns | |
675 | if not regex: |
|
675 | if not regex: | |
676 | print 'No regex pattern specified. Nothing done.' |
|
676 | print 'No regex pattern specified. Nothing done.' | |
677 | return |
|
677 | return | |
678 | else: |
|
678 | else: | |
679 | try: |
|
679 | try: | |
680 | m = re.compile(regex) |
|
680 | m = re.compile(regex) | |
681 | except TypeError: |
|
681 | except TypeError: | |
682 | raise TypeError('regex must be a string or compiled pattern') |
|
682 | raise TypeError('regex must be a string or compiled pattern') | |
683 | for i in self.who_ls(): |
|
683 | for i in self.who_ls(): | |
684 | if m.search(i): |
|
684 | if m.search(i): | |
685 | del(user_ns[i]) |
|
685 | del(user_ns[i]) | |
686 |
|
686 | |||
687 | @line_magic |
|
687 | @line_magic | |
688 | def xdel(self, parameter_s=''): |
|
688 | def xdel(self, parameter_s=''): | |
689 | """Delete a variable, trying to clear it from anywhere that |
|
689 | """Delete a variable, trying to clear it from anywhere that | |
690 | IPython's machinery has references to it. By default, this uses |
|
690 | IPython's machinery has references to it. By default, this uses | |
691 | the identity of the named object in the user namespace to remove |
|
691 | the identity of the named object in the user namespace to remove | |
692 | references held under other names. The object is also removed |
|
692 | references held under other names. The object is also removed | |
693 | from the output history. |
|
693 | from the output history. | |
694 |
|
694 | |||
695 | Options |
|
695 | Options | |
696 | -n : Delete the specified name from all namespaces, without |
|
696 | -n : Delete the specified name from all namespaces, without | |
697 | checking their identity. |
|
697 | checking their identity. | |
698 | """ |
|
698 | """ | |
699 | opts, varname = self.parse_options(parameter_s,'n') |
|
699 | opts, varname = self.parse_options(parameter_s,'n') | |
700 | try: |
|
700 | try: | |
701 | self.shell.del_var(varname, ('n' in opts)) |
|
701 | self.shell.del_var(varname, ('n' in opts)) | |
702 | except (NameError, ValueError) as e: |
|
702 | except (NameError, ValueError) as e: | |
703 | print type(e).__name__ +": "+ str(e) |
|
703 | print type(e).__name__ +": "+ str(e) |
General Comments 0
You need to be logged in to leave comments.
Login now