##// END OF EJS Templates
Mare reset -f more agressive and cull sys.modules;...
Matthias Bussonnier -
Show More

The requested changes are too big and content was truncated. Show full diff

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