##// END OF EJS Templates
add `--matplotlib` flag to terminal IPython...
MinRK -
Show More
@@ -1,371 +1,397 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 Authors
6 Authors
7 -------
7 -------
8
8
9 * Min Ragan-Kelley
9 * Min Ragan-Kelley
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2011 The IPython Development Team
13 # Copyright (C) 2008-2011 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from __future__ import absolute_import
23 from __future__ import absolute_import
24
24
25 import glob
25 import glob
26 import os
26 import os
27 import sys
27 import sys
28
28
29 from IPython.config.application import boolean_flag
29 from IPython.config.application import boolean_flag
30 from IPython.config.configurable import Configurable
30 from IPython.config.configurable import Configurable
31 from IPython.config.loader import Config
31 from IPython.config.loader import Config
32 from IPython.core import pylabtools
32 from IPython.core import pylabtools
33 from IPython.utils import py3compat
33 from IPython.utils import py3compat
34 from IPython.utils.contexts import preserve_keys
34 from IPython.utils.contexts import preserve_keys
35 from IPython.utils.path import filefind
35 from IPython.utils.path import filefind
36 from IPython.utils.traitlets import (
36 from IPython.utils.traitlets import (
37 Unicode, Instance, List, Bool, CaselessStrEnum
37 Unicode, Instance, List, Bool, CaselessStrEnum
38 )
38 )
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Aliases and Flags
41 # Aliases and Flags
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 shell_flags = {}
44 shell_flags = {}
45
45
46 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
46 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
47 addflag('autoindent', 'InteractiveShell.autoindent',
47 addflag('autoindent', 'InteractiveShell.autoindent',
48 'Turn on autoindenting.', 'Turn off autoindenting.'
48 'Turn on autoindenting.', 'Turn off autoindenting.'
49 )
49 )
50 addflag('automagic', 'InteractiveShell.automagic',
50 addflag('automagic', 'InteractiveShell.automagic',
51 """Turn on the auto calling of magic commands. Type %%magic at the
51 """Turn on the auto calling of magic commands. Type %%magic at the
52 IPython prompt for more information.""",
52 IPython prompt for more information.""",
53 'Turn off the auto calling of magic commands.'
53 'Turn off the auto calling of magic commands.'
54 )
54 )
55 addflag('pdb', 'InteractiveShell.pdb',
55 addflag('pdb', 'InteractiveShell.pdb',
56 "Enable auto calling the pdb debugger after every exception.",
56 "Enable auto calling the pdb debugger after every exception.",
57 "Disable auto calling the pdb debugger after every exception."
57 "Disable auto calling the pdb debugger after every exception."
58 )
58 )
59 # pydb flag doesn't do any config, as core.debugger switches on import,
59 # pydb flag doesn't do any config, as core.debugger switches on import,
60 # which is before parsing. This just allows the flag to be passed.
60 # which is before parsing. This just allows the flag to be passed.
61 shell_flags.update(dict(
61 shell_flags.update(dict(
62 pydb = ({},
62 pydb = ({},
63 """Use the third party 'pydb' package as debugger, instead of pdb.
63 """Use the third party 'pydb' package as debugger, instead of pdb.
64 Requires that pydb is installed."""
64 Requires that pydb is installed."""
65 )
65 )
66 ))
66 ))
67 addflag('pprint', 'PlainTextFormatter.pprint',
67 addflag('pprint', 'PlainTextFormatter.pprint',
68 "Enable auto pretty printing of results.",
68 "Enable auto pretty printing of results.",
69 "Disable auto auto pretty printing of results."
69 "Disable auto auto pretty printing of results."
70 )
70 )
71 addflag('color-info', 'InteractiveShell.color_info',
71 addflag('color-info', 'InteractiveShell.color_info',
72 """IPython can display information about objects via a set of func-
72 """IPython can display information about objects via a set of func-
73 tions, and optionally can use colors for this, syntax highlighting
73 tions, and optionally can use colors for this, syntax highlighting
74 source code and various other elements. However, because this
74 source code and various other elements. However, because this
75 information is passed through a pager (like 'less') and many pagers get
75 information is passed through a pager (like 'less') and many pagers get
76 confused with color codes, this option is off by default. You can test
76 confused with color codes, this option is off by default. You can test
77 it and turn it on permanently in your ipython_config.py file if it
77 it and turn it on permanently in your ipython_config.py file if it
78 works for you. Test it and turn it on permanently if it works with
78 works for you. Test it and turn it on permanently if it works with
79 your system. The magic function %%color_info allows you to toggle this
79 your system. The magic function %%color_info allows you to toggle this
80 interactively for testing.""",
80 interactively for testing.""",
81 "Disable using colors for info related things."
81 "Disable using colors for info related things."
82 )
82 )
83 addflag('deep-reload', 'InteractiveShell.deep_reload',
83 addflag('deep-reload', 'InteractiveShell.deep_reload',
84 """Enable deep (recursive) reloading by default. IPython can use the
84 """Enable deep (recursive) reloading by default. IPython can use the
85 deep_reload module which reloads changes in modules recursively (it
85 deep_reload module which reloads changes in modules recursively (it
86 replaces the reload() function, so you don't need to change anything to
86 replaces the reload() function, so you don't need to change anything to
87 use it). deep_reload() forces a full reload of modules whose code may
87 use it). deep_reload() forces a full reload of modules whose code may
88 have changed, which the default reload() function does not. When
88 have changed, which the default reload() function does not. When
89 deep_reload is off, IPython will use the normal reload(), but
89 deep_reload is off, IPython will use the normal reload(), but
90 deep_reload will still be available as dreload(). This feature is off
90 deep_reload will still be available as dreload(). This feature is off
91 by default [which means that you have both normal reload() and
91 by default [which means that you have both normal reload() and
92 dreload()].""",
92 dreload()].""",
93 "Disable deep (recursive) reloading by default."
93 "Disable deep (recursive) reloading by default."
94 )
94 )
95 nosep_config = Config()
95 nosep_config = Config()
96 nosep_config.InteractiveShell.separate_in = ''
96 nosep_config.InteractiveShell.separate_in = ''
97 nosep_config.InteractiveShell.separate_out = ''
97 nosep_config.InteractiveShell.separate_out = ''
98 nosep_config.InteractiveShell.separate_out2 = ''
98 nosep_config.InteractiveShell.separate_out2 = ''
99
99
100 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
100 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
101 shell_flags['pylab'] = (
101 shell_flags['pylab'] = (
102 {'InteractiveShellApp' : {'pylab' : 'auto'}},
102 {'InteractiveShellApp' : {'pylab' : 'auto'}},
103 """Pre-load matplotlib and numpy for interactive use with
103 """Pre-load matplotlib and numpy for interactive use with
104 the default matplotlib backend."""
104 the default matplotlib backend."""
105 )
105 )
106 shell_flags['matplotlib'] = (
107 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
108 """Configure matplotlib for interactive use with
109 the default matplotlib backend."""
110 )
106
111
107 # it's possible we don't want short aliases for *all* of these:
112 # it's possible we don't want short aliases for *all* of these:
108 shell_aliases = dict(
113 shell_aliases = dict(
109 autocall='InteractiveShell.autocall',
114 autocall='InteractiveShell.autocall',
110 colors='InteractiveShell.colors',
115 colors='InteractiveShell.colors',
111 logfile='InteractiveShell.logfile',
116 logfile='InteractiveShell.logfile',
112 logappend='InteractiveShell.logappend',
117 logappend='InteractiveShell.logappend',
113 c='InteractiveShellApp.code_to_run',
118 c='InteractiveShellApp.code_to_run',
114 m='InteractiveShellApp.module_to_run',
119 m='InteractiveShellApp.module_to_run',
115 ext='InteractiveShellApp.extra_extension',
120 ext='InteractiveShellApp.extra_extension',
116 gui='InteractiveShellApp.gui',
121 gui='InteractiveShellApp.gui',
117 pylab='InteractiveShellApp.pylab',
122 pylab='InteractiveShellApp.pylab',
123 matplotlib='InteractiveShellApp.matplotlib',
118 )
124 )
119 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
125 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
120
126
121 #-----------------------------------------------------------------------------
127 #-----------------------------------------------------------------------------
122 # Main classes and functions
128 # Main classes and functions
123 #-----------------------------------------------------------------------------
129 #-----------------------------------------------------------------------------
124
130
125 class InteractiveShellApp(Configurable):
131 class InteractiveShellApp(Configurable):
126 """A Mixin for applications that start InteractiveShell instances.
132 """A Mixin for applications that start InteractiveShell instances.
127
133
128 Provides configurables for loading extensions and executing files
134 Provides configurables for loading extensions and executing files
129 as part of configuring a Shell environment.
135 as part of configuring a Shell environment.
130
136
131 The following methods should be called by the :meth:`initialize` method
137 The following methods should be called by the :meth:`initialize` method
132 of the subclass:
138 of the subclass:
133
139
134 - :meth:`init_path`
140 - :meth:`init_path`
135 - :meth:`init_shell` (to be implemented by the subclass)
141 - :meth:`init_shell` (to be implemented by the subclass)
136 - :meth:`init_gui_pylab`
142 - :meth:`init_gui_pylab`
137 - :meth:`init_extensions`
143 - :meth:`init_extensions`
138 - :meth:`init_code`
144 - :meth:`init_code`
139 """
145 """
140 extensions = List(Unicode, config=True,
146 extensions = List(Unicode, config=True,
141 help="A list of dotted module names of IPython extensions to load."
147 help="A list of dotted module names of IPython extensions to load."
142 )
148 )
143 extra_extension = Unicode('', config=True,
149 extra_extension = Unicode('', config=True,
144 help="dotted module name of an IPython extension to load."
150 help="dotted module name of an IPython extension to load."
145 )
151 )
146 def _extra_extension_changed(self, name, old, new):
152 def _extra_extension_changed(self, name, old, new):
147 if new:
153 if new:
148 # add to self.extensions
154 # add to self.extensions
149 self.extensions.append(new)
155 self.extensions.append(new)
150
156
151 # Extensions that are always loaded (not configurable)
157 # Extensions that are always loaded (not configurable)
152 default_extensions = List(Unicode, [u'storemagic'], config=False)
158 default_extensions = List(Unicode, [u'storemagic'], config=False)
153
159
154 exec_files = List(Unicode, config=True,
160 exec_files = List(Unicode, config=True,
155 help="""List of files to run at IPython startup."""
161 help="""List of files to run at IPython startup."""
156 )
162 )
157 file_to_run = Unicode('', config=True,
163 file_to_run = Unicode('', config=True,
158 help="""A file to be run""")
164 help="""A file to be run""")
159
165
160 exec_lines = List(Unicode, config=True,
166 exec_lines = List(Unicode, config=True,
161 help="""lines of code to run at IPython startup."""
167 help="""lines of code to run at IPython startup."""
162 )
168 )
163 code_to_run = Unicode('', config=True,
169 code_to_run = Unicode('', config=True,
164 help="Execute the given command string."
170 help="Execute the given command string."
165 )
171 )
166 module_to_run = Unicode('', config=True,
172 module_to_run = Unicode('', config=True,
167 help="Run the module as a script."
173 help="Run the module as a script."
168 )
174 )
169 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx'), config=True,
175 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx'), config=True,
170 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx')."
176 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx')."
171 )
177 )
178 matplotlib = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'inline', 'auto'],
179 config=True,
180 help="""Configure matplotlib for interactive use with
181 the default matplotlib backend."""
182 )
172 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'inline', 'auto'],
183 pylab = CaselessStrEnum(['tk', 'qt', 'wx', 'gtk', 'osx', 'inline', 'auto'],
173 config=True,
184 config=True,
174 help="""Pre-load matplotlib and numpy for interactive use,
185 help="""Pre-load matplotlib and numpy for interactive use,
175 selecting a particular matplotlib backend and loop integration.
186 selecting a particular matplotlib backend and loop integration.
176 """
187 """
177 )
188 )
178 pylab_import_all = Bool(True, config=True,
189 pylab_import_all = Bool(True, config=True,
179 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
190 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
180 and an 'import *' is done from numpy and pylab, when using pylab mode.
191 and an 'import *' is done from numpy and pylab, when using pylab mode.
181
192
182 When False, pylab mode should not import any names into the user namespace.
193 When False, pylab mode should not import any names into the user namespace.
183 """
194 """
184 )
195 )
185 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
196 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
186
197
187 def init_path(self):
198 def init_path(self):
188 """Add current working directory, '', to sys.path"""
199 """Add current working directory, '', to sys.path"""
189 if sys.path[0] != '':
200 if sys.path[0] != '':
190 sys.path.insert(0, '')
201 sys.path.insert(0, '')
191
202
192 def init_shell(self):
203 def init_shell(self):
193 raise NotImplementedError("Override in subclasses")
204 raise NotImplementedError("Override in subclasses")
194
205
195 def init_gui_pylab(self):
206 def init_gui_pylab(self):
196 """Enable GUI event loop integration, taking pylab into account."""
207 """Enable GUI event loop integration, taking pylab into account."""
197 if self.gui or self.pylab:
208 enable = False
198 shell = self.shell
209 shell = self.shell
199 try:
200 if self.pylab:
210 if self.pylab:
201 gui, backend = pylabtools.find_gui_and_backend(self.pylab)
211 enable = shell.enable_pylab
202 self.log.info("Enabling GUI event loop integration, "
212 key = self.pylab
203 "toolkit=%s, pylab=%s" % (gui, self.pylab))
213 elif self.matplotlib:
204 if self.pylab == "auto":
214 enable = shell.enable_matplotlib
205 print ("using matplotlib backend: %s" % backend)
215 key = self.matplotlib
206 shell.enable_pylab(self.pylab, import_all=self.pylab_import_all)
216 elif self.gui:
207 else:
217 enable = shell.enable_gui
208 self.log.info("Enabling GUI event loop integration, "
218 key = self.gui
209 "toolkit=%s" % self.gui)
219
210 shell.enable_gui(self.gui)
220 if not enable:
221 return
222
223 try:
224 r = enable(key)
211 except ImportError:
225 except ImportError:
212 self.log.warn("pylab mode doesn't work as matplotlib could not be found." + \
226 self.log.warn("Eventloop or matplotlib integration failed. Is matplotlib installed?")
213 "\nIs it installed on the system?")
214 self.shell.showtraceback()
227 self.shell.showtraceback()
228 return
215 except Exception:
229 except Exception:
216 self.log.warn("GUI event loop or pylab initialization failed")
230 self.log.warn("GUI event loop or pylab initialization failed")
217 self.shell.showtraceback()
231 self.shell.showtraceback()
232 return
233
234 if isinstance(r, tuple):
235 gui, backend = r[:2]
236 self.log.info("Enabling GUI event loop integration, "
237 "eventloop=%s, matplotlib=%s", gui, backend)
238 if key == "auto":
239 print ("using matplotlib backend: %s" % backend)
240 else:
241 gui = r
242 self.log.info("Enabling GUI event loop integration, "
243 "eventloop=%s", gui)
218
244
219 def init_extensions(self):
245 def init_extensions(self):
220 """Load all IPython extensions in IPythonApp.extensions.
246 """Load all IPython extensions in IPythonApp.extensions.
221
247
222 This uses the :meth:`ExtensionManager.load_extensions` to load all
248 This uses the :meth:`ExtensionManager.load_extensions` to load all
223 the extensions listed in ``self.extensions``.
249 the extensions listed in ``self.extensions``.
224 """
250 """
225 try:
251 try:
226 self.log.debug("Loading IPython extensions...")
252 self.log.debug("Loading IPython extensions...")
227 extensions = self.default_extensions + self.extensions
253 extensions = self.default_extensions + self.extensions
228 for ext in extensions:
254 for ext in extensions:
229 try:
255 try:
230 self.log.info("Loading IPython extension: %s" % ext)
256 self.log.info("Loading IPython extension: %s" % ext)
231 self.shell.extension_manager.load_extension(ext)
257 self.shell.extension_manager.load_extension(ext)
232 except:
258 except:
233 self.log.warn("Error in loading extension: %s" % ext +
259 self.log.warn("Error in loading extension: %s" % ext +
234 "\nCheck your config files in %s" % self.profile_dir.location
260 "\nCheck your config files in %s" % self.profile_dir.location
235 )
261 )
236 self.shell.showtraceback()
262 self.shell.showtraceback()
237 except:
263 except:
238 self.log.warn("Unknown error in loading extensions:")
264 self.log.warn("Unknown error in loading extensions:")
239 self.shell.showtraceback()
265 self.shell.showtraceback()
240
266
241 def init_code(self):
267 def init_code(self):
242 """run the pre-flight code, specified via exec_lines"""
268 """run the pre-flight code, specified via exec_lines"""
243 self._run_startup_files()
269 self._run_startup_files()
244 self._run_exec_lines()
270 self._run_exec_lines()
245 self._run_exec_files()
271 self._run_exec_files()
246 self._run_cmd_line_code()
272 self._run_cmd_line_code()
247 self._run_module()
273 self._run_module()
248
274
249 # flush output, so itwon't be attached to the first cell
275 # flush output, so itwon't be attached to the first cell
250 sys.stdout.flush()
276 sys.stdout.flush()
251 sys.stderr.flush()
277 sys.stderr.flush()
252
278
253 # Hide variables defined here from %who etc.
279 # Hide variables defined here from %who etc.
254 self.shell.user_ns_hidden.update(self.shell.user_ns)
280 self.shell.user_ns_hidden.update(self.shell.user_ns)
255
281
256 def _run_exec_lines(self):
282 def _run_exec_lines(self):
257 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
283 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
258 if not self.exec_lines:
284 if not self.exec_lines:
259 return
285 return
260 try:
286 try:
261 self.log.debug("Running code from IPythonApp.exec_lines...")
287 self.log.debug("Running code from IPythonApp.exec_lines...")
262 for line in self.exec_lines:
288 for line in self.exec_lines:
263 try:
289 try:
264 self.log.info("Running code in user namespace: %s" %
290 self.log.info("Running code in user namespace: %s" %
265 line)
291 line)
266 self.shell.run_cell(line, store_history=False)
292 self.shell.run_cell(line, store_history=False)
267 except:
293 except:
268 self.log.warn("Error in executing line in user "
294 self.log.warn("Error in executing line in user "
269 "namespace: %s" % line)
295 "namespace: %s" % line)
270 self.shell.showtraceback()
296 self.shell.showtraceback()
271 except:
297 except:
272 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
298 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
273 self.shell.showtraceback()
299 self.shell.showtraceback()
274
300
275 def _exec_file(self, fname):
301 def _exec_file(self, fname):
276 try:
302 try:
277 full_filename = filefind(fname, [u'.', self.ipython_dir])
303 full_filename = filefind(fname, [u'.', self.ipython_dir])
278 except IOError as e:
304 except IOError as e:
279 self.log.warn("File not found: %r"%fname)
305 self.log.warn("File not found: %r"%fname)
280 return
306 return
281 # Make sure that the running script gets a proper sys.argv as if it
307 # Make sure that the running script gets a proper sys.argv as if it
282 # were run from a system shell.
308 # were run from a system shell.
283 save_argv = sys.argv
309 save_argv = sys.argv
284 sys.argv = [full_filename] + self.extra_args[1:]
310 sys.argv = [full_filename] + self.extra_args[1:]
285 # protect sys.argv from potential unicode strings on Python 2:
311 # protect sys.argv from potential unicode strings on Python 2:
286 if not py3compat.PY3:
312 if not py3compat.PY3:
287 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
313 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
288 try:
314 try:
289 if os.path.isfile(full_filename):
315 if os.path.isfile(full_filename):
290 self.log.info("Running file in user namespace: %s" %
316 self.log.info("Running file in user namespace: %s" %
291 full_filename)
317 full_filename)
292 # Ensure that __file__ is always defined to match Python
318 # Ensure that __file__ is always defined to match Python
293 # behavior.
319 # behavior.
294 with preserve_keys(self.shell.user_ns, '__file__'):
320 with preserve_keys(self.shell.user_ns, '__file__'):
295 self.shell.user_ns['__file__'] = fname
321 self.shell.user_ns['__file__'] = fname
296 if full_filename.endswith('.ipy'):
322 if full_filename.endswith('.ipy'):
297 self.shell.safe_execfile_ipy(full_filename)
323 self.shell.safe_execfile_ipy(full_filename)
298 else:
324 else:
299 # default to python, even without extension
325 # default to python, even without extension
300 self.shell.safe_execfile(full_filename,
326 self.shell.safe_execfile(full_filename,
301 self.shell.user_ns)
327 self.shell.user_ns)
302 finally:
328 finally:
303 sys.argv = save_argv
329 sys.argv = save_argv
304
330
305 def _run_startup_files(self):
331 def _run_startup_files(self):
306 """Run files from profile startup directory"""
332 """Run files from profile startup directory"""
307 startup_dir = self.profile_dir.startup_dir
333 startup_dir = self.profile_dir.startup_dir
308 startup_files = []
334 startup_files = []
309 if os.environ.get('PYTHONSTARTUP', False):
335 if os.environ.get('PYTHONSTARTUP', False):
310 startup_files.append(os.environ['PYTHONSTARTUP'])
336 startup_files.append(os.environ['PYTHONSTARTUP'])
311 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
337 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
312 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
338 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
313 if not startup_files:
339 if not startup_files:
314 return
340 return
315
341
316 self.log.debug("Running startup files from %s...", startup_dir)
342 self.log.debug("Running startup files from %s...", startup_dir)
317 try:
343 try:
318 for fname in sorted(startup_files):
344 for fname in sorted(startup_files):
319 self._exec_file(fname)
345 self._exec_file(fname)
320 except:
346 except:
321 self.log.warn("Unknown error in handling startup files:")
347 self.log.warn("Unknown error in handling startup files:")
322 self.shell.showtraceback()
348 self.shell.showtraceback()
323
349
324 def _run_exec_files(self):
350 def _run_exec_files(self):
325 """Run files from IPythonApp.exec_files"""
351 """Run files from IPythonApp.exec_files"""
326 if not self.exec_files:
352 if not self.exec_files:
327 return
353 return
328
354
329 self.log.debug("Running files in IPythonApp.exec_files...")
355 self.log.debug("Running files in IPythonApp.exec_files...")
330 try:
356 try:
331 for fname in self.exec_files:
357 for fname in self.exec_files:
332 self._exec_file(fname)
358 self._exec_file(fname)
333 except:
359 except:
334 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
360 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
335 self.shell.showtraceback()
361 self.shell.showtraceback()
336
362
337 def _run_cmd_line_code(self):
363 def _run_cmd_line_code(self):
338 """Run code or file specified at the command-line"""
364 """Run code or file specified at the command-line"""
339 if self.code_to_run:
365 if self.code_to_run:
340 line = self.code_to_run
366 line = self.code_to_run
341 try:
367 try:
342 self.log.info("Running code given at command line (c=): %s" %
368 self.log.info("Running code given at command line (c=): %s" %
343 line)
369 line)
344 self.shell.run_cell(line, store_history=False)
370 self.shell.run_cell(line, store_history=False)
345 except:
371 except:
346 self.log.warn("Error in executing line in user namespace: %s" %
372 self.log.warn("Error in executing line in user namespace: %s" %
347 line)
373 line)
348 self.shell.showtraceback()
374 self.shell.showtraceback()
349
375
350 # Like Python itself, ignore the second if the first of these is present
376 # Like Python itself, ignore the second if the first of these is present
351 elif self.file_to_run:
377 elif self.file_to_run:
352 fname = self.file_to_run
378 fname = self.file_to_run
353 try:
379 try:
354 self._exec_file(fname)
380 self._exec_file(fname)
355 except:
381 except:
356 self.log.warn("Error in executing file in user namespace: %s" %
382 self.log.warn("Error in executing file in user namespace: %s" %
357 fname)
383 fname)
358 self.shell.showtraceback()
384 self.shell.showtraceback()
359
385
360 def _run_module(self):
386 def _run_module(self):
361 """Run module specified at the command-line."""
387 """Run module specified at the command-line."""
362 if self.module_to_run:
388 if self.module_to_run:
363 # Make sure that the module gets a proper sys.argv as if it were
389 # Make sure that the module gets a proper sys.argv as if it were
364 # run using `python -m`.
390 # run using `python -m`.
365 save_argv = sys.argv
391 save_argv = sys.argv
366 sys.argv = [sys.executable] + self.extra_args
392 sys.argv = [sys.executable] + self.extra_args
367 try:
393 try:
368 self.shell.safe_run_module(self.module_to_run,
394 self.shell.safe_run_module(self.module_to_run,
369 self.shell.user_ns)
395 self.shell.user_ns)
370 finally:
396 finally:
371 sys.argv = save_argv
397 sys.argv = save_argv
General Comments 0
You need to be logged in to leave comments. Login now