Show More
This diff has been collapsed as it changes many lines, (702 lines changed) Show them Hide them | |||||
@@ -0,0 +1,702 b'' | |||||
|
1 | """Implementation of namespace-related magic functions. | |||
|
2 | """ | |||
|
3 | #----------------------------------------------------------------------------- | |||
|
4 | # Copyright (c) 2012 The IPython Development Team. | |||
|
5 | # | |||
|
6 | # Distributed under the terms of the Modified BSD License. | |||
|
7 | # | |||
|
8 | # The full license is in the file COPYING.txt, distributed with this software. | |||
|
9 | #----------------------------------------------------------------------------- | |||
|
10 | ||||
|
11 | #----------------------------------------------------------------------------- | |||
|
12 | # Imports | |||
|
13 | #----------------------------------------------------------------------------- | |||
|
14 | ||||
|
15 | # Stdlib | |||
|
16 | import gc | |||
|
17 | import re | |||
|
18 | import sys | |||
|
19 | ||||
|
20 | # Our own packages | |||
|
21 | from IPython.core import page | |||
|
22 | from IPython.core.error import StdinNotImplementedError | |||
|
23 | from IPython.core.magic import Magics, register_magics, line_magic | |||
|
24 | from IPython.testing.skipdoctest import skip_doctest | |||
|
25 | from IPython.utils.encoding import DEFAULT_ENCODING | |||
|
26 | from IPython.utils.path import get_py_filename | |||
|
27 | ||||
|
28 | #----------------------------------------------------------------------------- | |||
|
29 | # Magic implementation classes | |||
|
30 | #----------------------------------------------------------------------------- | |||
|
31 | ||||
|
32 | @register_magics | |||
|
33 | class NamespaceMagics(Magics): | |||
|
34 | """Magics to manage various aspects of the user's namespace. | |||
|
35 | ||||
|
36 | These include listing variables, introspecting into them, etc. | |||
|
37 | """ | |||
|
38 | ||||
|
39 | @line_magic | |||
|
40 | def pinfo(self, parameter_s='', namespaces=None): | |||
|
41 | """Provide detailed information about an object. | |||
|
42 | ||||
|
43 | '%pinfo object' is just a synonym for object? or ?object.""" | |||
|
44 | ||||
|
45 | #print 'pinfo par: <%s>' % parameter_s # dbg | |||
|
46 | ||||
|
47 | ||||
|
48 | # detail_level: 0 -> obj? , 1 -> obj?? | |||
|
49 | detail_level = 0 | |||
|
50 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |||
|
51 | # happen if the user types 'pinfo foo?' at the cmd line. | |||
|
52 | pinfo,qmark1,oname,qmark2 = \ | |||
|
53 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |||
|
54 | if pinfo or qmark1 or qmark2: | |||
|
55 | detail_level = 1 | |||
|
56 | if "*" in oname: | |||
|
57 | self.psearch(oname) | |||
|
58 | else: | |||
|
59 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |||
|
60 | namespaces=namespaces) | |||
|
61 | ||||
|
62 | @line_magic | |||
|
63 | def pinfo2(self, parameter_s='', namespaces=None): | |||
|
64 | """Provide extra detailed information about an object. | |||
|
65 | ||||
|
66 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |||
|
67 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |||
|
68 | namespaces=namespaces) | |||
|
69 | ||||
|
70 | @skip_doctest | |||
|
71 | @line_magic | |||
|
72 | def pdef(self, parameter_s='', namespaces=None): | |||
|
73 | """Print the definition header for any callable object. | |||
|
74 | ||||
|
75 | If the object is a class, print the constructor information. | |||
|
76 | ||||
|
77 | Examples | |||
|
78 | -------- | |||
|
79 | :: | |||
|
80 | ||||
|
81 | In [3]: %pdef urllib.urlopen | |||
|
82 | urllib.urlopen(url, data=None, proxies=None) | |||
|
83 | """ | |||
|
84 | self._inspect('pdef',parameter_s, namespaces) | |||
|
85 | ||||
|
86 | @line_magic | |||
|
87 | def pdoc(self, parameter_s='', namespaces=None): | |||
|
88 | """Print the docstring for an object. | |||
|
89 | ||||
|
90 | If the given object is a class, it will print both the class and the | |||
|
91 | constructor docstrings.""" | |||
|
92 | self._inspect('pdoc',parameter_s, namespaces) | |||
|
93 | ||||
|
94 | @line_magic | |||
|
95 | def psource(self, parameter_s='', namespaces=None): | |||
|
96 | """Print (or run through pager) the source code for an object.""" | |||
|
97 | self._inspect('psource',parameter_s, namespaces) | |||
|
98 | ||||
|
99 | @line_magic | |||
|
100 | def pfile(self, parameter_s=''): | |||
|
101 | """Print (or run through pager) the file where an object is defined. | |||
|
102 | ||||
|
103 | The file opens at the line where the object definition begins. IPython | |||
|
104 | will honor the environment variable PAGER if set, and otherwise will | |||
|
105 | do its best to print the file in a convenient form. | |||
|
106 | ||||
|
107 | If the given argument is not an object currently defined, IPython will | |||
|
108 | try to interpret it as a filename (automatically adding a .py extension | |||
|
109 | if needed). You can thus use %pfile as a syntax highlighting code | |||
|
110 | viewer.""" | |||
|
111 | ||||
|
112 | # first interpret argument as an object name | |||
|
113 | out = self._inspect('pfile',parameter_s) | |||
|
114 | # if not, try the input as a filename | |||
|
115 | if out == 'not found': | |||
|
116 | try: | |||
|
117 | filename = get_py_filename(parameter_s) | |||
|
118 | except IOError,msg: | |||
|
119 | print msg | |||
|
120 | return | |||
|
121 | page.page(self.shell.inspector.format(open(filename).read())) | |||
|
122 | ||||
|
123 | @line_magic | |||
|
124 | def psearch(self, parameter_s=''): | |||
|
125 | """Search for object in namespaces by wildcard. | |||
|
126 | ||||
|
127 | %psearch [options] PATTERN [OBJECT TYPE] | |||
|
128 | ||||
|
129 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |||
|
130 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |||
|
131 | rest of the command line must be unchanged (options come first), so | |||
|
132 | for example the following forms are equivalent | |||
|
133 | ||||
|
134 | %psearch -i a* function | |||
|
135 | -i a* function? | |||
|
136 | ?-i a* function | |||
|
137 | ||||
|
138 | Arguments: | |||
|
139 | ||||
|
140 | PATTERN | |||
|
141 | ||||
|
142 | where PATTERN is a string containing * as a wildcard similar to its | |||
|
143 | use in a shell. The pattern is matched in all namespaces on the | |||
|
144 | search path. By default objects starting with a single _ are not | |||
|
145 | matched, many IPython generated objects have a single | |||
|
146 | underscore. The default is case insensitive matching. Matching is | |||
|
147 | also done on the attributes of objects and not only on the objects | |||
|
148 | in a module. | |||
|
149 | ||||
|
150 | [OBJECT TYPE] | |||
|
151 | ||||
|
152 | Is the name of a python type from the types module. The name is | |||
|
153 | given in lowercase without the ending type, ex. StringType is | |||
|
154 | written string. By adding a type here only objects matching the | |||
|
155 | given type are matched. Using all here makes the pattern match all | |||
|
156 | types (this is the default). | |||
|
157 | ||||
|
158 | Options: | |||
|
159 | ||||
|
160 | -a: makes the pattern match even objects whose names start with a | |||
|
161 | single underscore. These names are normally omitted from the | |||
|
162 | search. | |||
|
163 | ||||
|
164 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |||
|
165 | these options are given, the default is read from your configuration | |||
|
166 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. | |||
|
167 | If this option is not specified in your configuration file, IPython's | |||
|
168 | internal default is to do a case sensitive search. | |||
|
169 | ||||
|
170 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |||
|
171 | specify can be searched in any of the following namespaces: | |||
|
172 | 'builtin', 'user', 'user_global','internal', 'alias', where | |||
|
173 | 'builtin' and 'user' are the search defaults. Note that you should | |||
|
174 | not use quotes when specifying namespaces. | |||
|
175 | ||||
|
176 | 'Builtin' contains the python module builtin, 'user' contains all | |||
|
177 | user data, 'alias' only contain the shell aliases and no python | |||
|
178 | objects, 'internal' contains objects used by IPython. The | |||
|
179 | 'user_global' namespace is only used by embedded IPython instances, | |||
|
180 | and it contains module-level globals. You can add namespaces to the | |||
|
181 | search with -s or exclude them with -e (these options can be given | |||
|
182 | more than once). | |||
|
183 | ||||
|
184 | Examples | |||
|
185 | -------- | |||
|
186 | :: | |||
|
187 | ||||
|
188 | %psearch a* -> objects beginning with an a | |||
|
189 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |||
|
190 | %psearch a* function -> all functions beginning with an a | |||
|
191 | %psearch re.e* -> objects beginning with an e in module re | |||
|
192 | %psearch r*.e* -> objects that start with e in modules starting in r | |||
|
193 | %psearch r*.* string -> all strings in modules beginning with r | |||
|
194 | ||||
|
195 | Case sensitive search:: | |||
|
196 | ||||
|
197 | %psearch -c a* list all object beginning with lower case a | |||
|
198 | ||||
|
199 | Show objects beginning with a single _:: | |||
|
200 | ||||
|
201 | %psearch -a _* list objects beginning with a single underscore | |||
|
202 | """ | |||
|
203 | try: | |||
|
204 | parameter_s.encode('ascii') | |||
|
205 | except UnicodeEncodeError: | |||
|
206 | print 'Python identifiers can only contain ascii characters.' | |||
|
207 | return | |||
|
208 | ||||
|
209 | # default namespaces to be searched | |||
|
210 | def_search = ['user_local', 'user_global', 'builtin'] | |||
|
211 | ||||
|
212 | # Process options/args | |||
|
213 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |||
|
214 | opt = opts.get | |||
|
215 | shell = self.shell | |||
|
216 | psearch = shell.inspector.psearch | |||
|
217 | ||||
|
218 | # select case options | |||
|
219 | if opts.has_key('i'): | |||
|
220 | ignore_case = True | |||
|
221 | elif opts.has_key('c'): | |||
|
222 | ignore_case = False | |||
|
223 | else: | |||
|
224 | ignore_case = not shell.wildcards_case_sensitive | |||
|
225 | ||||
|
226 | # Build list of namespaces to search from user options | |||
|
227 | def_search.extend(opt('s',[])) | |||
|
228 | ns_exclude = ns_exclude=opt('e',[]) | |||
|
229 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |||
|
230 | ||||
|
231 | # Call the actual search | |||
|
232 | try: | |||
|
233 | psearch(args,shell.ns_table,ns_search, | |||
|
234 | show_all=opt('a'),ignore_case=ignore_case) | |||
|
235 | except: | |||
|
236 | shell.showtraceback() | |||
|
237 | ||||
|
238 | @skip_doctest | |||
|
239 | @line_magic | |||
|
240 | def who_ls(self, parameter_s=''): | |||
|
241 | """Return a sorted list of all interactive variables. | |||
|
242 | ||||
|
243 | If arguments are given, only variables of types matching these | |||
|
244 | arguments are returned. | |||
|
245 | ||||
|
246 | Examples | |||
|
247 | -------- | |||
|
248 | ||||
|
249 | Define two variables and list them with who_ls:: | |||
|
250 | ||||
|
251 | In [1]: alpha = 123 | |||
|
252 | ||||
|
253 | In [2]: beta = 'test' | |||
|
254 | ||||
|
255 | In [3]: %who_ls | |||
|
256 | Out[3]: ['alpha', 'beta'] | |||
|
257 | ||||
|
258 | In [4]: %who_ls int | |||
|
259 | Out[4]: ['alpha'] | |||
|
260 | ||||
|
261 | In [5]: %who_ls str | |||
|
262 | Out[5]: ['beta'] | |||
|
263 | """ | |||
|
264 | ||||
|
265 | user_ns = self.shell.user_ns | |||
|
266 | user_ns_hidden = self.shell.user_ns_hidden | |||
|
267 | out = [ i for i in user_ns | |||
|
268 | if not i.startswith('_') \ | |||
|
269 | and not i in user_ns_hidden ] | |||
|
270 | ||||
|
271 | typelist = parameter_s.split() | |||
|
272 | if typelist: | |||
|
273 | typeset = set(typelist) | |||
|
274 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] | |||
|
275 | ||||
|
276 | out.sort() | |||
|
277 | return out | |||
|
278 | ||||
|
279 | @skip_doctest | |||
|
280 | @line_magic | |||
|
281 | def who(self, parameter_s=''): | |||
|
282 | """Print all interactive variables, with some minimal formatting. | |||
|
283 | ||||
|
284 | If any arguments are given, only variables whose type matches one of | |||
|
285 | these are printed. For example:: | |||
|
286 | ||||
|
287 | %who function str | |||
|
288 | ||||
|
289 | will only list functions and strings, excluding all other types of | |||
|
290 | variables. To find the proper type names, simply use type(var) at a | |||
|
291 | command line to see how python prints type names. For example: | |||
|
292 | ||||
|
293 | :: | |||
|
294 | ||||
|
295 | In [1]: type('hello')\\ | |||
|
296 | Out[1]: <type 'str'> | |||
|
297 | ||||
|
298 | indicates that the type name for strings is 'str'. | |||
|
299 | ||||
|
300 | ``%who`` always excludes executed names loaded through your configuration | |||
|
301 | file and things which are internal to IPython. | |||
|
302 | ||||
|
303 | This is deliberate, as typically you may load many modules and the | |||
|
304 | purpose of %who is to show you only what you've manually defined. | |||
|
305 | ||||
|
306 | Examples | |||
|
307 | -------- | |||
|
308 | ||||
|
309 | Define two variables and list them with who:: | |||
|
310 | ||||
|
311 | In [1]: alpha = 123 | |||
|
312 | ||||
|
313 | In [2]: beta = 'test' | |||
|
314 | ||||
|
315 | In [3]: %who | |||
|
316 | alpha beta | |||
|
317 | ||||
|
318 | In [4]: %who int | |||
|
319 | alpha | |||
|
320 | ||||
|
321 | In [5]: %who str | |||
|
322 | beta | |||
|
323 | """ | |||
|
324 | ||||
|
325 | varlist = self.who_ls(parameter_s) | |||
|
326 | if not varlist: | |||
|
327 | if parameter_s: | |||
|
328 | print 'No variables match your requested type.' | |||
|
329 | else: | |||
|
330 | print 'Interactive namespace is empty.' | |||
|
331 | return | |||
|
332 | ||||
|
333 | # if we have variables, move on... | |||
|
334 | count = 0 | |||
|
335 | for i in varlist: | |||
|
336 | print i+'\t', | |||
|
337 | count += 1 | |||
|
338 | if count > 8: | |||
|
339 | count = 0 | |||
|
340 | ||||
|
341 | ||||
|
342 | ||||
|
343 | @skip_doctest | |||
|
344 | @line_magic | |||
|
345 | def whos(self, parameter_s=''): | |||
|
346 | """Like %who, but gives some extra information about each variable. | |||
|
347 | ||||
|
348 | The same type filtering of %who can be applied here. | |||
|
349 | ||||
|
350 | For all variables, the type is printed. Additionally it prints: | |||
|
351 | ||||
|
352 | - For {},[],(): their length. | |||
|
353 | ||||
|
354 | - For numpy arrays, a summary with shape, number of | |||
|
355 | elements, typecode and size in memory. | |||
|
356 | ||||
|
357 | - Everything else: a string representation, snipping their middle if | |||
|
358 | too long. | |||
|
359 | ||||
|
360 | Examples | |||
|
361 | -------- | |||
|
362 | ||||
|
363 | Define two variables and list them with whos:: | |||
|
364 | ||||
|
365 | In [1]: alpha = 123 | |||
|
366 | ||||
|
367 | In [2]: beta = 'test' | |||
|
368 | ||||
|
369 | In [3]: %whos | |||
|
370 | Variable Type Data/Info | |||
|
371 | -------------------------------- | |||
|
372 | alpha int 123 | |||
|
373 | beta str test | |||
|
374 | """ | |||
|
375 | ||||
|
376 | varnames = self.who_ls(parameter_s) | |||
|
377 | if not varnames: | |||
|
378 | if parameter_s: | |||
|
379 | print 'No variables match your requested type.' | |||
|
380 | else: | |||
|
381 | print 'Interactive namespace is empty.' | |||
|
382 | return | |||
|
383 | ||||
|
384 | # if we have variables, move on... | |||
|
385 | ||||
|
386 | # for these types, show len() instead of data: | |||
|
387 | seq_types = ['dict', 'list', 'tuple'] | |||
|
388 | ||||
|
389 | # for numpy arrays, display summary info | |||
|
390 | ndarray_type = None | |||
|
391 | if 'numpy' in sys.modules: | |||
|
392 | try: | |||
|
393 | from numpy import ndarray | |||
|
394 | except ImportError: | |||
|
395 | pass | |||
|
396 | else: | |||
|
397 | ndarray_type = ndarray.__name__ | |||
|
398 | ||||
|
399 | # Find all variable names and types so we can figure out column sizes | |||
|
400 | def get_vars(i): | |||
|
401 | return self.shell.user_ns[i] | |||
|
402 | ||||
|
403 | # some types are well known and can be shorter | |||
|
404 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |||
|
405 | def type_name(v): | |||
|
406 | tn = type(v).__name__ | |||
|
407 | return abbrevs.get(tn,tn) | |||
|
408 | ||||
|
409 | varlist = map(get_vars,varnames) | |||
|
410 | ||||
|
411 | typelist = [] | |||
|
412 | for vv in varlist: | |||
|
413 | tt = type_name(vv) | |||
|
414 | ||||
|
415 | if tt=='instance': | |||
|
416 | typelist.append( abbrevs.get(str(vv.__class__), | |||
|
417 | str(vv.__class__))) | |||
|
418 | else: | |||
|
419 | typelist.append(tt) | |||
|
420 | ||||
|
421 | # column labels and # of spaces as separator | |||
|
422 | varlabel = 'Variable' | |||
|
423 | typelabel = 'Type' | |||
|
424 | datalabel = 'Data/Info' | |||
|
425 | colsep = 3 | |||
|
426 | # variable format strings | |||
|
427 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" | |||
|
428 | aformat = "%s: %s elems, type `%s`, %s bytes" | |||
|
429 | # find the size of the columns to format the output nicely | |||
|
430 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |||
|
431 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |||
|
432 | # table header | |||
|
433 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |||
|
434 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |||
|
435 | # and the table itself | |||
|
436 | kb = 1024 | |||
|
437 | Mb = 1048576 # kb**2 | |||
|
438 | for vname,var,vtype in zip(varnames,varlist,typelist): | |||
|
439 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), | |||
|
440 | if vtype in seq_types: | |||
|
441 | print "n="+str(len(var)) | |||
|
442 | elif vtype == ndarray_type: | |||
|
443 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |||
|
444 | if vtype==ndarray_type: | |||
|
445 | # numpy | |||
|
446 | vsize = var.size | |||
|
447 | vbytes = vsize*var.itemsize | |||
|
448 | vdtype = var.dtype | |||
|
449 | ||||
|
450 | if vbytes < 100000: | |||
|
451 | print aformat % (vshape,vsize,vdtype,vbytes) | |||
|
452 | else: | |||
|
453 | print aformat % (vshape,vsize,vdtype,vbytes), | |||
|
454 | if vbytes < Mb: | |||
|
455 | print '(%s kb)' % (vbytes/kb,) | |||
|
456 | else: | |||
|
457 | print '(%s Mb)' % (vbytes/Mb,) | |||
|
458 | else: | |||
|
459 | try: | |||
|
460 | vstr = str(var) | |||
|
461 | except UnicodeEncodeError: | |||
|
462 | vstr = unicode(var).encode(DEFAULT_ENCODING, | |||
|
463 | 'backslashreplace') | |||
|
464 | except: | |||
|
465 | vstr = "<object with id %d (str() failed)>" % id(var) | |||
|
466 | vstr = vstr.replace('\n','\\n') | |||
|
467 | if len(vstr) < 50: | |||
|
468 | print vstr | |||
|
469 | else: | |||
|
470 | print vstr[:25] + "<...>" + vstr[-25:] | |||
|
471 | ||||
|
472 | @line_magic | |||
|
473 | def reset(self, parameter_s=''): | |||
|
474 | """Resets the namespace by removing all names defined by the user, if | |||
|
475 | called without arguments, or by removing some types of objects, such | |||
|
476 | as everything currently in IPython's In[] and Out[] containers (see | |||
|
477 | the parameters for details). | |||
|
478 | ||||
|
479 | Parameters | |||
|
480 | ---------- | |||
|
481 | -f : force reset without asking for confirmation. | |||
|
482 | ||||
|
483 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. | |||
|
484 | References to objects may be kept. By default (without this option), | |||
|
485 | we do a 'hard' reset, giving you a new session and removing all | |||
|
486 | references to objects from the current session. | |||
|
487 | ||||
|
488 | in : reset input history | |||
|
489 | ||||
|
490 | out : reset output history | |||
|
491 | ||||
|
492 | dhist : reset directory history | |||
|
493 | ||||
|
494 | array : reset only variables that are NumPy arrays | |||
|
495 | ||||
|
496 | See Also | |||
|
497 | -------- | |||
|
498 | magic_reset_selective : invoked as ``%reset_selective`` | |||
|
499 | ||||
|
500 | Examples | |||
|
501 | -------- | |||
|
502 | :: | |||
|
503 | ||||
|
504 | In [6]: a = 1 | |||
|
505 | ||||
|
506 | In [7]: a | |||
|
507 | Out[7]: 1 | |||
|
508 | ||||
|
509 | In [8]: 'a' in _ip.user_ns | |||
|
510 | Out[8]: True | |||
|
511 | ||||
|
512 | In [9]: %reset -f | |||
|
513 | ||||
|
514 | In [1]: 'a' in _ip.user_ns | |||
|
515 | Out[1]: False | |||
|
516 | ||||
|
517 | In [2]: %reset -f in | |||
|
518 | Flushing input history | |||
|
519 | ||||
|
520 | In [3]: %reset -f dhist in | |||
|
521 | Flushing directory history | |||
|
522 | Flushing input history | |||
|
523 | ||||
|
524 | Notes | |||
|
525 | ----- | |||
|
526 | Calling this magic from clients that do not implement standard input, | |||
|
527 | such as the ipython notebook interface, will reset the namespace | |||
|
528 | without confirmation. | |||
|
529 | """ | |||
|
530 | opts, args = self.parse_options(parameter_s,'sf', mode='list') | |||
|
531 | if 'f' in opts: | |||
|
532 | ans = True | |||
|
533 | else: | |||
|
534 | try: | |||
|
535 | ans = self.shell.ask_yes_no( | |||
|
536 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", | |||
|
537 | default='n') | |||
|
538 | except StdinNotImplementedError: | |||
|
539 | ans = True | |||
|
540 | if not ans: | |||
|
541 | print 'Nothing done.' | |||
|
542 | return | |||
|
543 | ||||
|
544 | if 's' in opts: # Soft reset | |||
|
545 | user_ns = self.shell.user_ns | |||
|
546 | for i in self.who_ls(): | |||
|
547 | del(user_ns[i]) | |||
|
548 | elif len(args) == 0: # Hard reset | |||
|
549 | self.shell.reset(new_session = False) | |||
|
550 | ||||
|
551 | # reset in/out/dhist/array: previously extensinions/clearcmd.py | |||
|
552 | ip = self.shell | |||
|
553 | user_ns = self.shell.user_ns # local lookup, heavily used | |||
|
554 | ||||
|
555 | for target in args: | |||
|
556 | target = target.lower() # make matches case insensitive | |||
|
557 | if target == 'out': | |||
|
558 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) | |||
|
559 | self.shell.displayhook.flush() | |||
|
560 | ||||
|
561 | elif target == 'in': | |||
|
562 | print "Flushing input history" | |||
|
563 | pc = self.shell.displayhook.prompt_count + 1 | |||
|
564 | for n in range(1, pc): | |||
|
565 | key = '_i'+repr(n) | |||
|
566 | user_ns.pop(key,None) | |||
|
567 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) | |||
|
568 | hm = ip.history_manager | |||
|
569 | # don't delete these, as %save and %macro depending on the | |||
|
570 | # length of these lists to be preserved | |||
|
571 | hm.input_hist_parsed[:] = [''] * pc | |||
|
572 | hm.input_hist_raw[:] = [''] * pc | |||
|
573 | # hm has internal machinery for _i,_ii,_iii, clear it out | |||
|
574 | hm._i = hm._ii = hm._iii = hm._i00 = u'' | |||
|
575 | ||||
|
576 | elif target == 'array': | |||
|
577 | # Support cleaning up numpy arrays | |||
|
578 | try: | |||
|
579 | from numpy import ndarray | |||
|
580 | # This must be done with items and not iteritems because | |||
|
581 | # we're going to modify the dict in-place. | |||
|
582 | for x,val in user_ns.items(): | |||
|
583 | if isinstance(val,ndarray): | |||
|
584 | del user_ns[x] | |||
|
585 | except ImportError: | |||
|
586 | print "reset array only works if Numpy is available." | |||
|
587 | ||||
|
588 | elif target == 'dhist': | |||
|
589 | print "Flushing directory history" | |||
|
590 | del user_ns['_dh'][:] | |||
|
591 | ||||
|
592 | else: | |||
|
593 | print "Don't know how to reset ", | |||
|
594 | print target + ", please run `%reset?` for details" | |||
|
595 | ||||
|
596 | gc.collect() | |||
|
597 | ||||
|
598 | @line_magic | |||
|
599 | def reset_selective(self, parameter_s=''): | |||
|
600 | """Resets the namespace by removing names defined by the user. | |||
|
601 | ||||
|
602 | Input/Output history are left around in case you need them. | |||
|
603 | ||||
|
604 | %reset_selective [-f] regex | |||
|
605 | ||||
|
606 | No action is taken if regex is not included | |||
|
607 | ||||
|
608 | Options | |||
|
609 | -f : force reset without asking for confirmation. | |||
|
610 | ||||
|
611 | See Also | |||
|
612 | -------- | |||
|
613 | magic_reset : invoked as ``%reset`` | |||
|
614 | ||||
|
615 | Examples | |||
|
616 | -------- | |||
|
617 | ||||
|
618 | We first fully reset the namespace so your output looks identical to | |||
|
619 | this example for pedagogical reasons; in practice you do not need a | |||
|
620 | full reset:: | |||
|
621 | ||||
|
622 | In [1]: %reset -f | |||
|
623 | ||||
|
624 | Now, with a clean namespace we can make a few variables and use | |||
|
625 | ``%reset_selective`` to only delete names that match our regexp:: | |||
|
626 | ||||
|
627 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |||
|
628 | ||||
|
629 | In [3]: who_ls | |||
|
630 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |||
|
631 | ||||
|
632 | In [4]: %reset_selective -f b[2-3]m | |||
|
633 | ||||
|
634 | In [5]: who_ls | |||
|
635 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |||
|
636 | ||||
|
637 | In [6]: %reset_selective -f d | |||
|
638 | ||||
|
639 | In [7]: who_ls | |||
|
640 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |||
|
641 | ||||
|
642 | In [8]: %reset_selective -f c | |||
|
643 | ||||
|
644 | In [9]: who_ls | |||
|
645 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |||
|
646 | ||||
|
647 | In [10]: %reset_selective -f b | |||
|
648 | ||||
|
649 | In [11]: who_ls | |||
|
650 | Out[11]: ['a'] | |||
|
651 | ||||
|
652 | Notes | |||
|
653 | ----- | |||
|
654 | Calling this magic from clients that do not implement standard input, | |||
|
655 | such as the ipython notebook interface, will reset the namespace | |||
|
656 | without confirmation. | |||
|
657 | """ | |||
|
658 | ||||
|
659 | opts, regex = self.parse_options(parameter_s,'f') | |||
|
660 | ||||
|
661 | if opts.has_key('f'): | |||
|
662 | ans = True | |||
|
663 | else: | |||
|
664 | try: | |||
|
665 | ans = self.shell.ask_yes_no( | |||
|
666 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", | |||
|
667 | default='n') | |||
|
668 | except StdinNotImplementedError: | |||
|
669 | ans = True | |||
|
670 | if not ans: | |||
|
671 | print 'Nothing done.' | |||
|
672 | return | |||
|
673 | user_ns = self.shell.user_ns | |||
|
674 | if not regex: | |||
|
675 | print 'No regex pattern specified. Nothing done.' | |||
|
676 | return | |||
|
677 | else: | |||
|
678 | try: | |||
|
679 | m = re.compile(regex) | |||
|
680 | except TypeError: | |||
|
681 | raise TypeError('regex must be a string or compiled pattern') | |||
|
682 | for i in self.who_ls(): | |||
|
683 | if m.search(i): | |||
|
684 | del(user_ns[i]) | |||
|
685 | ||||
|
686 | @line_magic | |||
|
687 | def xdel(self, parameter_s=''): | |||
|
688 | """Delete a variable, trying to clear it from anywhere that | |||
|
689 | IPython's machinery has references to it. By default, this uses | |||
|
690 | the identity of the named object in the user namespace to remove | |||
|
691 | references held under other names. The object is also removed | |||
|
692 | from the output history. | |||
|
693 | ||||
|
694 | Options | |||
|
695 | -n : Delete the specified name from all namespaces, without | |||
|
696 | checking their identity. | |||
|
697 | """ | |||
|
698 | opts, varname = self.parse_options(parameter_s,'n') | |||
|
699 | try: | |||
|
700 | self.shell.del_var(varname, ('n' in opts)) | |||
|
701 | except (NameError, ValueError) as e: | |||
|
702 | print type(e).__name__ +": "+ str(e) |
@@ -2006,7 +2006,7 b' class InteractiveShell(SingletonConfigurable):' | |||||
2006 | self.define_magic = self.magics_manager.define_magic |
|
2006 | self.define_magic = self.magics_manager.define_magic | |
2007 |
|
2007 | |||
2008 | self.register_magics(m.BasicMagics, m.CodeMagics, m.ConfigMagics, |
|
2008 | self.register_magics(m.BasicMagics, m.CodeMagics, m.ConfigMagics, | |
2009 |
mf.ExecutionMagics, m |
|
2009 | mf.ExecutionMagics, m.NamespaceMagics, mf.AutoMagics, | |
2010 | mf.OSMagics, mf.LoggingMagics, mf.ExtensionsMagics, |
|
2010 | mf.OSMagics, mf.LoggingMagics, mf.ExtensionsMagics, | |
2011 | mf.PylabMagics, m.HistoryMagics, mf.DeprecatedMagics) |
|
2011 | mf.PylabMagics, m.HistoryMagics, mf.DeprecatedMagics) | |
2012 |
|
2012 |
This diff has been collapsed as it changes many lines, (672 lines changed) Show them Hide them | |||||
@@ -65,678 +65,6 b' from IPython.utils.warn import warn, error' | |||||
65 | #----------------------------------------------------------------------------- |
|
65 | #----------------------------------------------------------------------------- | |
66 | # Magic implementation classes |
|
66 | # Magic implementation classes | |
67 | #----------------------------------------------------------------------------- |
|
67 | #----------------------------------------------------------------------------- | |
68 | @register_magics |
|
|||
69 | class NamespaceMagics(Magics): |
|
|||
70 | """Magics to manage various aspects of the user's namespace. |
|
|||
71 |
|
||||
72 | These include listing variables, introspecting into them, etc. |
|
|||
73 | """ |
|
|||
74 |
|
||||
75 | @line_magic |
|
|||
76 | def pinfo(self, parameter_s='', namespaces=None): |
|
|||
77 | """Provide detailed information about an object. |
|
|||
78 |
|
||||
79 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
|||
80 |
|
||||
81 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
|||
82 |
|
||||
83 |
|
||||
84 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
|||
85 | detail_level = 0 |
|
|||
86 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
|||
87 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
|||
88 | pinfo,qmark1,oname,qmark2 = \ |
|
|||
89 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
|||
90 | if pinfo or qmark1 or qmark2: |
|
|||
91 | detail_level = 1 |
|
|||
92 | if "*" in oname: |
|
|||
93 | self.psearch(oname) |
|
|||
94 | else: |
|
|||
95 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
|||
96 | namespaces=namespaces) |
|
|||
97 |
|
||||
98 | @line_magic |
|
|||
99 | def pinfo2(self, parameter_s='', namespaces=None): |
|
|||
100 | """Provide extra detailed information about an object. |
|
|||
101 |
|
||||
102 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
|||
103 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
|||
104 | namespaces=namespaces) |
|
|||
105 |
|
||||
106 | @skip_doctest |
|
|||
107 | @line_magic |
|
|||
108 | def pdef(self, parameter_s='', namespaces=None): |
|
|||
109 | """Print the definition header for any callable object. |
|
|||
110 |
|
||||
111 | If the object is a class, print the constructor information. |
|
|||
112 |
|
||||
113 | Examples |
|
|||
114 | -------- |
|
|||
115 | :: |
|
|||
116 |
|
||||
117 | In [3]: %pdef urllib.urlopen |
|
|||
118 | urllib.urlopen(url, data=None, proxies=None) |
|
|||
119 | """ |
|
|||
120 | self._inspect('pdef',parameter_s, namespaces) |
|
|||
121 |
|
||||
122 | @line_magic |
|
|||
123 | def pdoc(self, parameter_s='', namespaces=None): |
|
|||
124 | """Print the docstring for an object. |
|
|||
125 |
|
||||
126 | If the given object is a class, it will print both the class and the |
|
|||
127 | constructor docstrings.""" |
|
|||
128 | self._inspect('pdoc',parameter_s, namespaces) |
|
|||
129 |
|
||||
130 | @line_magic |
|
|||
131 | def psource(self, parameter_s='', namespaces=None): |
|
|||
132 | """Print (or run through pager) the source code for an object.""" |
|
|||
133 | self._inspect('psource',parameter_s, namespaces) |
|
|||
134 |
|
||||
135 | @line_magic |
|
|||
136 | def pfile(self, parameter_s=''): |
|
|||
137 | """Print (or run through pager) the file where an object is defined. |
|
|||
138 |
|
||||
139 | The file opens at the line where the object definition begins. IPython |
|
|||
140 | will honor the environment variable PAGER if set, and otherwise will |
|
|||
141 | do its best to print the file in a convenient form. |
|
|||
142 |
|
||||
143 | If the given argument is not an object currently defined, IPython will |
|
|||
144 | try to interpret it as a filename (automatically adding a .py extension |
|
|||
145 | if needed). You can thus use %pfile as a syntax highlighting code |
|
|||
146 | viewer.""" |
|
|||
147 |
|
||||
148 | # first interpret argument as an object name |
|
|||
149 | out = self._inspect('pfile',parameter_s) |
|
|||
150 | # if not, try the input as a filename |
|
|||
151 | if out == 'not found': |
|
|||
152 | try: |
|
|||
153 | filename = get_py_filename(parameter_s) |
|
|||
154 | except IOError,msg: |
|
|||
155 | print msg |
|
|||
156 | return |
|
|||
157 | page.page(self.shell.inspector.format(open(filename).read())) |
|
|||
158 |
|
||||
159 | @line_magic |
|
|||
160 | def psearch(self, parameter_s=''): |
|
|||
161 | """Search for object in namespaces by wildcard. |
|
|||
162 |
|
||||
163 | %psearch [options] PATTERN [OBJECT TYPE] |
|
|||
164 |
|
||||
165 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
|||
166 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
|||
167 | rest of the command line must be unchanged (options come first), so |
|
|||
168 | for example the following forms are equivalent |
|
|||
169 |
|
||||
170 | %psearch -i a* function |
|
|||
171 | -i a* function? |
|
|||
172 | ?-i a* function |
|
|||
173 |
|
||||
174 | Arguments: |
|
|||
175 |
|
||||
176 | PATTERN |
|
|||
177 |
|
||||
178 | where PATTERN is a string containing * as a wildcard similar to its |
|
|||
179 | use in a shell. The pattern is matched in all namespaces on the |
|
|||
180 | search path. By default objects starting with a single _ are not |
|
|||
181 | matched, many IPython generated objects have a single |
|
|||
182 | underscore. The default is case insensitive matching. Matching is |
|
|||
183 | also done on the attributes of objects and not only on the objects |
|
|||
184 | in a module. |
|
|||
185 |
|
||||
186 | [OBJECT TYPE] |
|
|||
187 |
|
||||
188 | Is the name of a python type from the types module. The name is |
|
|||
189 | given in lowercase without the ending type, ex. StringType is |
|
|||
190 | written string. By adding a type here only objects matching the |
|
|||
191 | given type are matched. Using all here makes the pattern match all |
|
|||
192 | types (this is the default). |
|
|||
193 |
|
||||
194 | Options: |
|
|||
195 |
|
||||
196 | -a: makes the pattern match even objects whose names start with a |
|
|||
197 | single underscore. These names are normally omitted from the |
|
|||
198 | search. |
|
|||
199 |
|
||||
200 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
|||
201 | these options are given, the default is read from your configuration |
|
|||
202 | file, with the option ``InteractiveShell.wildcards_case_sensitive``. |
|
|||
203 | If this option is not specified in your configuration file, IPython's |
|
|||
204 | internal default is to do a case sensitive search. |
|
|||
205 |
|
||||
206 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
|||
207 | specify can be searched in any of the following namespaces: |
|
|||
208 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
|||
209 | 'builtin' and 'user' are the search defaults. Note that you should |
|
|||
210 | not use quotes when specifying namespaces. |
|
|||
211 |
|
||||
212 | 'Builtin' contains the python module builtin, 'user' contains all |
|
|||
213 | user data, 'alias' only contain the shell aliases and no python |
|
|||
214 | objects, 'internal' contains objects used by IPython. The |
|
|||
215 | 'user_global' namespace is only used by embedded IPython instances, |
|
|||
216 | and it contains module-level globals. You can add namespaces to the |
|
|||
217 | search with -s or exclude them with -e (these options can be given |
|
|||
218 | more than once). |
|
|||
219 |
|
||||
220 | Examples |
|
|||
221 | -------- |
|
|||
222 | :: |
|
|||
223 |
|
||||
224 | %psearch a* -> objects beginning with an a |
|
|||
225 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
|||
226 | %psearch a* function -> all functions beginning with an a |
|
|||
227 | %psearch re.e* -> objects beginning with an e in module re |
|
|||
228 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
|||
229 | %psearch r*.* string -> all strings in modules beginning with r |
|
|||
230 |
|
||||
231 | Case sensitive search:: |
|
|||
232 |
|
||||
233 | %psearch -c a* list all object beginning with lower case a |
|
|||
234 |
|
||||
235 | Show objects beginning with a single _:: |
|
|||
236 |
|
||||
237 | %psearch -a _* list objects beginning with a single underscore |
|
|||
238 | """ |
|
|||
239 | try: |
|
|||
240 | parameter_s.encode('ascii') |
|
|||
241 | except UnicodeEncodeError: |
|
|||
242 | print 'Python identifiers can only contain ascii characters.' |
|
|||
243 | return |
|
|||
244 |
|
||||
245 | # default namespaces to be searched |
|
|||
246 | def_search = ['user_local', 'user_global', 'builtin'] |
|
|||
247 |
|
||||
248 | # Process options/args |
|
|||
249 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
|||
250 | opt = opts.get |
|
|||
251 | shell = self.shell |
|
|||
252 | psearch = shell.inspector.psearch |
|
|||
253 |
|
||||
254 | # select case options |
|
|||
255 | if opts.has_key('i'): |
|
|||
256 | ignore_case = True |
|
|||
257 | elif opts.has_key('c'): |
|
|||
258 | ignore_case = False |
|
|||
259 | else: |
|
|||
260 | ignore_case = not shell.wildcards_case_sensitive |
|
|||
261 |
|
||||
262 | # Build list of namespaces to search from user options |
|
|||
263 | def_search.extend(opt('s',[])) |
|
|||
264 | ns_exclude = ns_exclude=opt('e',[]) |
|
|||
265 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
|||
266 |
|
||||
267 | # Call the actual search |
|
|||
268 | try: |
|
|||
269 | psearch(args,shell.ns_table,ns_search, |
|
|||
270 | show_all=opt('a'),ignore_case=ignore_case) |
|
|||
271 | except: |
|
|||
272 | shell.showtraceback() |
|
|||
273 |
|
||||
274 | @skip_doctest |
|
|||
275 | @line_magic |
|
|||
276 | def who_ls(self, parameter_s=''): |
|
|||
277 | """Return a sorted list of all interactive variables. |
|
|||
278 |
|
||||
279 | If arguments are given, only variables of types matching these |
|
|||
280 | arguments are returned. |
|
|||
281 |
|
||||
282 | Examples |
|
|||
283 | -------- |
|
|||
284 |
|
||||
285 | Define two variables and list them with who_ls:: |
|
|||
286 |
|
||||
287 | In [1]: alpha = 123 |
|
|||
288 |
|
||||
289 | In [2]: beta = 'test' |
|
|||
290 |
|
||||
291 | In [3]: %who_ls |
|
|||
292 | Out[3]: ['alpha', 'beta'] |
|
|||
293 |
|
||||
294 | In [4]: %who_ls int |
|
|||
295 | Out[4]: ['alpha'] |
|
|||
296 |
|
||||
297 | In [5]: %who_ls str |
|
|||
298 | Out[5]: ['beta'] |
|
|||
299 | """ |
|
|||
300 |
|
||||
301 | user_ns = self.shell.user_ns |
|
|||
302 | user_ns_hidden = self.shell.user_ns_hidden |
|
|||
303 | out = [ i for i in user_ns |
|
|||
304 | if not i.startswith('_') \ |
|
|||
305 | and not i in user_ns_hidden ] |
|
|||
306 |
|
||||
307 | typelist = parameter_s.split() |
|
|||
308 | if typelist: |
|
|||
309 | typeset = set(typelist) |
|
|||
310 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
|||
311 |
|
||||
312 | out.sort() |
|
|||
313 | return out |
|
|||
314 |
|
||||
315 | @skip_doctest |
|
|||
316 | @line_magic |
|
|||
317 | def who(self, parameter_s=''): |
|
|||
318 | """Print all interactive variables, with some minimal formatting. |
|
|||
319 |
|
||||
320 | If any arguments are given, only variables whose type matches one of |
|
|||
321 | these are printed. For example:: |
|
|||
322 |
|
||||
323 | %who function str |
|
|||
324 |
|
||||
325 | will only list functions and strings, excluding all other types of |
|
|||
326 | variables. To find the proper type names, simply use type(var) at a |
|
|||
327 | command line to see how python prints type names. For example: |
|
|||
328 |
|
||||
329 | :: |
|
|||
330 |
|
||||
331 | In [1]: type('hello')\\ |
|
|||
332 | Out[1]: <type 'str'> |
|
|||
333 |
|
||||
334 | indicates that the type name for strings is 'str'. |
|
|||
335 |
|
||||
336 | ``%who`` always excludes executed names loaded through your configuration |
|
|||
337 | file and things which are internal to IPython. |
|
|||
338 |
|
||||
339 | This is deliberate, as typically you may load many modules and the |
|
|||
340 | purpose of %who is to show you only what you've manually defined. |
|
|||
341 |
|
||||
342 | Examples |
|
|||
343 | -------- |
|
|||
344 |
|
||||
345 | Define two variables and list them with who:: |
|
|||
346 |
|
||||
347 | In [1]: alpha = 123 |
|
|||
348 |
|
||||
349 | In [2]: beta = 'test' |
|
|||
350 |
|
||||
351 | In [3]: %who |
|
|||
352 | alpha beta |
|
|||
353 |
|
||||
354 | In [4]: %who int |
|
|||
355 | alpha |
|
|||
356 |
|
||||
357 | In [5]: %who str |
|
|||
358 | beta |
|
|||
359 | """ |
|
|||
360 |
|
||||
361 | varlist = self.who_ls(parameter_s) |
|
|||
362 | if not varlist: |
|
|||
363 | if parameter_s: |
|
|||
364 | print 'No variables match your requested type.' |
|
|||
365 | else: |
|
|||
366 | print 'Interactive namespace is empty.' |
|
|||
367 | return |
|
|||
368 |
|
||||
369 | # if we have variables, move on... |
|
|||
370 | count = 0 |
|
|||
371 | for i in varlist: |
|
|||
372 | print i+'\t', |
|
|||
373 | count += 1 |
|
|||
374 | if count > 8: |
|
|||
375 | count = 0 |
|
|||
376 |
|
||||
377 |
|
||||
378 |
|
||||
379 | @skip_doctest |
|
|||
380 | @line_magic |
|
|||
381 | def whos(self, parameter_s=''): |
|
|||
382 | """Like %who, but gives some extra information about each variable. |
|
|||
383 |
|
||||
384 | The same type filtering of %who can be applied here. |
|
|||
385 |
|
||||
386 | For all variables, the type is printed. Additionally it prints: |
|
|||
387 |
|
||||
388 | - For {},[],(): their length. |
|
|||
389 |
|
||||
390 | - For numpy arrays, a summary with shape, number of |
|
|||
391 | elements, typecode and size in memory. |
|
|||
392 |
|
||||
393 | - Everything else: a string representation, snipping their middle if |
|
|||
394 | too long. |
|
|||
395 |
|
||||
396 | Examples |
|
|||
397 | -------- |
|
|||
398 |
|
||||
399 | Define two variables and list them with whos:: |
|
|||
400 |
|
||||
401 | In [1]: alpha = 123 |
|
|||
402 |
|
||||
403 | In [2]: beta = 'test' |
|
|||
404 |
|
||||
405 | In [3]: %whos |
|
|||
406 | Variable Type Data/Info |
|
|||
407 | -------------------------------- |
|
|||
408 | alpha int 123 |
|
|||
409 | beta str test |
|
|||
410 | """ |
|
|||
411 |
|
||||
412 | varnames = self.who_ls(parameter_s) |
|
|||
413 | if not varnames: |
|
|||
414 | if parameter_s: |
|
|||
415 | print 'No variables match your requested type.' |
|
|||
416 | else: |
|
|||
417 | print 'Interactive namespace is empty.' |
|
|||
418 | return |
|
|||
419 |
|
||||
420 | # if we have variables, move on... |
|
|||
421 |
|
||||
422 | # for these types, show len() instead of data: |
|
|||
423 | seq_types = ['dict', 'list', 'tuple'] |
|
|||
424 |
|
||||
425 | # for numpy arrays, display summary info |
|
|||
426 | ndarray_type = None |
|
|||
427 | if 'numpy' in sys.modules: |
|
|||
428 | try: |
|
|||
429 | from numpy import ndarray |
|
|||
430 | except ImportError: |
|
|||
431 | pass |
|
|||
432 | else: |
|
|||
433 | ndarray_type = ndarray.__name__ |
|
|||
434 |
|
||||
435 | # Find all variable names and types so we can figure out column sizes |
|
|||
436 | def get_vars(i): |
|
|||
437 | return self.shell.user_ns[i] |
|
|||
438 |
|
||||
439 | # some types are well known and can be shorter |
|
|||
440 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
|||
441 | def type_name(v): |
|
|||
442 | tn = type(v).__name__ |
|
|||
443 | return abbrevs.get(tn,tn) |
|
|||
444 |
|
||||
445 | varlist = map(get_vars,varnames) |
|
|||
446 |
|
||||
447 | typelist = [] |
|
|||
448 | for vv in varlist: |
|
|||
449 | tt = type_name(vv) |
|
|||
450 |
|
||||
451 | if tt=='instance': |
|
|||
452 | typelist.append( abbrevs.get(str(vv.__class__), |
|
|||
453 | str(vv.__class__))) |
|
|||
454 | else: |
|
|||
455 | typelist.append(tt) |
|
|||
456 |
|
||||
457 | # column labels and # of spaces as separator |
|
|||
458 | varlabel = 'Variable' |
|
|||
459 | typelabel = 'Type' |
|
|||
460 | datalabel = 'Data/Info' |
|
|||
461 | colsep = 3 |
|
|||
462 | # variable format strings |
|
|||
463 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
|||
464 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
|||
465 | # find the size of the columns to format the output nicely |
|
|||
466 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
|||
467 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
|||
468 | # table header |
|
|||
469 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
|||
470 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
|||
471 | # and the table itself |
|
|||
472 | kb = 1024 |
|
|||
473 | Mb = 1048576 # kb**2 |
|
|||
474 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
|||
475 | print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), |
|
|||
476 | if vtype in seq_types: |
|
|||
477 | print "n="+str(len(var)) |
|
|||
478 | elif vtype == ndarray_type: |
|
|||
479 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
|||
480 | if vtype==ndarray_type: |
|
|||
481 | # numpy |
|
|||
482 | vsize = var.size |
|
|||
483 | vbytes = vsize*var.itemsize |
|
|||
484 | vdtype = var.dtype |
|
|||
485 |
|
||||
486 | if vbytes < 100000: |
|
|||
487 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
|||
488 | else: |
|
|||
489 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
|||
490 | if vbytes < Mb: |
|
|||
491 | print '(%s kb)' % (vbytes/kb,) |
|
|||
492 | else: |
|
|||
493 | print '(%s Mb)' % (vbytes/Mb,) |
|
|||
494 | else: |
|
|||
495 | try: |
|
|||
496 | vstr = str(var) |
|
|||
497 | except UnicodeEncodeError: |
|
|||
498 | vstr = unicode(var).encode(DEFAULT_ENCODING, |
|
|||
499 | 'backslashreplace') |
|
|||
500 | except: |
|
|||
501 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
|||
502 | vstr = vstr.replace('\n','\\n') |
|
|||
503 | if len(vstr) < 50: |
|
|||
504 | print vstr |
|
|||
505 | else: |
|
|||
506 | print vstr[:25] + "<...>" + vstr[-25:] |
|
|||
507 |
|
||||
508 | @line_magic |
|
|||
509 | def reset(self, parameter_s=''): |
|
|||
510 | """Resets the namespace by removing all names defined by the user, if |
|
|||
511 | called without arguments, or by removing some types of objects, such |
|
|||
512 | as everything currently in IPython's In[] and Out[] containers (see |
|
|||
513 | the parameters for details). |
|
|||
514 |
|
||||
515 | Parameters |
|
|||
516 | ---------- |
|
|||
517 | -f : force reset without asking for confirmation. |
|
|||
518 |
|
||||
519 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
|||
520 | References to objects may be kept. By default (without this option), |
|
|||
521 | we do a 'hard' reset, giving you a new session and removing all |
|
|||
522 | references to objects from the current session. |
|
|||
523 |
|
||||
524 | in : reset input history |
|
|||
525 |
|
||||
526 | out : reset output history |
|
|||
527 |
|
||||
528 | dhist : reset directory history |
|
|||
529 |
|
||||
530 | array : reset only variables that are NumPy arrays |
|
|||
531 |
|
||||
532 | See Also |
|
|||
533 | -------- |
|
|||
534 | magic_reset_selective : invoked as ``%reset_selective`` |
|
|||
535 |
|
||||
536 | Examples |
|
|||
537 | -------- |
|
|||
538 | :: |
|
|||
539 |
|
||||
540 | In [6]: a = 1 |
|
|||
541 |
|
||||
542 | In [7]: a |
|
|||
543 | Out[7]: 1 |
|
|||
544 |
|
||||
545 | In [8]: 'a' in _ip.user_ns |
|
|||
546 | Out[8]: True |
|
|||
547 |
|
||||
548 | In [9]: %reset -f |
|
|||
549 |
|
||||
550 | In [1]: 'a' in _ip.user_ns |
|
|||
551 | Out[1]: False |
|
|||
552 |
|
||||
553 | In [2]: %reset -f in |
|
|||
554 | Flushing input history |
|
|||
555 |
|
||||
556 | In [3]: %reset -f dhist in |
|
|||
557 | Flushing directory history |
|
|||
558 | Flushing input history |
|
|||
559 |
|
||||
560 | Notes |
|
|||
561 | ----- |
|
|||
562 | Calling this magic from clients that do not implement standard input, |
|
|||
563 | such as the ipython notebook interface, will reset the namespace |
|
|||
564 | without confirmation. |
|
|||
565 | """ |
|
|||
566 | opts, args = self.parse_options(parameter_s,'sf', mode='list') |
|
|||
567 | if 'f' in opts: |
|
|||
568 | ans = True |
|
|||
569 | else: |
|
|||
570 | try: |
|
|||
571 | ans = self.shell.ask_yes_no( |
|
|||
572 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", |
|
|||
573 | default='n') |
|
|||
574 | except StdinNotImplementedError: |
|
|||
575 | ans = True |
|
|||
576 | if not ans: |
|
|||
577 | print 'Nothing done.' |
|
|||
578 | return |
|
|||
579 |
|
||||
580 | if 's' in opts: # Soft reset |
|
|||
581 | user_ns = self.shell.user_ns |
|
|||
582 | for i in self.who_ls(): |
|
|||
583 | del(user_ns[i]) |
|
|||
584 | elif len(args) == 0: # Hard reset |
|
|||
585 | self.shell.reset(new_session = False) |
|
|||
586 |
|
||||
587 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
|||
588 | ip = self.shell |
|
|||
589 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
|||
590 |
|
||||
591 | for target in args: |
|
|||
592 | target = target.lower() # make matches case insensitive |
|
|||
593 | if target == 'out': |
|
|||
594 | print "Flushing output cache (%d entries)" % len(user_ns['_oh']) |
|
|||
595 | self.shell.displayhook.flush() |
|
|||
596 |
|
||||
597 | elif target == 'in': |
|
|||
598 | print "Flushing input history" |
|
|||
599 | pc = self.shell.displayhook.prompt_count + 1 |
|
|||
600 | for n in range(1, pc): |
|
|||
601 | key = '_i'+repr(n) |
|
|||
602 | user_ns.pop(key,None) |
|
|||
603 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
|||
604 | hm = ip.history_manager |
|
|||
605 | # don't delete these, as %save and %macro depending on the |
|
|||
606 | # length of these lists to be preserved |
|
|||
607 | hm.input_hist_parsed[:] = [''] * pc |
|
|||
608 | hm.input_hist_raw[:] = [''] * pc |
|
|||
609 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
|||
610 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
|||
611 |
|
||||
612 | elif target == 'array': |
|
|||
613 | # Support cleaning up numpy arrays |
|
|||
614 | try: |
|
|||
615 | from numpy import ndarray |
|
|||
616 | # This must be done with items and not iteritems because |
|
|||
617 | # we're going to modify the dict in-place. |
|
|||
618 | for x,val in user_ns.items(): |
|
|||
619 | if isinstance(val,ndarray): |
|
|||
620 | del user_ns[x] |
|
|||
621 | except ImportError: |
|
|||
622 | print "reset array only works if Numpy is available." |
|
|||
623 |
|
||||
624 | elif target == 'dhist': |
|
|||
625 | print "Flushing directory history" |
|
|||
626 | del user_ns['_dh'][:] |
|
|||
627 |
|
||||
628 | else: |
|
|||
629 | print "Don't know how to reset ", |
|
|||
630 | print target + ", please run `%reset?` for details" |
|
|||
631 |
|
||||
632 | gc.collect() |
|
|||
633 |
|
||||
634 | @line_magic |
|
|||
635 | def reset_selective(self, parameter_s=''): |
|
|||
636 | """Resets the namespace by removing names defined by the user. |
|
|||
637 |
|
||||
638 | Input/Output history are left around in case you need them. |
|
|||
639 |
|
||||
640 | %reset_selective [-f] regex |
|
|||
641 |
|
||||
642 | No action is taken if regex is not included |
|
|||
643 |
|
||||
644 | Options |
|
|||
645 | -f : force reset without asking for confirmation. |
|
|||
646 |
|
||||
647 | See Also |
|
|||
648 | -------- |
|
|||
649 | magic_reset : invoked as ``%reset`` |
|
|||
650 |
|
||||
651 | Examples |
|
|||
652 | -------- |
|
|||
653 |
|
||||
654 | We first fully reset the namespace so your output looks identical to |
|
|||
655 | this example for pedagogical reasons; in practice you do not need a |
|
|||
656 | full reset:: |
|
|||
657 |
|
||||
658 | In [1]: %reset -f |
|
|||
659 |
|
||||
660 | Now, with a clean namespace we can make a few variables and use |
|
|||
661 | ``%reset_selective`` to only delete names that match our regexp:: |
|
|||
662 |
|
||||
663 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
|||
664 |
|
||||
665 | In [3]: who_ls |
|
|||
666 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
|||
667 |
|
||||
668 | In [4]: %reset_selective -f b[2-3]m |
|
|||
669 |
|
||||
670 | In [5]: who_ls |
|
|||
671 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
|||
672 |
|
||||
673 | In [6]: %reset_selective -f d |
|
|||
674 |
|
||||
675 | In [7]: who_ls |
|
|||
676 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
|||
677 |
|
||||
678 | In [8]: %reset_selective -f c |
|
|||
679 |
|
||||
680 | In [9]: who_ls |
|
|||
681 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
|||
682 |
|
||||
683 | In [10]: %reset_selective -f b |
|
|||
684 |
|
||||
685 | In [11]: who_ls |
|
|||
686 | Out[11]: ['a'] |
|
|||
687 |
|
||||
688 | Notes |
|
|||
689 | ----- |
|
|||
690 | Calling this magic from clients that do not implement standard input, |
|
|||
691 | such as the ipython notebook interface, will reset the namespace |
|
|||
692 | without confirmation. |
|
|||
693 | """ |
|
|||
694 |
|
||||
695 | opts, regex = self.parse_options(parameter_s,'f') |
|
|||
696 |
|
||||
697 | if opts.has_key('f'): |
|
|||
698 | ans = True |
|
|||
699 | else: |
|
|||
700 | try: |
|
|||
701 | ans = self.shell.ask_yes_no( |
|
|||
702 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
|||
703 | default='n') |
|
|||
704 | except StdinNotImplementedError: |
|
|||
705 | ans = True |
|
|||
706 | if not ans: |
|
|||
707 | print 'Nothing done.' |
|
|||
708 | return |
|
|||
709 | user_ns = self.shell.user_ns |
|
|||
710 | if not regex: |
|
|||
711 | print 'No regex pattern specified. Nothing done.' |
|
|||
712 | return |
|
|||
713 | else: |
|
|||
714 | try: |
|
|||
715 | m = re.compile(regex) |
|
|||
716 | except TypeError: |
|
|||
717 | raise TypeError('regex must be a string or compiled pattern') |
|
|||
718 | for i in self.who_ls(): |
|
|||
719 | if m.search(i): |
|
|||
720 | del(user_ns[i]) |
|
|||
721 |
|
||||
722 | @line_magic |
|
|||
723 | def xdel(self, parameter_s=''): |
|
|||
724 | """Delete a variable, trying to clear it from anywhere that |
|
|||
725 | IPython's machinery has references to it. By default, this uses |
|
|||
726 | the identity of the named object in the user namespace to remove |
|
|||
727 | references held under other names. The object is also removed |
|
|||
728 | from the output history. |
|
|||
729 |
|
||||
730 | Options |
|
|||
731 | -n : Delete the specified name from all namespaces, without |
|
|||
732 | checking their identity. |
|
|||
733 | """ |
|
|||
734 | opts, varname = self.parse_options(parameter_s,'n') |
|
|||
735 | try: |
|
|||
736 | self.shell.del_var(varname, ('n' in opts)) |
|
|||
737 | except (NameError, ValueError) as e: |
|
|||
738 | print type(e).__name__ +": "+ str(e) |
|
|||
739 |
|
||||
740 |
|
68 | |||
741 | @register_magics |
|
69 | @register_magics | |
742 | class ExecutionMagics(Magics): |
|
70 | class ExecutionMagics(Magics): |
@@ -17,6 +17,7 b' from .basic import BasicMagics' | |||||
17 | from .code import CodeMagics, MacroToEdit |
|
17 | from .code import CodeMagics, MacroToEdit | |
18 | from .config import ConfigMagics |
|
18 | from .config import ConfigMagics | |
19 | from .history import HistoryMagics |
|
19 | from .history import HistoryMagics | |
|
20 | from .namespace import NamespaceMagics | |||
20 |
|
21 | |||
21 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
22 | # Magic implementation classes |
|
23 | # Magic implementation classes |
General Comments 0
You need to be logged in to leave comments.
Login now