##// END OF EJS Templates
add config file note to failed load_extension message
MinRK -
Show More
@@ -1,289 +1,291 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 A mixin for :class:`~IPython.core.application.Application` classes that
3 A mixin for :class:`~IPython.core.application.Application` classes that
4 launch InteractiveShell instances, load extensions, etc.
4 launch InteractiveShell instances, load extensions, etc.
5
5
6 Authors
6 Authors
7 -------
7 -------
8
8
9 * Min Ragan-Kelley
9 * Min Ragan-Kelley
10 """
10 """
11
11
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13 # Copyright (C) 2008-2011 The IPython Development Team
13 # Copyright (C) 2008-2011 The IPython Development Team
14 #
14 #
15 # Distributed under the terms of the BSD License. The full license is in
15 # Distributed under the terms of the BSD License. The full license is in
16 # the file COPYING, distributed as part of this software.
16 # the file COPYING, distributed as part of this software.
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 from __future__ import absolute_import
23 from __future__ import absolute_import
24
24
25 import glob
25 import glob
26 import os
26 import os
27 import sys
27 import sys
28
28
29 from IPython.config.application import boolean_flag
29 from IPython.config.application import boolean_flag
30 from IPython.config.configurable import Configurable
30 from IPython.config.configurable import Configurable
31 from IPython.config.loader import Config
31 from IPython.config.loader import Config
32 from IPython.utils import py3compat
32 from IPython.utils import py3compat
33 from IPython.utils.path import filefind
33 from IPython.utils.path import filefind
34 from IPython.utils.traitlets import Unicode, Instance, List, Bool
34 from IPython.utils.traitlets import Unicode, Instance, List, Bool
35
35
36 #-----------------------------------------------------------------------------
36 #-----------------------------------------------------------------------------
37 # Aliases and Flags
37 # Aliases and Flags
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39
39
40 shell_flags = {}
40 shell_flags = {}
41
41
42 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
42 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
43 addflag('autoindent', 'InteractiveShell.autoindent',
43 addflag('autoindent', 'InteractiveShell.autoindent',
44 'Turn on autoindenting.', 'Turn off autoindenting.'
44 'Turn on autoindenting.', 'Turn off autoindenting.'
45 )
45 )
46 addflag('automagic', 'InteractiveShell.automagic',
46 addflag('automagic', 'InteractiveShell.automagic',
47 """Turn on the auto calling of magic commands. Type %%magic at the
47 """Turn on the auto calling of magic commands. Type %%magic at the
48 IPython prompt for more information.""",
48 IPython prompt for more information.""",
49 'Turn off the auto calling of magic commands.'
49 'Turn off the auto calling of magic commands.'
50 )
50 )
51 addflag('pdb', 'InteractiveShell.pdb',
51 addflag('pdb', 'InteractiveShell.pdb',
52 "Enable auto calling the pdb debugger after every exception.",
52 "Enable auto calling the pdb debugger after every exception.",
53 "Disable auto calling the pdb debugger after every exception."
53 "Disable auto calling the pdb debugger after every exception."
54 )
54 )
55 # pydb flag doesn't do any config, as core.debugger switches on import,
55 # pydb flag doesn't do any config, as core.debugger switches on import,
56 # which is before parsing. This just allows the flag to be passed.
56 # which is before parsing. This just allows the flag to be passed.
57 shell_flags.update(dict(
57 shell_flags.update(dict(
58 pydb = ({},
58 pydb = ({},
59 """"Use the third party 'pydb' package as debugger, instead of pdb.
59 """"Use the third party 'pydb' package as debugger, instead of pdb.
60 Requires that pydb is installed."""
60 Requires that pydb is installed."""
61 )
61 )
62 ))
62 ))
63 addflag('pprint', 'PlainTextFormatter.pprint',
63 addflag('pprint', 'PlainTextFormatter.pprint',
64 "Enable auto pretty printing of results.",
64 "Enable auto pretty printing of results.",
65 "Disable auto auto pretty printing of results."
65 "Disable auto auto pretty printing of results."
66 )
66 )
67 addflag('color-info', 'InteractiveShell.color_info',
67 addflag('color-info', 'InteractiveShell.color_info',
68 """IPython can display information about objects via a set of func-
68 """IPython can display information about objects via a set of func-
69 tions, and optionally can use colors for this, syntax highlighting
69 tions, and optionally can use colors for this, syntax highlighting
70 source code and various other elements. However, because this
70 source code and various other elements. However, because this
71 information is passed through a pager (like 'less') and many pagers get
71 information is passed through a pager (like 'less') and many pagers get
72 confused with color codes, this option is off by default. You can test
72 confused with color codes, this option is off by default. You can test
73 it and turn it on permanently in your ipython_config.py file if it
73 it and turn it on permanently in your ipython_config.py file if it
74 works for you. Test it and turn it on permanently if it works with
74 works for you. Test it and turn it on permanently if it works with
75 your system. The magic function %%color_info allows you to toggle this
75 your system. The magic function %%color_info allows you to toggle this
76 interactively for testing.""",
76 interactively for testing.""",
77 "Disable using colors for info related things."
77 "Disable using colors for info related things."
78 )
78 )
79 addflag('deep-reload', 'InteractiveShell.deep_reload',
79 addflag('deep-reload', 'InteractiveShell.deep_reload',
80 """Enable deep (recursive) reloading by default. IPython can use the
80 """Enable deep (recursive) reloading by default. IPython can use the
81 deep_reload module which reloads changes in modules recursively (it
81 deep_reload module which reloads changes in modules recursively (it
82 replaces the reload() function, so you don't need to change anything to
82 replaces the reload() function, so you don't need to change anything to
83 use it). deep_reload() forces a full reload of modules whose code may
83 use it). deep_reload() forces a full reload of modules whose code may
84 have changed, which the default reload() function does not. When
84 have changed, which the default reload() function does not. When
85 deep_reload is off, IPython will use the normal reload(), but
85 deep_reload is off, IPython will use the normal reload(), but
86 deep_reload will still be available as dreload(). This feature is off
86 deep_reload will still be available as dreload(). This feature is off
87 by default [which means that you have both normal reload() and
87 by default [which means that you have both normal reload() and
88 dreload()].""",
88 dreload()].""",
89 "Disable deep (recursive) reloading by default."
89 "Disable deep (recursive) reloading by default."
90 )
90 )
91 nosep_config = Config()
91 nosep_config = Config()
92 nosep_config.InteractiveShell.separate_in = ''
92 nosep_config.InteractiveShell.separate_in = ''
93 nosep_config.InteractiveShell.separate_out = ''
93 nosep_config.InteractiveShell.separate_out = ''
94 nosep_config.InteractiveShell.separate_out2 = ''
94 nosep_config.InteractiveShell.separate_out2 = ''
95
95
96 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
96 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
97
97
98
98
99 # it's possible we don't want short aliases for *all* of these:
99 # it's possible we don't want short aliases for *all* of these:
100 shell_aliases = dict(
100 shell_aliases = dict(
101 autocall='InteractiveShell.autocall',
101 autocall='InteractiveShell.autocall',
102 colors='InteractiveShell.colors',
102 colors='InteractiveShell.colors',
103 logfile='InteractiveShell.logfile',
103 logfile='InteractiveShell.logfile',
104 logappend='InteractiveShell.logappend',
104 logappend='InteractiveShell.logappend',
105 c='InteractiveShellApp.code_to_run',
105 c='InteractiveShellApp.code_to_run',
106 ext='InteractiveShellApp.extra_extension',
106 ext='InteractiveShellApp.extra_extension',
107 )
107 )
108 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
108 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
109
109
110 #-----------------------------------------------------------------------------
110 #-----------------------------------------------------------------------------
111 # Main classes and functions
111 # Main classes and functions
112 #-----------------------------------------------------------------------------
112 #-----------------------------------------------------------------------------
113
113
114 class InteractiveShellApp(Configurable):
114 class InteractiveShellApp(Configurable):
115 """A Mixin for applications that start InteractiveShell instances.
115 """A Mixin for applications that start InteractiveShell instances.
116
116
117 Provides configurables for loading extensions and executing files
117 Provides configurables for loading extensions and executing files
118 as part of configuring a Shell environment.
118 as part of configuring a Shell environment.
119
119
120 Provides init_extensions() and init_code() methods, to be called
120 Provides init_extensions() and init_code() methods, to be called
121 after init_shell(), which must be implemented by subclasses.
121 after init_shell(), which must be implemented by subclasses.
122 """
122 """
123 extensions = List(Unicode, config=True,
123 extensions = List(Unicode, config=True,
124 help="A list of dotted module names of IPython extensions to load."
124 help="A list of dotted module names of IPython extensions to load."
125 )
125 )
126 extra_extension = Unicode('', config=True,
126 extra_extension = Unicode('', config=True,
127 help="dotted module name of an IPython extension to load."
127 help="dotted module name of an IPython extension to load."
128 )
128 )
129 def _extra_extension_changed(self, name, old, new):
129 def _extra_extension_changed(self, name, old, new):
130 if new:
130 if new:
131 # add to self.extensions
131 # add to self.extensions
132 self.extensions.append(new)
132 self.extensions.append(new)
133
133
134 exec_files = List(Unicode, config=True,
134 exec_files = List(Unicode, config=True,
135 help="""List of files to run at IPython startup."""
135 help="""List of files to run at IPython startup."""
136 )
136 )
137 file_to_run = Unicode('', config=True,
137 file_to_run = Unicode('', config=True,
138 help="""A file to be run""")
138 help="""A file to be run""")
139
139
140 exec_lines = List(Unicode, config=True,
140 exec_lines = List(Unicode, config=True,
141 help="""lines of code to run at IPython startup."""
141 help="""lines of code to run at IPython startup."""
142 )
142 )
143 code_to_run = Unicode('', config=True,
143 code_to_run = Unicode('', config=True,
144 help="Execute the given command string."
144 help="Execute the given command string."
145 )
145 )
146 pylab_import_all = Bool(True, config=True,
146 pylab_import_all = Bool(True, config=True,
147 help="""If true, an 'import *' is done from numpy and pylab,
147 help="""If true, an 'import *' is done from numpy and pylab,
148 when using pylab"""
148 when using pylab"""
149 )
149 )
150 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
150 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
151
151
152 def init_shell(self):
152 def init_shell(self):
153 raise NotImplementedError("Override in subclasses")
153 raise NotImplementedError("Override in subclasses")
154
154
155 def init_extensions(self):
155 def init_extensions(self):
156 """Load all IPython extensions in IPythonApp.extensions.
156 """Load all IPython extensions in IPythonApp.extensions.
157
157
158 This uses the :meth:`ExtensionManager.load_extensions` to load all
158 This uses the :meth:`ExtensionManager.load_extensions` to load all
159 the extensions listed in ``self.extensions``.
159 the extensions listed in ``self.extensions``.
160 """
160 """
161 if not self.extensions:
161 if not self.extensions:
162 return
162 return
163 try:
163 try:
164 self.log.debug("Loading IPython extensions...")
164 self.log.debug("Loading IPython extensions...")
165 extensions = self.extensions
165 extensions = self.extensions
166 for ext in extensions:
166 for ext in extensions:
167 try:
167 try:
168 self.log.info("Loading IPython extension: %s" % ext)
168 self.log.info("Loading IPython extension: %s" % ext)
169 self.shell.extension_manager.load_extension(ext)
169 self.shell.extension_manager.load_extension(ext)
170 except:
170 except:
171 self.log.warn("Error in loading extension: %s" % ext)
171 self.log.warn("Error in loading extension: %s" % ext +
172 "\nCheck your config files in %s" % self.profile_dir.location
173 )
172 self.shell.showtraceback()
174 self.shell.showtraceback()
173 except:
175 except:
174 self.log.warn("Unknown error in loading extensions:")
176 self.log.warn("Unknown error in loading extensions:")
175 self.shell.showtraceback()
177 self.shell.showtraceback()
176
178
177 def init_code(self):
179 def init_code(self):
178 """run the pre-flight code, specified via exec_lines"""
180 """run the pre-flight code, specified via exec_lines"""
179 self._run_startup_files()
181 self._run_startup_files()
180 self._run_exec_lines()
182 self._run_exec_lines()
181 self._run_exec_files()
183 self._run_exec_files()
182 self._run_cmd_line_code()
184 self._run_cmd_line_code()
183
185
184 # Hide variables defined here from %who etc.
186 # Hide variables defined here from %who etc.
185 self.shell.user_ns_hidden.update(self.shell.user_ns)
187 self.shell.user_ns_hidden.update(self.shell.user_ns)
186
188
187 def _run_exec_lines(self):
189 def _run_exec_lines(self):
188 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
190 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
189 if not self.exec_lines:
191 if not self.exec_lines:
190 return
192 return
191 try:
193 try:
192 self.log.debug("Running code from IPythonApp.exec_lines...")
194 self.log.debug("Running code from IPythonApp.exec_lines...")
193 for line in self.exec_lines:
195 for line in self.exec_lines:
194 try:
196 try:
195 self.log.info("Running code in user namespace: %s" %
197 self.log.info("Running code in user namespace: %s" %
196 line)
198 line)
197 self.shell.run_cell(line, store_history=False)
199 self.shell.run_cell(line, store_history=False)
198 except:
200 except:
199 self.log.warn("Error in executing line in user "
201 self.log.warn("Error in executing line in user "
200 "namespace: %s" % line)
202 "namespace: %s" % line)
201 self.shell.showtraceback()
203 self.shell.showtraceback()
202 except:
204 except:
203 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
205 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
204 self.shell.showtraceback()
206 self.shell.showtraceback()
205
207
206 def _exec_file(self, fname):
208 def _exec_file(self, fname):
207 try:
209 try:
208 full_filename = filefind(fname, [u'.', self.ipython_dir])
210 full_filename = filefind(fname, [u'.', self.ipython_dir])
209 except IOError as e:
211 except IOError as e:
210 self.log.warn("File not found: %r"%fname)
212 self.log.warn("File not found: %r"%fname)
211 return
213 return
212 # Make sure that the running script gets a proper sys.argv as if it
214 # Make sure that the running script gets a proper sys.argv as if it
213 # were run from a system shell.
215 # were run from a system shell.
214 save_argv = sys.argv
216 save_argv = sys.argv
215 sys.argv = [full_filename] + self.extra_args[1:]
217 sys.argv = [full_filename] + self.extra_args[1:]
216 # protect sys.argv from potential unicode strings on Python 2:
218 # protect sys.argv from potential unicode strings on Python 2:
217 if not py3compat.PY3:
219 if not py3compat.PY3:
218 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
220 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
219 try:
221 try:
220 if os.path.isfile(full_filename):
222 if os.path.isfile(full_filename):
221 if full_filename.endswith('.ipy'):
223 if full_filename.endswith('.ipy'):
222 self.log.info("Running file in user namespace: %s" %
224 self.log.info("Running file in user namespace: %s" %
223 full_filename)
225 full_filename)
224 self.shell.safe_execfile_ipy(full_filename)
226 self.shell.safe_execfile_ipy(full_filename)
225 else:
227 else:
226 # default to python, even without extension
228 # default to python, even without extension
227 self.log.info("Running file in user namespace: %s" %
229 self.log.info("Running file in user namespace: %s" %
228 full_filename)
230 full_filename)
229 # Ensure that __file__ is always defined to match Python behavior
231 # Ensure that __file__ is always defined to match Python behavior
230 self.shell.user_ns['__file__'] = fname
232 self.shell.user_ns['__file__'] = fname
231 try:
233 try:
232 self.shell.safe_execfile(full_filename, self.shell.user_ns)
234 self.shell.safe_execfile(full_filename, self.shell.user_ns)
233 finally:
235 finally:
234 del self.shell.user_ns['__file__']
236 del self.shell.user_ns['__file__']
235 finally:
237 finally:
236 sys.argv = save_argv
238 sys.argv = save_argv
237
239
238 def _run_startup_files(self):
240 def _run_startup_files(self):
239 """Run files from profile startup directory"""
241 """Run files from profile startup directory"""
240 startup_dir = self.profile_dir.startup_dir
242 startup_dir = self.profile_dir.startup_dir
241 startup_files = glob.glob(os.path.join(startup_dir, '*.py'))
243 startup_files = glob.glob(os.path.join(startup_dir, '*.py'))
242 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
244 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
243 if not startup_files:
245 if not startup_files:
244 return
246 return
245
247
246 self.log.debug("Running startup files from %s...", startup_dir)
248 self.log.debug("Running startup files from %s...", startup_dir)
247 try:
249 try:
248 for fname in sorted(startup_files):
250 for fname in sorted(startup_files):
249 self._exec_file(fname)
251 self._exec_file(fname)
250 except:
252 except:
251 self.log.warn("Unknown error in handling startup files:")
253 self.log.warn("Unknown error in handling startup files:")
252 self.shell.showtraceback()
254 self.shell.showtraceback()
253
255
254 def _run_exec_files(self):
256 def _run_exec_files(self):
255 """Run files from IPythonApp.exec_files"""
257 """Run files from IPythonApp.exec_files"""
256 if not self.exec_files:
258 if not self.exec_files:
257 return
259 return
258
260
259 self.log.debug("Running files in IPythonApp.exec_files...")
261 self.log.debug("Running files in IPythonApp.exec_files...")
260 try:
262 try:
261 for fname in self.exec_files:
263 for fname in self.exec_files:
262 self._exec_file(fname)
264 self._exec_file(fname)
263 except:
265 except:
264 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
266 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
265 self.shell.showtraceback()
267 self.shell.showtraceback()
266
268
267 def _run_cmd_line_code(self):
269 def _run_cmd_line_code(self):
268 """Run code or file specified at the command-line"""
270 """Run code or file specified at the command-line"""
269 if self.code_to_run:
271 if self.code_to_run:
270 line = self.code_to_run
272 line = self.code_to_run
271 try:
273 try:
272 self.log.info("Running code given at command line (c=): %s" %
274 self.log.info("Running code given at command line (c=): %s" %
273 line)
275 line)
274 self.shell.run_cell(line, store_history=False)
276 self.shell.run_cell(line, store_history=False)
275 except:
277 except:
276 self.log.warn("Error in executing line in user namespace: %s" %
278 self.log.warn("Error in executing line in user namespace: %s" %
277 line)
279 line)
278 self.shell.showtraceback()
280 self.shell.showtraceback()
279
281
280 # Like Python itself, ignore the second if the first of these is present
282 # Like Python itself, ignore the second if the first of these is present
281 elif self.file_to_run:
283 elif self.file_to_run:
282 fname = self.file_to_run
284 fname = self.file_to_run
283 try:
285 try:
284 self._exec_file(fname)
286 self._exec_file(fname)
285 except:
287 except:
286 self.log.warn("Error in executing file in user namespace: %s" %
288 self.log.warn("Error in executing file in user namespace: %s" %
287 fname)
289 fname)
288 self.shell.showtraceback()
290 self.shell.showtraceback()
289
291
General Comments 0
You need to be logged in to leave comments. Login now