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