##// END OF EJS Templates
Fix comment which breaks Emacs syntax highlighting.
Bradley M. Froehle -
Show More
@@ -1,319 +1,319 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 m='InteractiveShellApp.module_to_run',
106 m='InteractiveShellApp.module_to_run',
107 ext='InteractiveShellApp.extra_extension',
107 ext='InteractiveShellApp.extra_extension',
108 )
108 )
109 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
109 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
110
110
111 #-----------------------------------------------------------------------------
111 #-----------------------------------------------------------------------------
112 # Main classes and functions
112 # Main classes and functions
113 #-----------------------------------------------------------------------------
113 #-----------------------------------------------------------------------------
114
114
115 class InteractiveShellApp(Configurable):
115 class InteractiveShellApp(Configurable):
116 """A Mixin for applications that start InteractiveShell instances.
116 """A Mixin for applications that start InteractiveShell instances.
117
117
118 Provides configurables for loading extensions and executing files
118 Provides configurables for loading extensions and executing files
119 as part of configuring a Shell environment.
119 as part of configuring a Shell environment.
120
120
121 Provides init_path(), to be called before, and init_extensions() and
121 Provides init_path(), to be called before, and init_extensions() and
122 init_code() methods, to be called after init_shell(), which must be
122 init_code() methods, to be called after init_shell(), which must be
123 implemented by subclasses.
123 implemented by subclasses.
124 """
124 """
125 extensions = List(Unicode, config=True,
125 extensions = List(Unicode, config=True,
126 help="A list of dotted module names of IPython extensions to load."
126 help="A list of dotted module names of IPython extensions to load."
127 )
127 )
128 extra_extension = Unicode('', config=True,
128 extra_extension = Unicode('', config=True,
129 help="dotted module name of an IPython extension to load."
129 help="dotted module name of an IPython extension to load."
130 )
130 )
131 def _extra_extension_changed(self, name, old, new):
131 def _extra_extension_changed(self, name, old, new):
132 if new:
132 if new:
133 # add to self.extensions
133 # add to self.extensions
134 self.extensions.append(new)
134 self.extensions.append(new)
135
135
136 # Extensions that are always loaded (not configurable)
136 # Extensions that are always loaded (not configurable)
137 default_extensions = List(Unicode, [u'storemagic'], config=False)
137 default_extensions = List(Unicode, [u'storemagic'], config=False)
138
138
139 exec_files = List(Unicode, config=True,
139 exec_files = List(Unicode, config=True,
140 help="""List of files to run at IPython startup."""
140 help="""List of files to run at IPython startup."""
141 )
141 )
142 file_to_run = Unicode('', config=True,
142 file_to_run = Unicode('', config=True,
143 help="""A file to be run""")
143 help="""A file to be run""")
144
144
145 exec_lines = List(Unicode, config=True,
145 exec_lines = List(Unicode, config=True,
146 help="""lines of code to run at IPython startup."""
146 help="""lines of code to run at IPython startup."""
147 )
147 )
148 code_to_run = Unicode('', config=True,
148 code_to_run = Unicode('', config=True,
149 help="Execute the given command string."
149 help="Execute the given command string."
150 )
150 )
151 module_to_run = Unicode('', config=True,
151 module_to_run = Unicode('', config=True,
152 help="Run the module as a script."
152 help="Run the module as a script."
153 )
153 )
154 pylab_import_all = Bool(True, config=True,
154 pylab_import_all = Bool(True, config=True,
155 help="""If true, an 'import *' is done from numpy and pylab,
155 help="""If true, an 'import *' is done from numpy and pylab,
156 when using pylab"""
156 when using pylab"""
157 )
157 )
158 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
158 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
159
159
160 def init_path(self):
160 def init_path(self):
161 """Add current working directory, '', to sys.path"""
161 """Add current working directory, '', to sys.path"""
162 if sys.path[0] != '':
162 if sys.path[0] != '':
163 sys.path.insert(0, '')
163 sys.path.insert(0, '')
164
164
165 def init_shell(self):
165 def init_shell(self):
166 raise NotImplementedError("Override in subclasses")
166 raise NotImplementedError("Override in subclasses")
167
167
168 def init_extensions(self):
168 def init_extensions(self):
169 """Load all IPython extensions in IPythonApp.extensions.
169 """Load all IPython extensions in IPythonApp.extensions.
170
170
171 This uses the :meth:`ExtensionManager.load_extensions` to load all
171 This uses the :meth:`ExtensionManager.load_extensions` to load all
172 the extensions listed in ``self.extensions``.
172 the extensions listed in ``self.extensions``.
173 """
173 """
174 try:
174 try:
175 self.log.debug("Loading IPython extensions...")
175 self.log.debug("Loading IPython extensions...")
176 extensions = self.default_extensions + self.extensions
176 extensions = self.default_extensions + self.extensions
177 for ext in extensions:
177 for ext in extensions:
178 try:
178 try:
179 self.log.info("Loading IPython extension: %s" % ext)
179 self.log.info("Loading IPython extension: %s" % ext)
180 self.shell.extension_manager.load_extension(ext)
180 self.shell.extension_manager.load_extension(ext)
181 except:
181 except:
182 self.log.warn("Error in loading extension: %s" % ext +
182 self.log.warn("Error in loading extension: %s" % ext +
183 "\nCheck your config files in %s" % self.profile_dir.location
183 "\nCheck your config files in %s" % self.profile_dir.location
184 )
184 )
185 self.shell.showtraceback()
185 self.shell.showtraceback()
186 except:
186 except:
187 self.log.warn("Unknown error in loading extensions:")
187 self.log.warn("Unknown error in loading extensions:")
188 self.shell.showtraceback()
188 self.shell.showtraceback()
189
189
190 def init_code(self):
190 def init_code(self):
191 """run the pre-flight code, specified via exec_lines"""
191 """run the pre-flight code, specified via exec_lines"""
192 self._run_startup_files()
192 self._run_startup_files()
193 self._run_exec_lines()
193 self._run_exec_lines()
194 self._run_exec_files()
194 self._run_exec_files()
195 self._run_cmd_line_code()
195 self._run_cmd_line_code()
196 self._run_module()
196 self._run_module()
197
197
198 # flush output, so itwon't be attached to the first cell
198 # flush output, so itwon't be attached to the first cell
199 sys.stdout.flush()
199 sys.stdout.flush()
200 sys.stderr.flush()
200 sys.stderr.flush()
201
201
202 # Hide variables defined here from %who etc.
202 # Hide variables defined here from %who etc.
203 self.shell.user_ns_hidden.update(self.shell.user_ns)
203 self.shell.user_ns_hidden.update(self.shell.user_ns)
204
204
205 def _run_exec_lines(self):
205 def _run_exec_lines(self):
206 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
206 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
207 if not self.exec_lines:
207 if not self.exec_lines:
208 return
208 return
209 try:
209 try:
210 self.log.debug("Running code from IPythonApp.exec_lines...")
210 self.log.debug("Running code from IPythonApp.exec_lines...")
211 for line in self.exec_lines:
211 for line in self.exec_lines:
212 try:
212 try:
213 self.log.info("Running code in user namespace: %s" %
213 self.log.info("Running code in user namespace: %s" %
214 line)
214 line)
215 self.shell.run_cell(line, store_history=False)
215 self.shell.run_cell(line, store_history=False)
216 except:
216 except:
217 self.log.warn("Error in executing line in user "
217 self.log.warn("Error in executing line in user "
218 "namespace: %s" % line)
218 "namespace: %s" % line)
219 self.shell.showtraceback()
219 self.shell.showtraceback()
220 except:
220 except:
221 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
221 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
222 self.shell.showtraceback()
222 self.shell.showtraceback()
223
223
224 def _exec_file(self, fname):
224 def _exec_file(self, fname):
225 try:
225 try:
226 full_filename = filefind(fname, [u'.', self.ipython_dir])
226 full_filename = filefind(fname, [u'.', self.ipython_dir])
227 except IOError as e:
227 except IOError as e:
228 self.log.warn("File not found: %r"%fname)
228 self.log.warn("File not found: %r"%fname)
229 return
229 return
230 # Make sure that the running script gets a proper sys.argv as if it
230 # Make sure that the running script gets a proper sys.argv as if it
231 # were run from a system shell.
231 # were run from a system shell.
232 save_argv = sys.argv
232 save_argv = sys.argv
233 sys.argv = [full_filename] + self.extra_args[1:]
233 sys.argv = [full_filename] + self.extra_args[1:]
234 # protect sys.argv from potential unicode strings on Python 2:
234 # protect sys.argv from potential unicode strings on Python 2:
235 if not py3compat.PY3:
235 if not py3compat.PY3:
236 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
236 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
237 try:
237 try:
238 if os.path.isfile(full_filename):
238 if os.path.isfile(full_filename):
239 if full_filename.endswith('.ipy'):
239 if full_filename.endswith('.ipy'):
240 self.log.info("Running file in user namespace: %s" %
240 self.log.info("Running file in user namespace: %s" %
241 full_filename)
241 full_filename)
242 self.shell.safe_execfile_ipy(full_filename)
242 self.shell.safe_execfile_ipy(full_filename)
243 else:
243 else:
244 # default to python, even without extension
244 # default to python, even without extension
245 self.log.info("Running file in user namespace: %s" %
245 self.log.info("Running file in user namespace: %s" %
246 full_filename)
246 full_filename)
247 # Ensure that __file__ is always defined to match Python behavior
247 # Ensure that __file__ is always defined to match Python behavior
248 self.shell.user_ns['__file__'] = fname
248 self.shell.user_ns['__file__'] = fname
249 try:
249 try:
250 self.shell.safe_execfile(full_filename, self.shell.user_ns)
250 self.shell.safe_execfile(full_filename, self.shell.user_ns)
251 finally:
251 finally:
252 del self.shell.user_ns['__file__']
252 del self.shell.user_ns['__file__']
253 finally:
253 finally:
254 sys.argv = save_argv
254 sys.argv = save_argv
255
255
256 def _run_startup_files(self):
256 def _run_startup_files(self):
257 """Run files from profile startup directory"""
257 """Run files from profile startup directory"""
258 startup_dir = self.profile_dir.startup_dir
258 startup_dir = self.profile_dir.startup_dir
259 startup_files = glob.glob(os.path.join(startup_dir, '*.py'))
259 startup_files = glob.glob(os.path.join(startup_dir, '*.py'))
260 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
260 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
261 if not startup_files:
261 if not startup_files:
262 return
262 return
263
263
264 self.log.debug("Running startup files from %s...", startup_dir)
264 self.log.debug("Running startup files from %s...", startup_dir)
265 try:
265 try:
266 for fname in sorted(startup_files):
266 for fname in sorted(startup_files):
267 self._exec_file(fname)
267 self._exec_file(fname)
268 except:
268 except:
269 self.log.warn("Unknown error in handling startup files:")
269 self.log.warn("Unknown error in handling startup files:")
270 self.shell.showtraceback()
270 self.shell.showtraceback()
271
271
272 def _run_exec_files(self):
272 def _run_exec_files(self):
273 """Run files from IPythonApp.exec_files"""
273 """Run files from IPythonApp.exec_files"""
274 if not self.exec_files:
274 if not self.exec_files:
275 return
275 return
276
276
277 self.log.debug("Running files in IPythonApp.exec_files...")
277 self.log.debug("Running files in IPythonApp.exec_files...")
278 try:
278 try:
279 for fname in self.exec_files:
279 for fname in self.exec_files:
280 self._exec_file(fname)
280 self._exec_file(fname)
281 except:
281 except:
282 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
282 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
283 self.shell.showtraceback()
283 self.shell.showtraceback()
284
284
285 def _run_cmd_line_code(self):
285 def _run_cmd_line_code(self):
286 """Run code or file specified at the command-line"""
286 """Run code or file specified at the command-line"""
287 if self.code_to_run:
287 if self.code_to_run:
288 line = self.code_to_run
288 line = self.code_to_run
289 try:
289 try:
290 self.log.info("Running code given at command line (c=): %s" %
290 self.log.info("Running code given at command line (c=): %s" %
291 line)
291 line)
292 self.shell.run_cell(line, store_history=False)
292 self.shell.run_cell(line, store_history=False)
293 except:
293 except:
294 self.log.warn("Error in executing line in user namespace: %s" %
294 self.log.warn("Error in executing line in user namespace: %s" %
295 line)
295 line)
296 self.shell.showtraceback()
296 self.shell.showtraceback()
297
297
298 # Like Python itself, ignore the second if the first of these is present
298 # Like Python itself, ignore the second if the first of these is present
299 elif self.file_to_run:
299 elif self.file_to_run:
300 fname = self.file_to_run
300 fname = self.file_to_run
301 try:
301 try:
302 self._exec_file(fname)
302 self._exec_file(fname)
303 except:
303 except:
304 self.log.warn("Error in executing file in user namespace: %s" %
304 self.log.warn("Error in executing file in user namespace: %s" %
305 fname)
305 fname)
306 self.shell.showtraceback()
306 self.shell.showtraceback()
307
307
308 def _run_module(self):
308 def _run_module(self):
309 """Run module specified at the command-line."""
309 """Run module specified at the command-line."""
310 if self.module_to_run:
310 if self.module_to_run:
311 # Make sure that the module gets a proper sys.argv as if it were
311 # Make sure that the module gets a proper sys.argv as if it were
312 # run using `python -m`.
312 # run using `python -m`.
313 save_argv = sys.argv
313 save_argv = sys.argv
314 sys.argv = [sys.executable] + self.extra_args
314 sys.argv = [sys.executable] + self.extra_args
315 try:
315 try:
316 self.shell.safe_run_module(self.module_to_run,
316 self.shell.safe_run_module(self.module_to_run,
317 self.shell.user_ns)
317 self.shell.user_ns)
318 finally:
318 finally:
319 sys.argv = save_argv
319 sys.argv = save_argv
General Comments 0
You need to be logged in to leave comments. Login now