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