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