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