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