##// END OF EJS Templates
Delete extra auto
Kyle Kelley -
Show More
@@ -1,400 +1,400 b''
1 1 # encoding: utf-8
2 2 """
3 3 A mixin for :class:`~IPython.core.application.Application` classes that
4 4 launch InteractiveShell instances, load extensions, etc.
5 5
6 6 Authors
7 7 -------
8 8
9 9 * Min Ragan-Kelley
10 10 """
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Copyright (C) 2008-2011 The IPython Development Team
14 14 #
15 15 # Distributed under the terms of the BSD License. The full license is in
16 16 # the file COPYING, distributed as part of this software.
17 17 #-----------------------------------------------------------------------------
18 18
19 19 #-----------------------------------------------------------------------------
20 20 # Imports
21 21 #-----------------------------------------------------------------------------
22 22
23 23 from __future__ import absolute_import
24 24
25 25 import glob
26 26 import os
27 27 import sys
28 28
29 29 from IPython.config.application import boolean_flag
30 30 from IPython.config.configurable import Configurable
31 31 from IPython.config.loader import Config
32 32 from IPython.core import pylabtools
33 33 from IPython.utils import py3compat
34 34 from IPython.utils.contexts import preserve_keys
35 35 from IPython.utils.path import filefind
36 36 from IPython.utils.traitlets import (
37 37 Unicode, Instance, List, Bool, CaselessStrEnum
38 38 )
39 39
40 40 #-----------------------------------------------------------------------------
41 41 # Aliases and Flags
42 42 #-----------------------------------------------------------------------------
43 43
44 44 backend_keys = sorted(pylabtools.backends.keys())
45 45 backend_keys.insert(0, 'auto')
46 46
47 47 shell_flags = {}
48 48
49 49 addflag = lambda *args: shell_flags.update(boolean_flag(*args))
50 50 addflag('autoindent', 'InteractiveShell.autoindent',
51 51 'Turn on autoindenting.', 'Turn off autoindenting.'
52 52 )
53 53 addflag('automagic', 'InteractiveShell.automagic',
54 54 """Turn on the auto calling of magic commands. Type %%magic at the
55 55 IPython prompt for more information.""",
56 56 'Turn off the auto calling of magic commands.'
57 57 )
58 58 addflag('pdb', 'InteractiveShell.pdb',
59 59 "Enable auto calling the pdb debugger after every exception.",
60 60 "Disable auto calling the pdb debugger after every exception."
61 61 )
62 62 # pydb flag doesn't do any config, as core.debugger switches on import,
63 63 # which is before parsing. This just allows the flag to be passed.
64 64 shell_flags.update(dict(
65 65 pydb = ({},
66 66 """Use the third party 'pydb' package as debugger, instead of pdb.
67 67 Requires that pydb is installed."""
68 68 )
69 69 ))
70 70 addflag('pprint', 'PlainTextFormatter.pprint',
71 71 "Enable auto pretty printing of results.",
72 "Disable auto auto pretty printing of results."
72 "Disable auto pretty printing of results."
73 73 )
74 74 addflag('color-info', 'InteractiveShell.color_info',
75 75 """IPython can display information about objects via a set of func-
76 76 tions, and optionally can use colors for this, syntax highlighting
77 77 source code and various other elements. However, because this
78 78 information is passed through a pager (like 'less') and many pagers get
79 79 confused with color codes, this option is off by default. You can test
80 80 it and turn it on permanently in your ipython_config.py file if it
81 81 works for you. Test it and turn it on permanently if it works with
82 82 your system. The magic function %%color_info allows you to toggle this
83 83 interactively for testing.""",
84 84 "Disable using colors for info related things."
85 85 )
86 86 addflag('deep-reload', 'InteractiveShell.deep_reload',
87 87 """Enable deep (recursive) reloading by default. IPython can use the
88 88 deep_reload module which reloads changes in modules recursively (it
89 89 replaces the reload() function, so you don't need to change anything to
90 90 use it). deep_reload() forces a full reload of modules whose code may
91 91 have changed, which the default reload() function does not. When
92 92 deep_reload is off, IPython will use the normal reload(), but
93 93 deep_reload will still be available as dreload(). This feature is off
94 94 by default [which means that you have both normal reload() and
95 95 dreload()].""",
96 96 "Disable deep (recursive) reloading by default."
97 97 )
98 98 nosep_config = Config()
99 99 nosep_config.InteractiveShell.separate_in = ''
100 100 nosep_config.InteractiveShell.separate_out = ''
101 101 nosep_config.InteractiveShell.separate_out2 = ''
102 102
103 103 shell_flags['nosep']=(nosep_config, "Eliminate all spacing between prompts.")
104 104 shell_flags['pylab'] = (
105 105 {'InteractiveShellApp' : {'pylab' : 'auto'}},
106 106 """Pre-load matplotlib and numpy for interactive use with
107 107 the default matplotlib backend."""
108 108 )
109 109 shell_flags['matplotlib'] = (
110 110 {'InteractiveShellApp' : {'matplotlib' : 'auto'}},
111 111 """Configure matplotlib for interactive use with
112 112 the default matplotlib backend."""
113 113 )
114 114
115 115 # it's possible we don't want short aliases for *all* of these:
116 116 shell_aliases = dict(
117 117 autocall='InteractiveShell.autocall',
118 118 colors='InteractiveShell.colors',
119 119 logfile='InteractiveShell.logfile',
120 120 logappend='InteractiveShell.logappend',
121 121 c='InteractiveShellApp.code_to_run',
122 122 m='InteractiveShellApp.module_to_run',
123 123 ext='InteractiveShellApp.extra_extension',
124 124 gui='InteractiveShellApp.gui',
125 125 pylab='InteractiveShellApp.pylab',
126 126 matplotlib='InteractiveShellApp.matplotlib',
127 127 )
128 128 shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
129 129
130 130 #-----------------------------------------------------------------------------
131 131 # Main classes and functions
132 132 #-----------------------------------------------------------------------------
133 133
134 134 class InteractiveShellApp(Configurable):
135 135 """A Mixin for applications that start InteractiveShell instances.
136 136
137 137 Provides configurables for loading extensions and executing files
138 138 as part of configuring a Shell environment.
139 139
140 140 The following methods should be called by the :meth:`initialize` method
141 141 of the subclass:
142 142
143 143 - :meth:`init_path`
144 144 - :meth:`init_shell` (to be implemented by the subclass)
145 145 - :meth:`init_gui_pylab`
146 146 - :meth:`init_extensions`
147 147 - :meth:`init_code`
148 148 """
149 149 extensions = List(Unicode, config=True,
150 150 help="A list of dotted module names of IPython extensions to load."
151 151 )
152 152 extra_extension = Unicode('', config=True,
153 153 help="dotted module name of an IPython extension to load."
154 154 )
155 155 def _extra_extension_changed(self, name, old, new):
156 156 if new:
157 157 # add to self.extensions
158 158 self.extensions.append(new)
159 159
160 160 # Extensions that are always loaded (not configurable)
161 161 default_extensions = List(Unicode, [u'storemagic'], config=False)
162 162
163 163 exec_files = List(Unicode, config=True,
164 164 help="""List of files to run at IPython startup."""
165 165 )
166 166 file_to_run = Unicode('', config=True,
167 167 help="""A file to be run""")
168 168
169 169 exec_lines = List(Unicode, config=True,
170 170 help="""lines of code to run at IPython startup."""
171 171 )
172 172 code_to_run = Unicode('', config=True,
173 173 help="Execute the given command string."
174 174 )
175 175 module_to_run = Unicode('', config=True,
176 176 help="Run the module as a script."
177 177 )
178 178 gui = CaselessStrEnum(('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx'), config=True,
179 179 help="Enable GUI event loop integration ('qt', 'wx', 'gtk', 'glut', 'pyglet', 'osx')."
180 180 )
181 181 matplotlib = CaselessStrEnum(backend_keys,
182 182 config=True,
183 183 help="""Configure matplotlib for interactive use with
184 184 the default matplotlib backend."""
185 185 )
186 186 pylab = CaselessStrEnum(backend_keys,
187 187 config=True,
188 188 help="""Pre-load matplotlib and numpy for interactive use,
189 189 selecting a particular matplotlib backend and loop integration.
190 190 """
191 191 )
192 192 pylab_import_all = Bool(True, config=True,
193 193 help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
194 194 and an 'import *' is done from numpy and pylab, when using pylab mode.
195 195
196 196 When False, pylab mode should not import any names into the user namespace.
197 197 """
198 198 )
199 199 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
200 200
201 201 def init_path(self):
202 202 """Add current working directory, '', to sys.path"""
203 203 if sys.path[0] != '':
204 204 sys.path.insert(0, '')
205 205
206 206 def init_shell(self):
207 207 raise NotImplementedError("Override in subclasses")
208 208
209 209 def init_gui_pylab(self):
210 210 """Enable GUI event loop integration, taking pylab into account."""
211 211 enable = False
212 212 shell = self.shell
213 213 if self.pylab:
214 214 enable = shell.enable_pylab
215 215 key = self.pylab
216 216 elif self.matplotlib:
217 217 enable = shell.enable_matplotlib
218 218 key = self.matplotlib
219 219 elif self.gui:
220 220 enable = shell.enable_gui
221 221 key = self.gui
222 222
223 223 if not enable:
224 224 return
225 225
226 226 try:
227 227 r = enable(key)
228 228 except ImportError:
229 229 self.log.warn("Eventloop or matplotlib integration failed. Is matplotlib installed?")
230 230 self.shell.showtraceback()
231 231 return
232 232 except Exception:
233 233 self.log.warn("GUI event loop or pylab initialization failed")
234 234 self.shell.showtraceback()
235 235 return
236 236
237 237 if isinstance(r, tuple):
238 238 gui, backend = r[:2]
239 239 self.log.info("Enabling GUI event loop integration, "
240 240 "eventloop=%s, matplotlib=%s", gui, backend)
241 241 if key == "auto":
242 242 print ("using matplotlib backend: %s" % backend)
243 243 else:
244 244 gui = r
245 245 self.log.info("Enabling GUI event loop integration, "
246 246 "eventloop=%s", gui)
247 247
248 248 def init_extensions(self):
249 249 """Load all IPython extensions in IPythonApp.extensions.
250 250
251 251 This uses the :meth:`ExtensionManager.load_extensions` to load all
252 252 the extensions listed in ``self.extensions``.
253 253 """
254 254 try:
255 255 self.log.debug("Loading IPython extensions...")
256 256 extensions = self.default_extensions + self.extensions
257 257 for ext in extensions:
258 258 try:
259 259 self.log.info("Loading IPython extension: %s" % ext)
260 260 self.shell.extension_manager.load_extension(ext)
261 261 except:
262 262 self.log.warn("Error in loading extension: %s" % ext +
263 263 "\nCheck your config files in %s" % self.profile_dir.location
264 264 )
265 265 self.shell.showtraceback()
266 266 except:
267 267 self.log.warn("Unknown error in loading extensions:")
268 268 self.shell.showtraceback()
269 269
270 270 def init_code(self):
271 271 """run the pre-flight code, specified via exec_lines"""
272 272 self._run_startup_files()
273 273 self._run_exec_lines()
274 274 self._run_exec_files()
275 275 self._run_cmd_line_code()
276 276 self._run_module()
277 277
278 278 # flush output, so itwon't be attached to the first cell
279 279 sys.stdout.flush()
280 280 sys.stderr.flush()
281 281
282 282 # Hide variables defined here from %who etc.
283 283 self.shell.user_ns_hidden.update(self.shell.user_ns)
284 284
285 285 def _run_exec_lines(self):
286 286 """Run lines of code in IPythonApp.exec_lines in the user's namespace."""
287 287 if not self.exec_lines:
288 288 return
289 289 try:
290 290 self.log.debug("Running code from IPythonApp.exec_lines...")
291 291 for line in self.exec_lines:
292 292 try:
293 293 self.log.info("Running code in user namespace: %s" %
294 294 line)
295 295 self.shell.run_cell(line, store_history=False)
296 296 except:
297 297 self.log.warn("Error in executing line in user "
298 298 "namespace: %s" % line)
299 299 self.shell.showtraceback()
300 300 except:
301 301 self.log.warn("Unknown error in handling IPythonApp.exec_lines:")
302 302 self.shell.showtraceback()
303 303
304 304 def _exec_file(self, fname):
305 305 try:
306 306 full_filename = filefind(fname, [u'.', self.ipython_dir])
307 307 except IOError as e:
308 308 self.log.warn("File not found: %r"%fname)
309 309 return
310 310 # Make sure that the running script gets a proper sys.argv as if it
311 311 # were run from a system shell.
312 312 save_argv = sys.argv
313 313 sys.argv = [full_filename] + self.extra_args[1:]
314 314 # protect sys.argv from potential unicode strings on Python 2:
315 315 if not py3compat.PY3:
316 316 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
317 317 try:
318 318 if os.path.isfile(full_filename):
319 319 self.log.info("Running file in user namespace: %s" %
320 320 full_filename)
321 321 # Ensure that __file__ is always defined to match Python
322 322 # behavior.
323 323 with preserve_keys(self.shell.user_ns, '__file__'):
324 324 self.shell.user_ns['__file__'] = fname
325 325 if full_filename.endswith('.ipy'):
326 326 self.shell.safe_execfile_ipy(full_filename)
327 327 else:
328 328 # default to python, even without extension
329 329 self.shell.safe_execfile(full_filename,
330 330 self.shell.user_ns)
331 331 finally:
332 332 sys.argv = save_argv
333 333
334 334 def _run_startup_files(self):
335 335 """Run files from profile startup directory"""
336 336 startup_dir = self.profile_dir.startup_dir
337 337 startup_files = []
338 338 if os.environ.get('PYTHONSTARTUP', False):
339 339 startup_files.append(os.environ['PYTHONSTARTUP'])
340 340 startup_files += glob.glob(os.path.join(startup_dir, '*.py'))
341 341 startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
342 342 if not startup_files:
343 343 return
344 344
345 345 self.log.debug("Running startup files from %s...", startup_dir)
346 346 try:
347 347 for fname in sorted(startup_files):
348 348 self._exec_file(fname)
349 349 except:
350 350 self.log.warn("Unknown error in handling startup files:")
351 351 self.shell.showtraceback()
352 352
353 353 def _run_exec_files(self):
354 354 """Run files from IPythonApp.exec_files"""
355 355 if not self.exec_files:
356 356 return
357 357
358 358 self.log.debug("Running files in IPythonApp.exec_files...")
359 359 try:
360 360 for fname in self.exec_files:
361 361 self._exec_file(fname)
362 362 except:
363 363 self.log.warn("Unknown error in handling IPythonApp.exec_files:")
364 364 self.shell.showtraceback()
365 365
366 366 def _run_cmd_line_code(self):
367 367 """Run code or file specified at the command-line"""
368 368 if self.code_to_run:
369 369 line = self.code_to_run
370 370 try:
371 371 self.log.info("Running code given at command line (c=): %s" %
372 372 line)
373 373 self.shell.run_cell(line, store_history=False)
374 374 except:
375 375 self.log.warn("Error in executing line in user namespace: %s" %
376 376 line)
377 377 self.shell.showtraceback()
378 378
379 379 # Like Python itself, ignore the second if the first of these is present
380 380 elif self.file_to_run:
381 381 fname = self.file_to_run
382 382 try:
383 383 self._exec_file(fname)
384 384 except:
385 385 self.log.warn("Error in executing file in user namespace: %s" %
386 386 fname)
387 387 self.shell.showtraceback()
388 388
389 389 def _run_module(self):
390 390 """Run module specified at the command-line."""
391 391 if self.module_to_run:
392 392 # Make sure that the module gets a proper sys.argv as if it were
393 393 # run using `python -m`.
394 394 save_argv = sys.argv
395 395 sys.argv = [sys.executable] + self.extra_args
396 396 try:
397 397 self.shell.safe_run_module(self.module_to_run,
398 398 self.shell.user_ns)
399 399 finally:
400 400 sys.argv = save_argv
General Comments 0
You need to be logged in to leave comments. Login now