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