Show More
The requested changes are too big and content was truncated. Show full diff
|
1 | NO CONTENT: modified file | |
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,708 +1,712 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 | # default namespaces to be searched |
|
212 | 212 | def_search = ['user_local', 'user_global', 'builtin'] |
|
213 | 213 | |
|
214 | 214 | # Process options/args |
|
215 | 215 | opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True) |
|
216 | 216 | opt = opts.get |
|
217 | 217 | shell = self.shell |
|
218 | 218 | psearch = shell.inspector.psearch |
|
219 | 219 | |
|
220 | 220 | # select list object types |
|
221 | 221 | list_types = False |
|
222 | 222 | if 'l' in opts: |
|
223 | 223 | list_types = True |
|
224 | 224 | |
|
225 | 225 | # select case options |
|
226 | 226 | if 'i' in opts: |
|
227 | 227 | ignore_case = True |
|
228 | 228 | elif 'c' in opts: |
|
229 | 229 | ignore_case = False |
|
230 | 230 | else: |
|
231 | 231 | ignore_case = not shell.wildcards_case_sensitive |
|
232 | 232 | |
|
233 | 233 | # Build list of namespaces to search from user options |
|
234 | 234 | def_search.extend(opt('s',[])) |
|
235 | 235 | ns_exclude = ns_exclude=opt('e',[]) |
|
236 | 236 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
237 | 237 | |
|
238 | 238 | # Call the actual search |
|
239 | 239 | try: |
|
240 | 240 | psearch(args,shell.ns_table,ns_search, |
|
241 | 241 | show_all=opt('a'),ignore_case=ignore_case, list_types=list_types) |
|
242 | 242 | except: |
|
243 | 243 | shell.showtraceback() |
|
244 | 244 | |
|
245 | 245 | @skip_doctest |
|
246 | 246 | @line_magic |
|
247 | 247 | def who_ls(self, parameter_s=''): |
|
248 | 248 | """Return a sorted list of all interactive variables. |
|
249 | 249 | |
|
250 | 250 | If arguments are given, only variables of types matching these |
|
251 | 251 | arguments are returned. |
|
252 | 252 | |
|
253 | 253 | Examples |
|
254 | 254 | -------- |
|
255 | 255 | |
|
256 | 256 | Define two variables and list them with who_ls:: |
|
257 | 257 | |
|
258 | 258 | In [1]: alpha = 123 |
|
259 | 259 | |
|
260 | 260 | In [2]: beta = 'test' |
|
261 | 261 | |
|
262 | 262 | In [3]: %who_ls |
|
263 | 263 | Out[3]: ['alpha', 'beta'] |
|
264 | 264 | |
|
265 | 265 | In [4]: %who_ls int |
|
266 | 266 | Out[4]: ['alpha'] |
|
267 | 267 | |
|
268 | 268 | In [5]: %who_ls str |
|
269 | 269 | Out[5]: ['beta'] |
|
270 | 270 | """ |
|
271 | 271 | |
|
272 | 272 | user_ns = self.shell.user_ns |
|
273 | 273 | user_ns_hidden = self.shell.user_ns_hidden |
|
274 | 274 | nonmatching = object() # This can never be in user_ns |
|
275 | 275 | out = [ i for i in user_ns |
|
276 | 276 | if not i.startswith('_') \ |
|
277 | 277 | and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ] |
|
278 | 278 | |
|
279 | 279 | typelist = parameter_s.split() |
|
280 | 280 | if typelist: |
|
281 | 281 | typeset = set(typelist) |
|
282 | 282 | out = [i for i in out if type(user_ns[i]).__name__ in typeset] |
|
283 | 283 | |
|
284 | 284 | out.sort() |
|
285 | 285 | return out |
|
286 | 286 | |
|
287 | 287 | @skip_doctest |
|
288 | 288 | @line_magic |
|
289 | 289 | def who(self, parameter_s=''): |
|
290 | 290 | """Print all interactive variables, with some minimal formatting. |
|
291 | 291 | |
|
292 | 292 | If any arguments are given, only variables whose type matches one of |
|
293 | 293 | these are printed. For example:: |
|
294 | 294 | |
|
295 | 295 | %who function str |
|
296 | 296 | |
|
297 | 297 | will only list functions and strings, excluding all other types of |
|
298 | 298 | variables. To find the proper type names, simply use type(var) at a |
|
299 | 299 | command line to see how python prints type names. For example: |
|
300 | 300 | |
|
301 | 301 | :: |
|
302 | 302 | |
|
303 | 303 | In [1]: type('hello')\\ |
|
304 | 304 | Out[1]: <type 'str'> |
|
305 | 305 | |
|
306 | 306 | indicates that the type name for strings is 'str'. |
|
307 | 307 | |
|
308 | 308 | ``%who`` always excludes executed names loaded through your configuration |
|
309 | 309 | file and things which are internal to IPython. |
|
310 | 310 | |
|
311 | 311 | This is deliberate, as typically you may load many modules and the |
|
312 | 312 | purpose of %who is to show you only what you've manually defined. |
|
313 | 313 | |
|
314 | 314 | Examples |
|
315 | 315 | -------- |
|
316 | 316 | |
|
317 | 317 | Define two variables and list them with who:: |
|
318 | 318 | |
|
319 | 319 | In [1]: alpha = 123 |
|
320 | 320 | |
|
321 | 321 | In [2]: beta = 'test' |
|
322 | 322 | |
|
323 | 323 | In [3]: %who |
|
324 | 324 | alpha beta |
|
325 | 325 | |
|
326 | 326 | In [4]: %who int |
|
327 | 327 | alpha |
|
328 | 328 | |
|
329 | 329 | In [5]: %who str |
|
330 | 330 | beta |
|
331 | 331 | """ |
|
332 | 332 | |
|
333 | 333 | varlist = self.who_ls(parameter_s) |
|
334 | 334 | if not varlist: |
|
335 | 335 | if parameter_s: |
|
336 | 336 | print('No variables match your requested type.') |
|
337 | 337 | else: |
|
338 | 338 | print('Interactive namespace is empty.') |
|
339 | 339 | return |
|
340 | 340 | |
|
341 | 341 | # if we have variables, move on... |
|
342 | 342 | count = 0 |
|
343 | 343 | for i in varlist: |
|
344 | 344 | print(i+'\t', end=' ') |
|
345 | 345 | count += 1 |
|
346 | 346 | if count > 8: |
|
347 | 347 | count = 0 |
|
348 | 348 | print() |
|
349 | 349 | print() |
|
350 | 350 | |
|
351 | 351 | @skip_doctest |
|
352 | 352 | @line_magic |
|
353 | 353 | def whos(self, parameter_s=''): |
|
354 | 354 | """Like %who, but gives some extra information about each variable. |
|
355 | 355 | |
|
356 | 356 | The same type filtering of %who can be applied here. |
|
357 | 357 | |
|
358 | 358 | For all variables, the type is printed. Additionally it prints: |
|
359 | 359 | |
|
360 | 360 | - For {},[],(): their length. |
|
361 | 361 | |
|
362 | 362 | - For numpy arrays, a summary with shape, number of |
|
363 | 363 | elements, typecode and size in memory. |
|
364 | 364 | |
|
365 | 365 | - Everything else: a string representation, snipping their middle if |
|
366 | 366 | too long. |
|
367 | 367 | |
|
368 | 368 | Examples |
|
369 | 369 | -------- |
|
370 | 370 | |
|
371 | 371 | Define two variables and list them with whos:: |
|
372 | 372 | |
|
373 | 373 | In [1]: alpha = 123 |
|
374 | 374 | |
|
375 | 375 | In [2]: beta = 'test' |
|
376 | 376 | |
|
377 | 377 | In [3]: %whos |
|
378 | 378 | Variable Type Data/Info |
|
379 | 379 | -------------------------------- |
|
380 | 380 | alpha int 123 |
|
381 | 381 | beta str test |
|
382 | 382 | """ |
|
383 | 383 | |
|
384 | 384 | varnames = self.who_ls(parameter_s) |
|
385 | 385 | if not varnames: |
|
386 | 386 | if parameter_s: |
|
387 | 387 | print('No variables match your requested type.') |
|
388 | 388 | else: |
|
389 | 389 | print('Interactive namespace is empty.') |
|
390 | 390 | return |
|
391 | 391 | |
|
392 | 392 | # if we have variables, move on... |
|
393 | 393 | |
|
394 | 394 | # for these types, show len() instead of data: |
|
395 | 395 | seq_types = ['dict', 'list', 'tuple'] |
|
396 | 396 | |
|
397 | 397 | # for numpy arrays, display summary info |
|
398 | 398 | ndarray_type = None |
|
399 | 399 | if 'numpy' in sys.modules: |
|
400 | 400 | try: |
|
401 | 401 | from numpy import ndarray |
|
402 | 402 | except ImportError: |
|
403 | 403 | pass |
|
404 | 404 | else: |
|
405 | 405 | ndarray_type = ndarray.__name__ |
|
406 | 406 | |
|
407 | 407 | # Find all variable names and types so we can figure out column sizes |
|
408 | 408 | |
|
409 | 409 | # some types are well known and can be shorter |
|
410 | 410 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
411 | 411 | def type_name(v): |
|
412 | 412 | tn = type(v).__name__ |
|
413 | 413 | return abbrevs.get(tn,tn) |
|
414 | 414 | |
|
415 | 415 | varlist = [self.shell.user_ns[n] for n in varnames] |
|
416 | 416 | |
|
417 | 417 | typelist = [] |
|
418 | 418 | for vv in varlist: |
|
419 | 419 | tt = type_name(vv) |
|
420 | 420 | |
|
421 | 421 | if tt=='instance': |
|
422 | 422 | typelist.append( abbrevs.get(str(vv.__class__), |
|
423 | 423 | str(vv.__class__))) |
|
424 | 424 | else: |
|
425 | 425 | typelist.append(tt) |
|
426 | 426 | |
|
427 | 427 | # column labels and # of spaces as separator |
|
428 | 428 | varlabel = 'Variable' |
|
429 | 429 | typelabel = 'Type' |
|
430 | 430 | datalabel = 'Data/Info' |
|
431 | 431 | colsep = 3 |
|
432 | 432 | # variable format strings |
|
433 | 433 | vformat = "{0:<{varwidth}}{1:<{typewidth}}" |
|
434 | 434 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
435 | 435 | # find the size of the columns to format the output nicely |
|
436 | 436 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
437 | 437 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
438 | 438 | # table header |
|
439 | 439 | print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
440 | 440 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)) |
|
441 | 441 | # and the table itself |
|
442 | 442 | kb = 1024 |
|
443 | 443 | Mb = 1048576 # kb**2 |
|
444 | 444 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
445 | 445 | print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ') |
|
446 | 446 | if vtype in seq_types: |
|
447 | 447 | print("n="+str(len(var))) |
|
448 | 448 | elif vtype == ndarray_type: |
|
449 | 449 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
450 | 450 | if vtype==ndarray_type: |
|
451 | 451 | # numpy |
|
452 | 452 | vsize = var.size |
|
453 | 453 | vbytes = vsize*var.itemsize |
|
454 | 454 | vdtype = var.dtype |
|
455 | 455 | |
|
456 | 456 | if vbytes < 100000: |
|
457 | 457 | print(aformat % (vshape, vsize, vdtype, vbytes)) |
|
458 | 458 | else: |
|
459 | 459 | print(aformat % (vshape, vsize, vdtype, vbytes), end=' ') |
|
460 | 460 | if vbytes < Mb: |
|
461 | 461 | print('(%s kb)' % (vbytes/kb,)) |
|
462 | 462 | else: |
|
463 | 463 | print('(%s Mb)' % (vbytes/Mb,)) |
|
464 | 464 | else: |
|
465 | 465 | try: |
|
466 | 466 | vstr = str(var) |
|
467 | 467 | except UnicodeEncodeError: |
|
468 | 468 | vstr = var.encode(DEFAULT_ENCODING, |
|
469 | 469 | 'backslashreplace') |
|
470 | 470 | except: |
|
471 | 471 | vstr = "<object with id %d (str() failed)>" % id(var) |
|
472 | 472 | vstr = vstr.replace('\n', '\\n') |
|
473 | 473 | if len(vstr) < 50: |
|
474 | 474 | print(vstr) |
|
475 | 475 | else: |
|
476 | 476 | print(vstr[:25] + "<...>" + vstr[-25:]) |
|
477 | 477 | |
|
478 | 478 | @line_magic |
|
479 | 479 | def reset(self, parameter_s=''): |
|
480 | 480 | """Resets the namespace by removing all names defined by the user, if |
|
481 | 481 | called without arguments, or by removing some types of objects, such |
|
482 | 482 | as everything currently in IPython's In[] and Out[] containers (see |
|
483 | 483 | the parameters for details). |
|
484 | 484 | |
|
485 | 485 | Parameters |
|
486 | 486 | ---------- |
|
487 | 487 | -f : force reset without asking for confirmation. |
|
488 | 488 | |
|
489 | 489 | -s : 'Soft' reset: Only clears your namespace, leaving history intact. |
|
490 | 490 | References to objects may be kept. By default (without this option), |
|
491 | 491 | we do a 'hard' reset, giving you a new session and removing all |
|
492 | 492 | references to objects from the current session. |
|
493 | 493 | |
|
494 | --aggressive: Try to aggressively remove modules from sys.modules ; this | |
|
495 | may allow you to reimport Python modules that have been updated and | |
|
496 | pick up changes, but can have unattended consequences. | |
|
497 | ||
|
494 | 498 | in : reset input history |
|
495 | 499 | |
|
496 | 500 | out : reset output history |
|
497 | 501 | |
|
498 | 502 | dhist : reset directory history |
|
499 | 503 | |
|
500 | 504 | array : reset only variables that are NumPy arrays |
|
501 | 505 | |
|
502 | 506 | See Also |
|
503 | 507 | -------- |
|
504 | 508 | reset_selective : invoked as ``%reset_selective`` |
|
505 | 509 | |
|
506 | 510 | Examples |
|
507 | 511 | -------- |
|
508 | 512 | :: |
|
509 | 513 | |
|
510 | 514 | In [6]: a = 1 |
|
511 | 515 | |
|
512 | 516 | In [7]: a |
|
513 | 517 | Out[7]: 1 |
|
514 | 518 | |
|
515 | 519 | In [8]: 'a' in get_ipython().user_ns |
|
516 | 520 | Out[8]: True |
|
517 | 521 | |
|
518 | 522 | In [9]: %reset -f |
|
519 | 523 | |
|
520 | 524 | In [1]: 'a' in get_ipython().user_ns |
|
521 | 525 | Out[1]: False |
|
522 | 526 | |
|
523 | 527 | In [2]: %reset -f in |
|
524 | 528 | Flushing input history |
|
525 | 529 | |
|
526 | 530 | In [3]: %reset -f dhist in |
|
527 | 531 | Flushing directory history |
|
528 | 532 | Flushing input history |
|
529 | 533 | |
|
530 | 534 | Notes |
|
531 | 535 | ----- |
|
532 | 536 | Calling this magic from clients that do not implement standard input, |
|
533 | 537 | such as the ipython notebook interface, will reset the namespace |
|
534 | 538 | without confirmation. |
|
535 | 539 | """ |
|
536 |
opts, args = self.parse_options(parameter_s, |
|
|
537 |
if |
|
|
540 | opts, args = self.parse_options(parameter_s, "sf", "aggressive", mode="list") | |
|
541 | if "f" in opts: | |
|
538 | 542 | ans = True |
|
539 | 543 | else: |
|
540 | 544 | try: |
|
541 | 545 | ans = self.shell.ask_yes_no( |
|
542 | 546 | "Once deleted, variables cannot be recovered. Proceed (y/[n])?", |
|
543 | 547 | default='n') |
|
544 | 548 | except StdinNotImplementedError: |
|
545 | 549 | ans = True |
|
546 | 550 | if not ans: |
|
547 | 551 | print('Nothing done.') |
|
548 | 552 | return |
|
549 | 553 | |
|
550 | 554 | if 's' in opts: # Soft reset |
|
551 | 555 | user_ns = self.shell.user_ns |
|
552 | 556 | for i in self.who_ls(): |
|
553 | 557 | del(user_ns[i]) |
|
554 | 558 | elif len(args) == 0: # Hard reset |
|
555 |
self.shell.reset(new_session = |
|
|
559 | self.shell.reset(new_session=False, aggressive=("aggressive" in opts)) | |
|
556 | 560 | |
|
557 | 561 | # reset in/out/dhist/array: previously extensinions/clearcmd.py |
|
558 | 562 | ip = self.shell |
|
559 | 563 | user_ns = self.shell.user_ns # local lookup, heavily used |
|
560 | 564 | |
|
561 | 565 | for target in args: |
|
562 | 566 | target = target.lower() # make matches case insensitive |
|
563 | 567 | if target == 'out': |
|
564 | 568 | print("Flushing output cache (%d entries)" % len(user_ns['_oh'])) |
|
565 | 569 | self.shell.displayhook.flush() |
|
566 | 570 | |
|
567 | 571 | elif target == 'in': |
|
568 | 572 | print("Flushing input history") |
|
569 | 573 | pc = self.shell.displayhook.prompt_count + 1 |
|
570 | 574 | for n in range(1, pc): |
|
571 | 575 | key = '_i'+repr(n) |
|
572 | 576 | user_ns.pop(key,None) |
|
573 | 577 | user_ns.update(dict(_i=u'',_ii=u'',_iii=u'')) |
|
574 | 578 | hm = ip.history_manager |
|
575 | 579 | # don't delete these, as %save and %macro depending on the |
|
576 | 580 | # length of these lists to be preserved |
|
577 | 581 | hm.input_hist_parsed[:] = [''] * pc |
|
578 | 582 | hm.input_hist_raw[:] = [''] * pc |
|
579 | 583 | # hm has internal machinery for _i,_ii,_iii, clear it out |
|
580 | 584 | hm._i = hm._ii = hm._iii = hm._i00 = u'' |
|
581 | 585 | |
|
582 | 586 | elif target == 'array': |
|
583 | 587 | # Support cleaning up numpy arrays |
|
584 | 588 | try: |
|
585 | 589 | from numpy import ndarray |
|
586 | 590 | # This must be done with items and not iteritems because |
|
587 | 591 | # we're going to modify the dict in-place. |
|
588 | 592 | for x,val in list(user_ns.items()): |
|
589 | 593 | if isinstance(val,ndarray): |
|
590 | 594 | del user_ns[x] |
|
591 | 595 | except ImportError: |
|
592 | 596 | print("reset array only works if Numpy is available.") |
|
593 | 597 | |
|
594 | 598 | elif target == 'dhist': |
|
595 | 599 | print("Flushing directory history") |
|
596 | 600 | del user_ns['_dh'][:] |
|
597 | 601 | |
|
598 | 602 | else: |
|
599 | 603 | print("Don't know how to reset ", end=' ') |
|
600 | 604 | print(target + ", please run `%reset?` for details") |
|
601 | 605 | |
|
602 | 606 | gc.collect() |
|
603 | 607 | |
|
604 | 608 | @line_magic |
|
605 | 609 | def reset_selective(self, parameter_s=''): |
|
606 | 610 | """Resets the namespace by removing names defined by the user. |
|
607 | 611 | |
|
608 | 612 | Input/Output history are left around in case you need them. |
|
609 | 613 | |
|
610 | 614 | %reset_selective [-f] regex |
|
611 | 615 | |
|
612 | 616 | No action is taken if regex is not included |
|
613 | 617 | |
|
614 | 618 | Options |
|
615 | 619 | -f : force reset without asking for confirmation. |
|
616 | 620 | |
|
617 | 621 | See Also |
|
618 | 622 | -------- |
|
619 | 623 | reset : invoked as ``%reset`` |
|
620 | 624 | |
|
621 | 625 | Examples |
|
622 | 626 | -------- |
|
623 | 627 | |
|
624 | 628 | We first fully reset the namespace so your output looks identical to |
|
625 | 629 | this example for pedagogical reasons; in practice you do not need a |
|
626 | 630 | full reset:: |
|
627 | 631 | |
|
628 | 632 | In [1]: %reset -f |
|
629 | 633 | |
|
630 | 634 | Now, with a clean namespace we can make a few variables and use |
|
631 | 635 | ``%reset_selective`` to only delete names that match our regexp:: |
|
632 | 636 | |
|
633 | 637 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
634 | 638 | |
|
635 | 639 | In [3]: who_ls |
|
636 | 640 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
637 | 641 | |
|
638 | 642 | In [4]: %reset_selective -f b[2-3]m |
|
639 | 643 | |
|
640 | 644 | In [5]: who_ls |
|
641 | 645 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
642 | 646 | |
|
643 | 647 | In [6]: %reset_selective -f d |
|
644 | 648 | |
|
645 | 649 | In [7]: who_ls |
|
646 | 650 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
647 | 651 | |
|
648 | 652 | In [8]: %reset_selective -f c |
|
649 | 653 | |
|
650 | 654 | In [9]: who_ls |
|
651 | 655 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
652 | 656 | |
|
653 | 657 | In [10]: %reset_selective -f b |
|
654 | 658 | |
|
655 | 659 | In [11]: who_ls |
|
656 | 660 | Out[11]: ['a'] |
|
657 | 661 | |
|
658 | 662 | Notes |
|
659 | 663 | ----- |
|
660 | 664 | Calling this magic from clients that do not implement standard input, |
|
661 | 665 | such as the ipython notebook interface, will reset the namespace |
|
662 | 666 | without confirmation. |
|
663 | 667 | """ |
|
664 | 668 | |
|
665 | 669 | opts, regex = self.parse_options(parameter_s,'f') |
|
666 | 670 | |
|
667 | 671 | if 'f' in opts: |
|
668 | 672 | ans = True |
|
669 | 673 | else: |
|
670 | 674 | try: |
|
671 | 675 | ans = self.shell.ask_yes_no( |
|
672 | 676 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", |
|
673 | 677 | default='n') |
|
674 | 678 | except StdinNotImplementedError: |
|
675 | 679 | ans = True |
|
676 | 680 | if not ans: |
|
677 | 681 | print('Nothing done.') |
|
678 | 682 | return |
|
679 | 683 | user_ns = self.shell.user_ns |
|
680 | 684 | if not regex: |
|
681 | 685 | print('No regex pattern specified. Nothing done.') |
|
682 | 686 | return |
|
683 | 687 | else: |
|
684 | 688 | try: |
|
685 | 689 | m = re.compile(regex) |
|
686 | 690 | except TypeError as e: |
|
687 | 691 | raise TypeError('regex must be a string or compiled pattern') from e |
|
688 | 692 | for i in self.who_ls(): |
|
689 | 693 | if m.search(i): |
|
690 | 694 | del(user_ns[i]) |
|
691 | 695 | |
|
692 | 696 | @line_magic |
|
693 | 697 | def xdel(self, parameter_s=''): |
|
694 | 698 | """Delete a variable, trying to clear it from anywhere that |
|
695 | 699 | IPython's machinery has references to it. By default, this uses |
|
696 | 700 | the identity of the named object in the user namespace to remove |
|
697 | 701 | references held under other names. The object is also removed |
|
698 | 702 | from the output history. |
|
699 | 703 | |
|
700 | 704 | Options |
|
701 | 705 | -n : Delete the specified name from all namespaces, without |
|
702 | 706 | checking their identity. |
|
703 | 707 | """ |
|
704 | 708 | opts, varname = self.parse_options(parameter_s,'n') |
|
705 | 709 | try: |
|
706 | 710 | self.shell.del_var(varname, ('n' in opts)) |
|
707 | 711 | except (NameError, ValueError) as e: |
|
708 | 712 | print(type(e).__name__ +": "+ str(e)) |
@@ -1,469 +1,470 b'' | |||
|
1 | 1 | # encoding: utf-8 |
|
2 | 2 | """ |
|
3 | 3 | A mixin for :class:`~IPython.core.application.Application` classes that |
|
4 | 4 | launch InteractiveShell instances, load extensions, etc. |
|
5 | 5 | """ |
|
6 | 6 | |
|
7 | 7 | # Copyright (c) IPython Development Team. |
|
8 | 8 | # Distributed under the terms of the Modified BSD License. |
|
9 | 9 | |
|
10 | 10 | import glob |
|
11 | 11 | from itertools import chain |
|
12 | 12 | import os |
|
13 | 13 | import sys |
|
14 | 14 | |
|
15 | 15 | from traitlets.config.application import boolean_flag |
|
16 | 16 | from traitlets.config.configurable import Configurable |
|
17 | 17 | from traitlets.config.loader import Config |
|
18 | 18 | from IPython.core.application import SYSTEM_CONFIG_DIRS, ENV_CONFIG_DIRS |
|
19 | 19 | from IPython.core import pylabtools |
|
20 | 20 | from IPython.utils.contexts import preserve_keys |
|
21 | 21 | from IPython.utils.path import filefind |
|
22 | 22 | import traitlets |
|
23 | 23 | from traitlets import ( |
|
24 | 24 | Unicode, Instance, List, Bool, CaselessStrEnum, observe, |
|
25 | 25 | DottedObjectName, |
|
26 | 26 | ) |
|
27 | 27 | from IPython.terminal import pt_inputhooks |
|
28 | 28 | |
|
29 | 29 | #----------------------------------------------------------------------------- |
|
30 | 30 | # Aliases and Flags |
|
31 | 31 | #----------------------------------------------------------------------------- |
|
32 | 32 | |
|
33 | 33 | gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases)) |
|
34 | 34 | |
|
35 | 35 | backend_keys = sorted(pylabtools.backends.keys()) |
|
36 | 36 | backend_keys.insert(0, 'auto') |
|
37 | 37 | |
|
38 | 38 | shell_flags = {} |
|
39 | 39 | |
|
40 | 40 | addflag = lambda *args: shell_flags.update(boolean_flag(*args)) |
|
41 | 41 | addflag('autoindent', 'InteractiveShell.autoindent', |
|
42 | 42 | 'Turn on autoindenting.', 'Turn off autoindenting.' |
|
43 | 43 | ) |
|
44 | 44 | addflag('automagic', 'InteractiveShell.automagic', |
|
45 | 45 | """Turn on the auto calling of magic commands. Type %%magic at the |
|
46 | 46 | IPython prompt for more information.""", |
|
47 | 47 | 'Turn off the auto calling of magic commands.' |
|
48 | 48 | ) |
|
49 | 49 | addflag('pdb', 'InteractiveShell.pdb', |
|
50 | 50 | "Enable auto calling the pdb debugger after every exception.", |
|
51 | 51 | "Disable auto calling the pdb debugger after every exception." |
|
52 | 52 | ) |
|
53 | 53 | addflag('pprint', 'PlainTextFormatter.pprint', |
|
54 | 54 | "Enable auto pretty printing of results.", |
|
55 | 55 | "Disable auto pretty printing of results." |
|
56 | 56 | ) |
|
57 | 57 | addflag('color-info', 'InteractiveShell.color_info', |
|
58 | 58 | """IPython can display information about objects via a set of functions, |
|
59 | 59 | and optionally can use colors for this, syntax highlighting |
|
60 | 60 | source code and various other elements. This is on by default, but can cause |
|
61 | 61 | problems with some pagers. If you see such problems, you can disable the |
|
62 | 62 | colours.""", |
|
63 | 63 | "Disable using colors for info related things." |
|
64 | 64 | ) |
|
65 | 65 | addflag('ignore-cwd', 'InteractiveShellApp.ignore_cwd', |
|
66 | 66 | "Exclude the current working directory from sys.path", |
|
67 | 67 | "Include the current working directory in sys.path", |
|
68 | 68 | ) |
|
69 | 69 | nosep_config = Config() |
|
70 | 70 | nosep_config.InteractiveShell.separate_in = '' |
|
71 | 71 | nosep_config.InteractiveShell.separate_out = '' |
|
72 | 72 | nosep_config.InteractiveShell.separate_out2 = '' |
|
73 | 73 | |
|
74 | 74 | shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.") |
|
75 | 75 | shell_flags['pylab'] = ( |
|
76 | 76 | {'InteractiveShellApp' : {'pylab' : 'auto'}}, |
|
77 | 77 | """Pre-load matplotlib and numpy for interactive use with |
|
78 | 78 | the default matplotlib backend.""" |
|
79 | 79 | ) |
|
80 | 80 | shell_flags['matplotlib'] = ( |
|
81 | 81 | {'InteractiveShellApp' : {'matplotlib' : 'auto'}}, |
|
82 | 82 | """Configure matplotlib for interactive use with |
|
83 | 83 | the default matplotlib backend.""" |
|
84 | 84 | ) |
|
85 | 85 | |
|
86 | 86 | # it's possible we don't want short aliases for *all* of these: |
|
87 | 87 | shell_aliases = dict( |
|
88 | 88 | autocall='InteractiveShell.autocall', |
|
89 | 89 | colors='InteractiveShell.colors', |
|
90 | 90 | logfile='InteractiveShell.logfile', |
|
91 | 91 | logappend='InteractiveShell.logappend', |
|
92 | 92 | c='InteractiveShellApp.code_to_run', |
|
93 | 93 | m='InteractiveShellApp.module_to_run', |
|
94 | 94 | ext="InteractiveShellApp.extra_extensions", |
|
95 | 95 | gui='InteractiveShellApp.gui', |
|
96 | 96 | pylab='InteractiveShellApp.pylab', |
|
97 | 97 | matplotlib='InteractiveShellApp.matplotlib', |
|
98 | 98 | ) |
|
99 | 99 | shell_aliases['cache-size'] = 'InteractiveShell.cache_size' |
|
100 | 100 | |
|
101 | 101 | if traitlets.version_info < (5, 0): |
|
102 | 102 | # traitlets 4 doesn't handle lists on CLI |
|
103 | 103 | shell_aliases["ext"] = "InteractiveShellApp.extra_extension" |
|
104 | 104 | |
|
105 | 105 | |
|
106 | 106 | #----------------------------------------------------------------------------- |
|
107 | 107 | # Main classes and functions |
|
108 | 108 | #----------------------------------------------------------------------------- |
|
109 | 109 | |
|
110 | 110 | class InteractiveShellApp(Configurable): |
|
111 | 111 | """A Mixin for applications that start InteractiveShell instances. |
|
112 | 112 | |
|
113 | 113 | Provides configurables for loading extensions and executing files |
|
114 | 114 | as part of configuring a Shell environment. |
|
115 | 115 | |
|
116 | 116 | The following methods should be called by the :meth:`initialize` method |
|
117 | 117 | of the subclass: |
|
118 | 118 | |
|
119 | 119 | - :meth:`init_path` |
|
120 | 120 | - :meth:`init_shell` (to be implemented by the subclass) |
|
121 | 121 | - :meth:`init_gui_pylab` |
|
122 | 122 | - :meth:`init_extensions` |
|
123 | 123 | - :meth:`init_code` |
|
124 | 124 | """ |
|
125 | 125 | extensions = List(Unicode(), |
|
126 | 126 | help="A list of dotted module names of IPython extensions to load." |
|
127 | 127 | ).tag(config=True) |
|
128 | 128 | |
|
129 | 129 | extra_extension = Unicode( |
|
130 | 130 | "", |
|
131 | 131 | help=""" |
|
132 | 132 | DEPRECATED. Dotted module name of a single extra IPython extension to load. |
|
133 | 133 | |
|
134 | 134 | Only one extension can be added this way. |
|
135 | 135 | |
|
136 | 136 | Only used with traitlets < 5.0, plural extra_extensions list is used in traitlets 5. |
|
137 | 137 | """, |
|
138 | 138 | ).tag(config=True) |
|
139 | 139 | |
|
140 | 140 | extra_extensions = List( |
|
141 | 141 | DottedObjectName(), |
|
142 | 142 | help=""" |
|
143 | 143 | Dotted module name(s) of one or more IPython extensions to load. |
|
144 | 144 | |
|
145 | 145 | For specifying extra extensions to load on the command-line. |
|
146 | 146 | |
|
147 | 147 | .. versionadded:: 7.10 |
|
148 | 148 | """, |
|
149 | 149 | ).tag(config=True) |
|
150 | 150 | |
|
151 | 151 | reraise_ipython_extension_failures = Bool(False, |
|
152 | 152 | help="Reraise exceptions encountered loading IPython extensions?", |
|
153 | 153 | ).tag(config=True) |
|
154 | 154 | |
|
155 | 155 | # Extensions that are always loaded (not configurable) |
|
156 | 156 | default_extensions = List(Unicode(), [u'storemagic']).tag(config=False) |
|
157 | 157 | |
|
158 | 158 | hide_initial_ns = Bool(True, |
|
159 | 159 | help="""Should variables loaded at startup (by startup files, exec_lines, etc.) |
|
160 | 160 | be hidden from tools like %who?""" |
|
161 | 161 | ).tag(config=True) |
|
162 | 162 | |
|
163 | 163 | exec_files = List(Unicode(), |
|
164 | 164 | help="""List of files to run at IPython startup.""" |
|
165 | 165 | ).tag(config=True) |
|
166 | 166 | exec_PYTHONSTARTUP = Bool(True, |
|
167 | 167 | help="""Run the file referenced by the PYTHONSTARTUP environment |
|
168 | 168 | variable at IPython startup.""" |
|
169 | 169 | ).tag(config=True) |
|
170 | 170 | file_to_run = Unicode('', |
|
171 | 171 | help="""A file to be run""").tag(config=True) |
|
172 | 172 | |
|
173 | 173 | exec_lines = List(Unicode(), |
|
174 | 174 | help="""lines of code to run at IPython startup.""" |
|
175 | 175 | ).tag(config=True) |
|
176 | 176 | code_to_run = Unicode('', |
|
177 | 177 | help="Execute the given command string." |
|
178 | 178 | ).tag(config=True) |
|
179 | 179 | module_to_run = Unicode('', |
|
180 | 180 | help="Run the module as a script." |
|
181 | 181 | ).tag(config=True) |
|
182 | 182 | gui = CaselessStrEnum(gui_keys, allow_none=True, |
|
183 | 183 | help="Enable GUI event loop integration with any of {0}.".format(gui_keys) |
|
184 | 184 | ).tag(config=True) |
|
185 | 185 | matplotlib = CaselessStrEnum(backend_keys, allow_none=True, |
|
186 | 186 | help="""Configure matplotlib for interactive use with |
|
187 | 187 | the default matplotlib backend.""" |
|
188 | 188 | ).tag(config=True) |
|
189 | 189 | pylab = CaselessStrEnum(backend_keys, allow_none=True, |
|
190 | 190 | help="""Pre-load matplotlib and numpy for interactive use, |
|
191 | 191 | selecting a particular matplotlib backend and loop integration. |
|
192 | 192 | """ |
|
193 | 193 | ).tag(config=True) |
|
194 | 194 | pylab_import_all = Bool(True, |
|
195 | 195 | help="""If true, IPython will populate the user namespace with numpy, pylab, etc. |
|
196 | 196 | and an ``import *`` is done from numpy and pylab, when using pylab mode. |
|
197 | 197 | |
|
198 | 198 | When False, pylab mode should not import any names into the user namespace. |
|
199 | 199 | """ |
|
200 | 200 | ).tag(config=True) |
|
201 | 201 | ignore_cwd = Bool( |
|
202 | 202 | False, |
|
203 | 203 | help="""If True, IPython will not add the current working directory to sys.path. |
|
204 | 204 | When False, the current working directory is added to sys.path, allowing imports |
|
205 | 205 | of modules defined in the current directory.""" |
|
206 | 206 | ).tag(config=True) |
|
207 | 207 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', |
|
208 | 208 | allow_none=True) |
|
209 | 209 | # whether interact-loop should start |
|
210 | 210 | interact = Bool(True) |
|
211 | 211 | |
|
212 | 212 | user_ns = Instance(dict, args=None, allow_none=True) |
|
213 | 213 | @observe('user_ns') |
|
214 | 214 | def _user_ns_changed(self, change): |
|
215 | 215 | if self.shell is not None: |
|
216 | 216 | self.shell.user_ns = change['new'] |
|
217 | 217 | self.shell.init_user_ns() |
|
218 | 218 | |
|
219 | 219 | def init_path(self): |
|
220 | 220 | """Add current working directory, '', to sys.path |
|
221 | 221 | |
|
222 | 222 | Unlike Python's default, we insert before the first `site-packages` |
|
223 | 223 | or `dist-packages` directory, |
|
224 | 224 | so that it is after the standard library. |
|
225 | 225 | |
|
226 | 226 | .. versionchanged:: 7.2 |
|
227 | 227 | Try to insert after the standard library, instead of first. |
|
228 | 228 | .. versionchanged:: 8.0 |
|
229 | 229 | Allow optionally not including the current directory in sys.path |
|
230 | 230 | """ |
|
231 | 231 | if '' in sys.path or self.ignore_cwd: |
|
232 | 232 | return |
|
233 | 233 | for idx, path in enumerate(sys.path): |
|
234 | 234 | parent, last_part = os.path.split(path) |
|
235 | 235 | if last_part in {'site-packages', 'dist-packages'}: |
|
236 | 236 | break |
|
237 | 237 | else: |
|
238 | 238 | # no site-packages or dist-packages found (?!) |
|
239 | 239 | # back to original behavior of inserting at the front |
|
240 | 240 | idx = 0 |
|
241 | 241 | sys.path.insert(idx, '') |
|
242 | 242 | |
|
243 | 243 | def init_shell(self): |
|
244 | 244 | raise NotImplementedError("Override in subclasses") |
|
245 | 245 | |
|
246 | 246 | def init_gui_pylab(self): |
|
247 | 247 | """Enable GUI event loop integration, taking pylab into account.""" |
|
248 | 248 | enable = False |
|
249 | 249 | shell = self.shell |
|
250 | 250 | if self.pylab: |
|
251 | 251 | enable = lambda key: shell.enable_pylab(key, import_all=self.pylab_import_all) |
|
252 | 252 | key = self.pylab |
|
253 | 253 | elif self.matplotlib: |
|
254 | 254 | enable = shell.enable_matplotlib |
|
255 | 255 | key = self.matplotlib |
|
256 | 256 | elif self.gui: |
|
257 | 257 | enable = shell.enable_gui |
|
258 | 258 | key = self.gui |
|
259 | 259 | |
|
260 | 260 | if not enable: |
|
261 | 261 | return |
|
262 | 262 | |
|
263 | 263 | try: |
|
264 | 264 | r = enable(key) |
|
265 | 265 | except ImportError: |
|
266 | 266 | self.log.warning("Eventloop or matplotlib integration failed. Is matplotlib installed?") |
|
267 | 267 | self.shell.showtraceback() |
|
268 | 268 | return |
|
269 | 269 | except Exception: |
|
270 | 270 | self.log.warning("GUI event loop or pylab initialization failed") |
|
271 | 271 | self.shell.showtraceback() |
|
272 | 272 | return |
|
273 | 273 | |
|
274 | 274 | if isinstance(r, tuple): |
|
275 | 275 | gui, backend = r[:2] |
|
276 | 276 | self.log.info("Enabling GUI event loop integration, " |
|
277 | 277 | "eventloop=%s, matplotlib=%s", gui, backend) |
|
278 | 278 | if key == "auto": |
|
279 | 279 | print("Using matplotlib backend: %s" % backend) |
|
280 | 280 | else: |
|
281 | 281 | gui = r |
|
282 | 282 | self.log.info("Enabling GUI event loop integration, " |
|
283 | 283 | "eventloop=%s", gui) |
|
284 | 284 | |
|
285 | 285 | def init_extensions(self): |
|
286 | 286 | """Load all IPython extensions in IPythonApp.extensions. |
|
287 | 287 | |
|
288 | 288 | This uses the :meth:`ExtensionManager.load_extensions` to load all |
|
289 | 289 | the extensions listed in ``self.extensions``. |
|
290 | 290 | """ |
|
291 | 291 | try: |
|
292 | 292 | self.log.debug("Loading IPython extensions...") |
|
293 | 293 | extensions = ( |
|
294 | 294 | self.default_extensions + self.extensions + self.extra_extensions |
|
295 | 295 | ) |
|
296 | 296 | if self.extra_extension: |
|
297 | 297 | extensions.append(self.extra_extension) |
|
298 | 298 | for ext in extensions: |
|
299 | 299 | try: |
|
300 | 300 | self.log.info("Loading IPython extension: %s" % ext) |
|
301 | 301 | self.shell.extension_manager.load_extension(ext) |
|
302 | 302 | except: |
|
303 | 303 | if self.reraise_ipython_extension_failures: |
|
304 | 304 | raise |
|
305 | 305 | msg = ("Error in loading extension: {ext}\n" |
|
306 | 306 | "Check your config files in {location}".format( |
|
307 | 307 | ext=ext, |
|
308 | 308 | location=self.profile_dir.location |
|
309 | 309 | )) |
|
310 | 310 | self.log.warning(msg, exc_info=True) |
|
311 | 311 | except: |
|
312 | 312 | if self.reraise_ipython_extension_failures: |
|
313 | 313 | raise |
|
314 | 314 | self.log.warning("Unknown error in loading extensions:", exc_info=True) |
|
315 | 315 | |
|
316 | 316 | def init_code(self): |
|
317 | 317 | """run the pre-flight code, specified via exec_lines""" |
|
318 | 318 | self._run_startup_files() |
|
319 | 319 | self._run_exec_lines() |
|
320 | 320 | self._run_exec_files() |
|
321 | 321 | |
|
322 | 322 | # Hide variables defined here from %who etc. |
|
323 | 323 | if self.hide_initial_ns: |
|
324 | 324 | self.shell.user_ns_hidden.update(self.shell.user_ns) |
|
325 | 325 | |
|
326 | 326 | # command-line execution (ipython -i script.py, ipython -m module) |
|
327 | 327 | # should *not* be excluded from %whos |
|
328 | 328 | self._run_cmd_line_code() |
|
329 | 329 | self._run_module() |
|
330 | 330 | |
|
331 | 331 | # flush output, so itwon't be attached to the first cell |
|
332 | 332 | sys.stdout.flush() |
|
333 | 333 | sys.stderr.flush() |
|
334 | self.shell._sys_modules_keys = set(sys.modules.keys()) | |
|
334 | 335 | |
|
335 | 336 | def _run_exec_lines(self): |
|
336 | 337 | """Run lines of code in IPythonApp.exec_lines in the user's namespace.""" |
|
337 | 338 | if not self.exec_lines: |
|
338 | 339 | return |
|
339 | 340 | try: |
|
340 | 341 | self.log.debug("Running code from IPythonApp.exec_lines...") |
|
341 | 342 | for line in self.exec_lines: |
|
342 | 343 | try: |
|
343 | 344 | self.log.info("Running code in user namespace: %s" % |
|
344 | 345 | line) |
|
345 | 346 | self.shell.run_cell(line, store_history=False) |
|
346 | 347 | except: |
|
347 | 348 | self.log.warning("Error in executing line in user " |
|
348 | 349 | "namespace: %s" % line) |
|
349 | 350 | self.shell.showtraceback() |
|
350 | 351 | except: |
|
351 | 352 | self.log.warning("Unknown error in handling IPythonApp.exec_lines:") |
|
352 | 353 | self.shell.showtraceback() |
|
353 | 354 | |
|
354 | 355 | def _exec_file(self, fname, shell_futures=False): |
|
355 | 356 | try: |
|
356 | 357 | full_filename = filefind(fname, [u'.', self.ipython_dir]) |
|
357 | 358 | except IOError: |
|
358 | 359 | self.log.warning("File not found: %r"%fname) |
|
359 | 360 | return |
|
360 | 361 | # Make sure that the running script gets a proper sys.argv as if it |
|
361 | 362 | # were run from a system shell. |
|
362 | 363 | save_argv = sys.argv |
|
363 | 364 | sys.argv = [full_filename] + self.extra_args[1:] |
|
364 | 365 | try: |
|
365 | 366 | if os.path.isfile(full_filename): |
|
366 | 367 | self.log.info("Running file in user namespace: %s" % |
|
367 | 368 | full_filename) |
|
368 | 369 | # Ensure that __file__ is always defined to match Python |
|
369 | 370 | # behavior. |
|
370 | 371 | with preserve_keys(self.shell.user_ns, '__file__'): |
|
371 | 372 | self.shell.user_ns['__file__'] = fname |
|
372 | 373 | if full_filename.endswith('.ipy') or full_filename.endswith('.ipynb'): |
|
373 | 374 | self.shell.safe_execfile_ipy(full_filename, |
|
374 | 375 | shell_futures=shell_futures) |
|
375 | 376 | else: |
|
376 | 377 | # default to python, even without extension |
|
377 | 378 | self.shell.safe_execfile(full_filename, |
|
378 | 379 | self.shell.user_ns, |
|
379 | 380 | shell_futures=shell_futures, |
|
380 | 381 | raise_exceptions=True) |
|
381 | 382 | finally: |
|
382 | 383 | sys.argv = save_argv |
|
383 | 384 | |
|
384 | 385 | def _run_startup_files(self): |
|
385 | 386 | """Run files from profile startup directory""" |
|
386 | 387 | startup_dirs = [self.profile_dir.startup_dir] + [ |
|
387 | 388 | os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS) |
|
388 | 389 | ] |
|
389 | 390 | startup_files = [] |
|
390 | 391 | |
|
391 | 392 | if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \ |
|
392 | 393 | not (self.file_to_run or self.code_to_run or self.module_to_run): |
|
393 | 394 | python_startup = os.environ['PYTHONSTARTUP'] |
|
394 | 395 | self.log.debug("Running PYTHONSTARTUP file %s...", python_startup) |
|
395 | 396 | try: |
|
396 | 397 | self._exec_file(python_startup) |
|
397 | 398 | except: |
|
398 | 399 | self.log.warning("Unknown error in handling PYTHONSTARTUP file %s:", python_startup) |
|
399 | 400 | self.shell.showtraceback() |
|
400 | 401 | for startup_dir in startup_dirs[::-1]: |
|
401 | 402 | startup_files += glob.glob(os.path.join(startup_dir, '*.py')) |
|
402 | 403 | startup_files += glob.glob(os.path.join(startup_dir, '*.ipy')) |
|
403 | 404 | if not startup_files: |
|
404 | 405 | return |
|
405 | 406 | |
|
406 | 407 | self.log.debug("Running startup files from %s...", startup_dir) |
|
407 | 408 | try: |
|
408 | 409 | for fname in sorted(startup_files): |
|
409 | 410 | self._exec_file(fname) |
|
410 | 411 | except: |
|
411 | 412 | self.log.warning("Unknown error in handling startup files:") |
|
412 | 413 | self.shell.showtraceback() |
|
413 | 414 | |
|
414 | 415 | def _run_exec_files(self): |
|
415 | 416 | """Run files from IPythonApp.exec_files""" |
|
416 | 417 | if not self.exec_files: |
|
417 | 418 | return |
|
418 | 419 | |
|
419 | 420 | self.log.debug("Running files in IPythonApp.exec_files...") |
|
420 | 421 | try: |
|
421 | 422 | for fname in self.exec_files: |
|
422 | 423 | self._exec_file(fname) |
|
423 | 424 | except: |
|
424 | 425 | self.log.warning("Unknown error in handling IPythonApp.exec_files:") |
|
425 | 426 | self.shell.showtraceback() |
|
426 | 427 | |
|
427 | 428 | def _run_cmd_line_code(self): |
|
428 | 429 | """Run code or file specified at the command-line""" |
|
429 | 430 | if self.code_to_run: |
|
430 | 431 | line = self.code_to_run |
|
431 | 432 | try: |
|
432 | 433 | self.log.info("Running code given at command line (c=): %s" % |
|
433 | 434 | line) |
|
434 | 435 | self.shell.run_cell(line, store_history=False) |
|
435 | 436 | except: |
|
436 | 437 | self.log.warning("Error in executing line in user namespace: %s" % |
|
437 | 438 | line) |
|
438 | 439 | self.shell.showtraceback() |
|
439 | 440 | if not self.interact: |
|
440 | 441 | self.exit(1) |
|
441 | 442 | |
|
442 | 443 | # Like Python itself, ignore the second if the first of these is present |
|
443 | 444 | elif self.file_to_run: |
|
444 | 445 | fname = self.file_to_run |
|
445 | 446 | if os.path.isdir(fname): |
|
446 | 447 | fname = os.path.join(fname, "__main__.py") |
|
447 | 448 | if not os.path.exists(fname): |
|
448 | 449 | self.log.warning("File '%s' doesn't exist", fname) |
|
449 | 450 | if not self.interact: |
|
450 | 451 | self.exit(2) |
|
451 | 452 | try: |
|
452 | 453 | self._exec_file(fname, shell_futures=True) |
|
453 | 454 | except: |
|
454 | 455 | self.shell.showtraceback(tb_offset=4) |
|
455 | 456 | if not self.interact: |
|
456 | 457 | self.exit(1) |
|
457 | 458 | |
|
458 | 459 | def _run_module(self): |
|
459 | 460 | """Run module specified at the command-line.""" |
|
460 | 461 | if self.module_to_run: |
|
461 | 462 | # Make sure that the module gets a proper sys.argv as if it were |
|
462 | 463 | # run using `python -m`. |
|
463 | 464 | save_argv = sys.argv |
|
464 | 465 | sys.argv = [sys.executable] + self.extra_args |
|
465 | 466 | try: |
|
466 | 467 | self.shell.safe_run_module(self.module_to_run, |
|
467 | 468 | self.shell.user_ns) |
|
468 | 469 | finally: |
|
469 | 470 | sys.argv = save_argv |
General Comments 0
You need to be logged in to leave comments.
Login now