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