##// END OF EJS Templates
Remove "\M-" readline bindings...
MinRK -
Show More
@@ -1,165 +1,165 b''
1 1 # Get the config being loaded so we can set attributes on it
2 2 c = get_config()
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Global options
6 6 #-----------------------------------------------------------------------------
7 7
8 8 # c.Global.display_banner = True
9 9
10 10 # c.Global.classic = False
11 11
12 12 # c.Global.nosep = True
13 13
14 14 # If you still use multiple versions of IPytho on the same machine,
15 15 # set this to True to suppress warnings about old configuration files
16 16 # c.Global.ignore_old_config = False
17 17
18 18 # Set this to determine the detail of what is logged at startup.
19 19 # The default is 30 and possible values are 0,10,20,30,40,50.
20 20 # c.Global.log_level = 20
21 21
22 22 # This should be a list of importable Python modules that have an
23 23 # load_ipython_extension(ip) method. This method gets called when the extension
24 24 # is loaded. You can put your extensions anywhere they can be imported
25 25 # but we add the extensions subdir of the ipython directory to sys.path
26 26 # during extension loading, so you can put them there as well.
27 27 # c.Global.extensions = [
28 28 # 'myextension'
29 29 # ]
30 30
31 31 # These lines are run in IPython in the user's namespace after extensions
32 32 # are loaded. They can contain full IPython syntax with magics etc.
33 33 # c.Global.exec_lines = [
34 34 # 'import numpy',
35 35 # 'a = 10; b = 20',
36 36 # '1/0'
37 37 # ]
38 38
39 39 # These files are run in IPython in the user's namespace. Files with a .py
40 40 # extension need to be pure Python. Files with a .ipy extension can have
41 41 # custom IPython syntax (like magics, etc.).
42 42 # These files need to be in the cwd, the ipython_dir or be absolute paths.
43 43 # c.Global.exec_files = [
44 44 # 'mycode.py',
45 45 # 'fancy.ipy'
46 46 # ]
47 47
48 48 #-----------------------------------------------------------------------------
49 49 # InteractiveShell options
50 50 #-----------------------------------------------------------------------------
51 51
52 52 # c.InteractiveShell.autocall = 1
53 53
54 54 # c.TerminalInteractiveShell.autoedit_syntax = False
55 55
56 56 # c.InteractiveShell.autoindent = True
57 57
58 58 # c.InteractiveShell.automagic = False
59 59
60 60 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
61 61
62 62 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
63 63
64 64 # c.InteractiveShell.cache_size = 1000
65 65
66 66 # c.InteractiveShell.colors = 'LightBG'
67 67
68 68 # c.InteractiveShell.color_info = True
69 69
70 70 # c.TerminalInteractiveShell.confirm_exit = True
71 71
72 72 # c.InteractiveShell.deep_reload = False
73 73
74 74 # c.TerminalInteractiveShell.editor = 'nano'
75 75
76 76 # c.InteractiveShell.logstart = True
77 77
78 78 # c.InteractiveShell.logfile = u'ipython_log.py'
79 79
80 80 # c.InteractiveShell.logappend = u'mylog.py'
81 81
82 82 # c.InteractiveShell.object_info_string_level = 0
83 83
84 84 # c.TerminalInteractiveShell.pager = 'less'
85 85
86 86 # c.InteractiveShell.pdb = False
87 87
88 88 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
89 89 # c.InteractiveShell.prompt_in2 = ' .\D.: '
90 90 # c.InteractiveShell.prompt_out = 'Out[\#]: '
91 91 # c.InteractiveShell.prompts_pad_left = True
92 92
93 93 # c.InteractiveShell.quiet = False
94 94
95 95 # c.InteractiveShell.history_length = 10000
96 96
97 97 # Readline
98 98 # c.InteractiveShell.readline_use = True
99 99
100 # be careful with meta-key ('\M-<x>') bindings, because
101 # they conflict with 8-bit encodings (e.g. UTF8)
102
100 103 # c.InteractiveShell.readline_parse_and_bind = [
101 104 # 'tab: complete',
102 105 # '"\C-l": possible-completions',
103 106 # 'set show-all-if-ambiguous on',
104 107 # '"\C-o": tab-insert',
105 # '"\M-i": " "',
106 # '"\M-o": "\d\d\d\d"',
107 # '"\M-I": "\d\d\d\d"',
108 108 # '"\C-r": reverse-search-history',
109 109 # '"\C-s": forward-search-history',
110 110 # '"\C-p": history-search-backward',
111 111 # '"\C-n": history-search-forward',
112 112 # '"\e[A": history-search-backward',
113 113 # '"\e[B": history-search-forward',
114 114 # '"\C-k": kill-line',
115 115 # '"\C-u": unix-line-discard',
116 116 # ]
117 117 # c.InteractiveShell.readline_remove_delims = '-/~'
118 118 # c.InteractiveShell.readline_merge_completions = True
119 119 # c.InteractiveShell.readline_omit__names = 0
120 120
121 121 # c.TerminalInteractiveShell.screen_length = 0
122 122
123 123 # c.InteractiveShell.separate_in = '\n'
124 124 # c.InteractiveShell.separate_out = ''
125 125 # c.InteractiveShell.separate_out2 = ''
126 126
127 127 # c.TerminalInteractiveShell.term_title = False
128 128
129 129 # c.InteractiveShell.wildcards_case_sensitive = True
130 130
131 131 # c.InteractiveShell.xmode = 'Context'
132 132
133 133 #-----------------------------------------------------------------------------
134 134 # Formatter and display options
135 135 #-----------------------------------------------------------------------------
136 136
137 137 # c.PlainTextFormatter.pprint = True
138 138
139 139 #-----------------------------------------------------------------------------
140 140 # PrefilterManager options
141 141 #-----------------------------------------------------------------------------
142 142
143 143 # c.PrefilterManager.multi_line_specials = True
144 144
145 145 #-----------------------------------------------------------------------------
146 146 # AliasManager options
147 147 #-----------------------------------------------------------------------------
148 148
149 149 # Do this to disable all defaults
150 150 # c.AliasManager.default_aliases = []
151 151
152 152 # c.AliasManager.user_aliases = [
153 153 # ('foo', 'echo Hi')
154 154 # ]
155 155
156 156 #-----------------------------------------------------------------------------
157 157 # HistoryManager options
158 158 #-----------------------------------------------------------------------------
159 159
160 160 # Enable logging output as well as input to the database.
161 161 # c.HistoryManager.db_log_output = False
162 162
163 163 # Only write to the database every n commands - this can save disk
164 164 # access (and hence power) over the default of writing on every command.
165 165 # c.HistoryManager.db_cache_size = 0
@@ -1,2435 +1,2433 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import with_statement
18 18 from __future__ import absolute_import
19 19
20 20 import __builtin__
21 21 import __future__
22 22 import abc
23 23 import ast
24 24 import atexit
25 25 import codeop
26 26 import inspect
27 27 import os
28 28 import re
29 29 import sys
30 30 import tempfile
31 31 import types
32 32 from contextlib import nested
33 33
34 34 from IPython.config.configurable import Configurable
35 35 from IPython.core import debugger, oinspect
36 36 from IPython.core import history as ipcorehist
37 37 from IPython.core import page
38 38 from IPython.core import prefilter
39 39 from IPython.core import shadowns
40 40 from IPython.core import ultratb
41 41 from IPython.core.alias import AliasManager, AliasError
42 42 from IPython.core.autocall import ExitAutocall
43 43 from IPython.core.builtin_trap import BuiltinTrap
44 44 from IPython.core.compilerop import CachingCompiler
45 45 from IPython.core.display_trap import DisplayTrap
46 46 from IPython.core.displayhook import DisplayHook
47 47 from IPython.core.displaypub import DisplayPublisher
48 48 from IPython.core.error import TryNext, UsageError
49 49 from IPython.core.extensions import ExtensionManager
50 50 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
51 51 from IPython.core.formatters import DisplayFormatter
52 52 from IPython.core.history import HistoryManager
53 53 from IPython.core.inputsplitter import IPythonInputSplitter
54 54 from IPython.core.logger import Logger
55 55 from IPython.core.macro import Macro
56 56 from IPython.core.magic import Magic
57 57 from IPython.core.payload import PayloadManager
58 58 from IPython.core.plugin import PluginManager
59 59 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
60 60 from IPython.external.Itpl import ItplNS
61 61 from IPython.utils import PyColorize
62 62 from IPython.utils import io
63 63 from IPython.utils.doctestreload import doctest_reload
64 64 from IPython.utils.io import ask_yes_no, rprint
65 65 from IPython.utils.ipstruct import Struct
66 66 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
67 67 from IPython.utils.pickleshare import PickleShareDB
68 68 from IPython.utils.process import system, getoutput
69 69 from IPython.utils.strdispatch import StrDispatch
70 70 from IPython.utils.syspathcontext import prepended_to_syspath
71 71 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
72 72 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
73 73 List, Unicode, Instance, Type)
74 74 from IPython.utils.warn import warn, error, fatal
75 75 import IPython.core.hooks
76 76
77 77 #-----------------------------------------------------------------------------
78 78 # Globals
79 79 #-----------------------------------------------------------------------------
80 80
81 81 # compiled regexps for autoindent management
82 82 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
83 83
84 84 #-----------------------------------------------------------------------------
85 85 # Utilities
86 86 #-----------------------------------------------------------------------------
87 87
88 88 # store the builtin raw_input globally, and use this always, in case user code
89 89 # overwrites it (like wx.py.PyShell does)
90 90 raw_input_original = raw_input
91 91
92 92 def softspace(file, newvalue):
93 93 """Copied from code.py, to remove the dependency"""
94 94
95 95 oldvalue = 0
96 96 try:
97 97 oldvalue = file.softspace
98 98 except AttributeError:
99 99 pass
100 100 try:
101 101 file.softspace = newvalue
102 102 except (AttributeError, TypeError):
103 103 # "attribute-less object" or "read-only attributes"
104 104 pass
105 105 return oldvalue
106 106
107 107
108 108 def no_op(*a, **kw): pass
109 109
110 110 class SpaceInInput(Exception): pass
111 111
112 112 class Bunch: pass
113 113
114 114
115 115 def get_default_colors():
116 116 if sys.platform=='darwin':
117 117 return "LightBG"
118 118 elif os.name=='nt':
119 119 return 'Linux'
120 120 else:
121 121 return 'Linux'
122 122
123 123
124 124 class SeparateStr(Str):
125 125 """A Str subclass to validate separate_in, separate_out, etc.
126 126
127 127 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
128 128 """
129 129
130 130 def validate(self, obj, value):
131 131 if value == '0': value = ''
132 132 value = value.replace('\\n','\n')
133 133 return super(SeparateStr, self).validate(obj, value)
134 134
135 135 class MultipleInstanceError(Exception):
136 136 pass
137 137
138 138 class ReadlineNoRecord(object):
139 139 """Context manager to execute some code, then reload readline history
140 140 so that interactive input to the code doesn't appear when pressing up."""
141 141 def __init__(self, shell):
142 142 self.shell = shell
143 143 self._nested_level = 0
144 144
145 145 def __enter__(self):
146 146 if self._nested_level == 0:
147 147 try:
148 148 self.orig_length = self.current_length()
149 149 self.readline_tail = self.get_readline_tail()
150 150 except (AttributeError, IndexError): # Can fail with pyreadline
151 151 self.orig_length, self.readline_tail = 999999, []
152 152 self._nested_level += 1
153 153
154 154 def __exit__(self, type, value, traceback):
155 155 self._nested_level -= 1
156 156 if self._nested_level == 0:
157 157 # Try clipping the end if it's got longer
158 158 try:
159 159 e = self.current_length() - self.orig_length
160 160 if e > 0:
161 161 for _ in range(e):
162 162 self.shell.readline.remove_history_item(self.orig_length)
163 163
164 164 # If it still doesn't match, just reload readline history.
165 165 if self.current_length() != self.orig_length \
166 166 or self.get_readline_tail() != self.readline_tail:
167 167 self.shell.refill_readline_hist()
168 168 except (AttributeError, IndexError):
169 169 pass
170 170 # Returning False will cause exceptions to propagate
171 171 return False
172 172
173 173 def current_length(self):
174 174 return self.shell.readline.get_current_history_length()
175 175
176 176 def get_readline_tail(self, n=10):
177 177 """Get the last n items in readline history."""
178 178 end = self.shell.readline.get_current_history_length() + 1
179 179 start = max(end-n, 1)
180 180 ghi = self.shell.readline.get_history_item
181 181 return [ghi(x) for x in range(start, end)]
182 182
183 183
184 184 #-----------------------------------------------------------------------------
185 185 # Main IPython class
186 186 #-----------------------------------------------------------------------------
187 187
188 188 class InteractiveShell(Configurable, Magic):
189 189 """An enhanced, interactive shell for Python."""
190 190
191 191 _instance = None
192 192 autocall = Enum((0,1,2), default_value=1, config=True)
193 193 # TODO: remove all autoindent logic and put into frontends.
194 194 # We can't do this yet because even runlines uses the autoindent.
195 195 autoindent = CBool(True, config=True)
196 196 automagic = CBool(True, config=True)
197 197 cache_size = Int(1000, config=True)
198 198 color_info = CBool(True, config=True)
199 199 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
200 200 default_value=get_default_colors(), config=True)
201 201 debug = CBool(False, config=True)
202 202 deep_reload = CBool(False, config=True)
203 203 display_formatter = Instance(DisplayFormatter)
204 204 displayhook_class = Type(DisplayHook)
205 205 display_pub_class = Type(DisplayPublisher)
206 206
207 207 exit_now = CBool(False)
208 208 exiter = Instance(ExitAutocall)
209 209 def _exiter_default(self):
210 210 return ExitAutocall(self)
211 211 # Monotonically increasing execution counter
212 212 execution_count = Int(1)
213 213 filename = Unicode("<ipython console>")
214 214 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
215 215
216 216 # Input splitter, to split entire cells of input into either individual
217 217 # interactive statements or whole blocks.
218 218 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
219 219 (), {})
220 220 logstart = CBool(False, config=True)
221 221 logfile = Unicode('', config=True)
222 222 logappend = Unicode('', config=True)
223 223 object_info_string_level = Enum((0,1,2), default_value=0,
224 224 config=True)
225 225 pdb = CBool(False, config=True)
226 226
227 227 profile = Unicode('', config=True)
228 228 prompt_in1 = Str('In [\\#]: ', config=True)
229 229 prompt_in2 = Str(' .\\D.: ', config=True)
230 230 prompt_out = Str('Out[\\#]: ', config=True)
231 231 prompts_pad_left = CBool(True, config=True)
232 232 quiet = CBool(False, config=True)
233 233
234 234 history_length = Int(10000, config=True)
235 235
236 236 # The readline stuff will eventually be moved to the terminal subclass
237 237 # but for now, we can't do that as readline is welded in everywhere.
238 238 readline_use = CBool(True, config=True)
239 239 readline_merge_completions = CBool(True, config=True)
240 240 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
241 241 readline_remove_delims = Str('-/~', config=True)
242 # don't use \M- bindings by default, because they
243 # conflict with 8-bit encodings. See gh-58,gh-88
242 244 readline_parse_and_bind = List([
243 245 'tab: complete',
244 246 '"\C-l": clear-screen',
245 247 'set show-all-if-ambiguous on',
246 248 '"\C-o": tab-insert',
247 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
248 # crash IPython.
249 '"\M-o": "\d\d\d\d"',
250 '"\M-I": "\d\d\d\d"',
251 249 '"\C-r": reverse-search-history',
252 250 '"\C-s": forward-search-history',
253 251 '"\C-p": history-search-backward',
254 252 '"\C-n": history-search-forward',
255 253 '"\e[A": history-search-backward',
256 254 '"\e[B": history-search-forward',
257 255 '"\C-k": kill-line',
258 256 '"\C-u": unix-line-discard',
259 257 ], allow_none=False, config=True)
260 258
261 259 # TODO: this part of prompt management should be moved to the frontends.
262 260 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
263 261 separate_in = SeparateStr('\n', config=True)
264 262 separate_out = SeparateStr('', config=True)
265 263 separate_out2 = SeparateStr('', config=True)
266 264 wildcards_case_sensitive = CBool(True, config=True)
267 265 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
268 266 default_value='Context', config=True)
269 267
270 268 # Subcomponents of InteractiveShell
271 269 alias_manager = Instance('IPython.core.alias.AliasManager')
272 270 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
273 271 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
274 272 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
275 273 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
276 274 plugin_manager = Instance('IPython.core.plugin.PluginManager')
277 275 payload_manager = Instance('IPython.core.payload.PayloadManager')
278 276 history_manager = Instance('IPython.core.history.HistoryManager')
279 277
280 278 # Private interface
281 279 _post_execute = Instance(dict)
282 280
283 281 def __init__(self, config=None, ipython_dir=None,
284 282 user_ns=None, user_global_ns=None,
285 283 custom_exceptions=((), None)):
286 284
287 285 # This is where traits with a config_key argument are updated
288 286 # from the values on config.
289 287 super(InteractiveShell, self).__init__(config=config)
290 288
291 289 # These are relatively independent and stateless
292 290 self.init_ipython_dir(ipython_dir)
293 291 self.init_instance_attrs()
294 292 self.init_environment()
295 293
296 294 # Create namespaces (user_ns, user_global_ns, etc.)
297 295 self.init_create_namespaces(user_ns, user_global_ns)
298 296 # This has to be done after init_create_namespaces because it uses
299 297 # something in self.user_ns, but before init_sys_modules, which
300 298 # is the first thing to modify sys.
301 299 # TODO: When we override sys.stdout and sys.stderr before this class
302 300 # is created, we are saving the overridden ones here. Not sure if this
303 301 # is what we want to do.
304 302 self.save_sys_module_state()
305 303 self.init_sys_modules()
306 304
307 305 # While we're trying to have each part of the code directly access what
308 306 # it needs without keeping redundant references to objects, we have too
309 307 # much legacy code that expects ip.db to exist.
310 308 self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
311 309
312 310 self.init_history()
313 311 self.init_encoding()
314 312 self.init_prefilter()
315 313
316 314 Magic.__init__(self, self)
317 315
318 316 self.init_syntax_highlighting()
319 317 self.init_hooks()
320 318 self.init_pushd_popd_magic()
321 319 # self.init_traceback_handlers use to be here, but we moved it below
322 320 # because it and init_io have to come after init_readline.
323 321 self.init_user_ns()
324 322 self.init_logger()
325 323 self.init_alias()
326 324 self.init_builtins()
327 325
328 326 # pre_config_initialization
329 327
330 328 # The next section should contain everything that was in ipmaker.
331 329 self.init_logstart()
332 330
333 331 # The following was in post_config_initialization
334 332 self.init_inspector()
335 333 # init_readline() must come before init_io(), because init_io uses
336 334 # readline related things.
337 335 self.init_readline()
338 336 # init_completer must come after init_readline, because it needs to
339 337 # know whether readline is present or not system-wide to configure the
340 338 # completers, since the completion machinery can now operate
341 339 # independently of readline (e.g. over the network)
342 340 self.init_completer()
343 341 # TODO: init_io() needs to happen before init_traceback handlers
344 342 # because the traceback handlers hardcode the stdout/stderr streams.
345 343 # This logic in in debugger.Pdb and should eventually be changed.
346 344 self.init_io()
347 345 self.init_traceback_handlers(custom_exceptions)
348 346 self.init_prompts()
349 347 self.init_display_formatter()
350 348 self.init_display_pub()
351 349 self.init_displayhook()
352 350 self.init_reload_doctest()
353 351 self.init_magics()
354 352 self.init_pdb()
355 353 self.init_extension_manager()
356 354 self.init_plugin_manager()
357 355 self.init_payload()
358 356 self.hooks.late_startup_hook()
359 357 atexit.register(self.atexit_operations)
360 358
361 359 @classmethod
362 360 def instance(cls, *args, **kwargs):
363 361 """Returns a global InteractiveShell instance."""
364 362 if cls._instance is None:
365 363 inst = cls(*args, **kwargs)
366 364 # Now make sure that the instance will also be returned by
367 365 # the subclasses instance attribute.
368 366 for subclass in cls.mro():
369 367 if issubclass(cls, subclass) and \
370 368 issubclass(subclass, InteractiveShell):
371 369 subclass._instance = inst
372 370 else:
373 371 break
374 372 if isinstance(cls._instance, cls):
375 373 return cls._instance
376 374 else:
377 375 raise MultipleInstanceError(
378 376 'Multiple incompatible subclass instances of '
379 377 'InteractiveShell are being created.'
380 378 )
381 379
382 380 @classmethod
383 381 def initialized(cls):
384 382 return hasattr(cls, "_instance")
385 383
386 384 def get_ipython(self):
387 385 """Return the currently running IPython instance."""
388 386 return self
389 387
390 388 #-------------------------------------------------------------------------
391 389 # Trait changed handlers
392 390 #-------------------------------------------------------------------------
393 391
394 392 def _ipython_dir_changed(self, name, new):
395 393 if not os.path.isdir(new):
396 394 os.makedirs(new, mode = 0777)
397 395
398 396 def set_autoindent(self,value=None):
399 397 """Set the autoindent flag, checking for readline support.
400 398
401 399 If called with no arguments, it acts as a toggle."""
402 400
403 401 if not self.has_readline:
404 402 if os.name == 'posix':
405 403 warn("The auto-indent feature requires the readline library")
406 404 self.autoindent = 0
407 405 return
408 406 if value is None:
409 407 self.autoindent = not self.autoindent
410 408 else:
411 409 self.autoindent = value
412 410
413 411 #-------------------------------------------------------------------------
414 412 # init_* methods called by __init__
415 413 #-------------------------------------------------------------------------
416 414
417 415 def init_ipython_dir(self, ipython_dir):
418 416 if ipython_dir is not None:
419 417 self.ipython_dir = ipython_dir
420 418 self.config.Global.ipython_dir = self.ipython_dir
421 419 return
422 420
423 421 if hasattr(self.config.Global, 'ipython_dir'):
424 422 self.ipython_dir = self.config.Global.ipython_dir
425 423 else:
426 424 self.ipython_dir = get_ipython_dir()
427 425
428 426 # All children can just read this
429 427 self.config.Global.ipython_dir = self.ipython_dir
430 428
431 429 def init_instance_attrs(self):
432 430 self.more = False
433 431
434 432 # command compiler
435 433 self.compile = CachingCompiler()
436 434
437 435 # Make an empty namespace, which extension writers can rely on both
438 436 # existing and NEVER being used by ipython itself. This gives them a
439 437 # convenient location for storing additional information and state
440 438 # their extensions may require, without fear of collisions with other
441 439 # ipython names that may develop later.
442 440 self.meta = Struct()
443 441
444 442 # Temporary files used for various purposes. Deleted at exit.
445 443 self.tempfiles = []
446 444
447 445 # Keep track of readline usage (later set by init_readline)
448 446 self.has_readline = False
449 447
450 448 # keep track of where we started running (mainly for crash post-mortem)
451 449 # This is not being used anywhere currently.
452 450 self.starting_dir = os.getcwd()
453 451
454 452 # Indentation management
455 453 self.indent_current_nsp = 0
456 454
457 455 # Dict to track post-execution functions that have been registered
458 456 self._post_execute = {}
459 457
460 458 def init_environment(self):
461 459 """Any changes we need to make to the user's environment."""
462 460 pass
463 461
464 462 def init_encoding(self):
465 463 # Get system encoding at startup time. Certain terminals (like Emacs
466 464 # under Win32 have it set to None, and we need to have a known valid
467 465 # encoding to use in the raw_input() method
468 466 try:
469 467 self.stdin_encoding = sys.stdin.encoding or 'ascii'
470 468 except AttributeError:
471 469 self.stdin_encoding = 'ascii'
472 470
473 471 def init_syntax_highlighting(self):
474 472 # Python source parser/formatter for syntax highlighting
475 473 pyformat = PyColorize.Parser().format
476 474 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
477 475
478 476 def init_pushd_popd_magic(self):
479 477 # for pushd/popd management
480 478 try:
481 479 self.home_dir = get_home_dir()
482 480 except HomeDirError, msg:
483 481 fatal(msg)
484 482
485 483 self.dir_stack = []
486 484
487 485 def init_logger(self):
488 486 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
489 487 logmode='rotate')
490 488
491 489 def init_logstart(self):
492 490 """Initialize logging in case it was requested at the command line.
493 491 """
494 492 if self.logappend:
495 493 self.magic_logstart(self.logappend + ' append')
496 494 elif self.logfile:
497 495 self.magic_logstart(self.logfile)
498 496 elif self.logstart:
499 497 self.magic_logstart()
500 498
501 499 def init_builtins(self):
502 500 self.builtin_trap = BuiltinTrap(shell=self)
503 501
504 502 def init_inspector(self):
505 503 # Object inspector
506 504 self.inspector = oinspect.Inspector(oinspect.InspectColors,
507 505 PyColorize.ANSICodeColors,
508 506 'NoColor',
509 507 self.object_info_string_level)
510 508
511 509 def init_io(self):
512 510 # This will just use sys.stdout and sys.stderr. If you want to
513 511 # override sys.stdout and sys.stderr themselves, you need to do that
514 512 # *before* instantiating this class, because io holds onto
515 513 # references to the underlying streams.
516 514 if sys.platform == 'win32' and self.has_readline:
517 515 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
518 516 else:
519 517 io.stdout = io.IOStream(sys.stdout)
520 518 io.stderr = io.IOStream(sys.stderr)
521 519
522 520 def init_prompts(self):
523 521 # TODO: This is a pass for now because the prompts are managed inside
524 522 # the DisplayHook. Once there is a separate prompt manager, this
525 523 # will initialize that object and all prompt related information.
526 524 pass
527 525
528 526 def init_display_formatter(self):
529 527 self.display_formatter = DisplayFormatter(config=self.config)
530 528
531 529 def init_display_pub(self):
532 530 self.display_pub = self.display_pub_class(config=self.config)
533 531
534 532 def init_displayhook(self):
535 533 # Initialize displayhook, set in/out prompts and printing system
536 534 self.displayhook = self.displayhook_class(
537 535 config=self.config,
538 536 shell=self,
539 537 cache_size=self.cache_size,
540 538 input_sep = self.separate_in,
541 539 output_sep = self.separate_out,
542 540 output_sep2 = self.separate_out2,
543 541 ps1 = self.prompt_in1,
544 542 ps2 = self.prompt_in2,
545 543 ps_out = self.prompt_out,
546 544 pad_left = self.prompts_pad_left
547 545 )
548 546 # This is a context manager that installs/revmoes the displayhook at
549 547 # the appropriate time.
550 548 self.display_trap = DisplayTrap(hook=self.displayhook)
551 549
552 550 def init_reload_doctest(self):
553 551 # Do a proper resetting of doctest, including the necessary displayhook
554 552 # monkeypatching
555 553 try:
556 554 doctest_reload()
557 555 except ImportError:
558 556 warn("doctest module does not exist.")
559 557
560 558 #-------------------------------------------------------------------------
561 559 # Things related to injections into the sys module
562 560 #-------------------------------------------------------------------------
563 561
564 562 def save_sys_module_state(self):
565 563 """Save the state of hooks in the sys module.
566 564
567 565 This has to be called after self.user_ns is created.
568 566 """
569 567 self._orig_sys_module_state = {}
570 568 self._orig_sys_module_state['stdin'] = sys.stdin
571 569 self._orig_sys_module_state['stdout'] = sys.stdout
572 570 self._orig_sys_module_state['stderr'] = sys.stderr
573 571 self._orig_sys_module_state['excepthook'] = sys.excepthook
574 572 try:
575 573 self._orig_sys_modules_main_name = self.user_ns['__name__']
576 574 except KeyError:
577 575 pass
578 576
579 577 def restore_sys_module_state(self):
580 578 """Restore the state of the sys module."""
581 579 try:
582 580 for k, v in self._orig_sys_module_state.iteritems():
583 581 setattr(sys, k, v)
584 582 except AttributeError:
585 583 pass
586 584 # Reset what what done in self.init_sys_modules
587 585 try:
588 586 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
589 587 except (AttributeError, KeyError):
590 588 pass
591 589
592 590 #-------------------------------------------------------------------------
593 591 # Things related to hooks
594 592 #-------------------------------------------------------------------------
595 593
596 594 def init_hooks(self):
597 595 # hooks holds pointers used for user-side customizations
598 596 self.hooks = Struct()
599 597
600 598 self.strdispatchers = {}
601 599
602 600 # Set all default hooks, defined in the IPython.hooks module.
603 601 hooks = IPython.core.hooks
604 602 for hook_name in hooks.__all__:
605 603 # default hooks have priority 100, i.e. low; user hooks should have
606 604 # 0-100 priority
607 605 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
608 606
609 607 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
610 608 """set_hook(name,hook) -> sets an internal IPython hook.
611 609
612 610 IPython exposes some of its internal API as user-modifiable hooks. By
613 611 adding your function to one of these hooks, you can modify IPython's
614 612 behavior to call at runtime your own routines."""
615 613
616 614 # At some point in the future, this should validate the hook before it
617 615 # accepts it. Probably at least check that the hook takes the number
618 616 # of args it's supposed to.
619 617
620 618 f = types.MethodType(hook,self)
621 619
622 620 # check if the hook is for strdispatcher first
623 621 if str_key is not None:
624 622 sdp = self.strdispatchers.get(name, StrDispatch())
625 623 sdp.add_s(str_key, f, priority )
626 624 self.strdispatchers[name] = sdp
627 625 return
628 626 if re_key is not None:
629 627 sdp = self.strdispatchers.get(name, StrDispatch())
630 628 sdp.add_re(re.compile(re_key), f, priority )
631 629 self.strdispatchers[name] = sdp
632 630 return
633 631
634 632 dp = getattr(self.hooks, name, None)
635 633 if name not in IPython.core.hooks.__all__:
636 634 print "Warning! Hook '%s' is not one of %s" % \
637 635 (name, IPython.core.hooks.__all__ )
638 636 if not dp:
639 637 dp = IPython.core.hooks.CommandChainDispatcher()
640 638
641 639 try:
642 640 dp.add(f,priority)
643 641 except AttributeError:
644 642 # it was not commandchain, plain old func - replace
645 643 dp = f
646 644
647 645 setattr(self.hooks,name, dp)
648 646
649 647 def register_post_execute(self, func):
650 648 """Register a function for calling after code execution.
651 649 """
652 650 if not callable(func):
653 651 raise ValueError('argument %s must be callable' % func)
654 652 self._post_execute[func] = True
655 653
656 654 #-------------------------------------------------------------------------
657 655 # Things related to the "main" module
658 656 #-------------------------------------------------------------------------
659 657
660 658 def new_main_mod(self,ns=None):
661 659 """Return a new 'main' module object for user code execution.
662 660 """
663 661 main_mod = self._user_main_module
664 662 init_fakemod_dict(main_mod,ns)
665 663 return main_mod
666 664
667 665 def cache_main_mod(self,ns,fname):
668 666 """Cache a main module's namespace.
669 667
670 668 When scripts are executed via %run, we must keep a reference to the
671 669 namespace of their __main__ module (a FakeModule instance) around so
672 670 that Python doesn't clear it, rendering objects defined therein
673 671 useless.
674 672
675 673 This method keeps said reference in a private dict, keyed by the
676 674 absolute path of the module object (which corresponds to the script
677 675 path). This way, for multiple executions of the same script we only
678 676 keep one copy of the namespace (the last one), thus preventing memory
679 677 leaks from old references while allowing the objects from the last
680 678 execution to be accessible.
681 679
682 680 Note: we can not allow the actual FakeModule instances to be deleted,
683 681 because of how Python tears down modules (it hard-sets all their
684 682 references to None without regard for reference counts). This method
685 683 must therefore make a *copy* of the given namespace, to allow the
686 684 original module's __dict__ to be cleared and reused.
687 685
688 686
689 687 Parameters
690 688 ----------
691 689 ns : a namespace (a dict, typically)
692 690
693 691 fname : str
694 692 Filename associated with the namespace.
695 693
696 694 Examples
697 695 --------
698 696
699 697 In [10]: import IPython
700 698
701 699 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
702 700
703 701 In [12]: IPython.__file__ in _ip._main_ns_cache
704 702 Out[12]: True
705 703 """
706 704 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
707 705
708 706 def clear_main_mod_cache(self):
709 707 """Clear the cache of main modules.
710 708
711 709 Mainly for use by utilities like %reset.
712 710
713 711 Examples
714 712 --------
715 713
716 714 In [15]: import IPython
717 715
718 716 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
719 717
720 718 In [17]: len(_ip._main_ns_cache) > 0
721 719 Out[17]: True
722 720
723 721 In [18]: _ip.clear_main_mod_cache()
724 722
725 723 In [19]: len(_ip._main_ns_cache) == 0
726 724 Out[19]: True
727 725 """
728 726 self._main_ns_cache.clear()
729 727
730 728 #-------------------------------------------------------------------------
731 729 # Things related to debugging
732 730 #-------------------------------------------------------------------------
733 731
734 732 def init_pdb(self):
735 733 # Set calling of pdb on exceptions
736 734 # self.call_pdb is a property
737 735 self.call_pdb = self.pdb
738 736
739 737 def _get_call_pdb(self):
740 738 return self._call_pdb
741 739
742 740 def _set_call_pdb(self,val):
743 741
744 742 if val not in (0,1,False,True):
745 743 raise ValueError,'new call_pdb value must be boolean'
746 744
747 745 # store value in instance
748 746 self._call_pdb = val
749 747
750 748 # notify the actual exception handlers
751 749 self.InteractiveTB.call_pdb = val
752 750
753 751 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
754 752 'Control auto-activation of pdb at exceptions')
755 753
756 754 def debugger(self,force=False):
757 755 """Call the pydb/pdb debugger.
758 756
759 757 Keywords:
760 758
761 759 - force(False): by default, this routine checks the instance call_pdb
762 760 flag and does not actually invoke the debugger if the flag is false.
763 761 The 'force' option forces the debugger to activate even if the flag
764 762 is false.
765 763 """
766 764
767 765 if not (force or self.call_pdb):
768 766 return
769 767
770 768 if not hasattr(sys,'last_traceback'):
771 769 error('No traceback has been produced, nothing to debug.')
772 770 return
773 771
774 772 # use pydb if available
775 773 if debugger.has_pydb:
776 774 from pydb import pm
777 775 else:
778 776 # fallback to our internal debugger
779 777 pm = lambda : self.InteractiveTB.debugger(force=True)
780 778
781 779 with self.readline_no_record:
782 780 pm()
783 781
784 782 #-------------------------------------------------------------------------
785 783 # Things related to IPython's various namespaces
786 784 #-------------------------------------------------------------------------
787 785
788 786 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
789 787 # Create the namespace where the user will operate. user_ns is
790 788 # normally the only one used, and it is passed to the exec calls as
791 789 # the locals argument. But we do carry a user_global_ns namespace
792 790 # given as the exec 'globals' argument, This is useful in embedding
793 791 # situations where the ipython shell opens in a context where the
794 792 # distinction between locals and globals is meaningful. For
795 793 # non-embedded contexts, it is just the same object as the user_ns dict.
796 794
797 795 # FIXME. For some strange reason, __builtins__ is showing up at user
798 796 # level as a dict instead of a module. This is a manual fix, but I
799 797 # should really track down where the problem is coming from. Alex
800 798 # Schmolck reported this problem first.
801 799
802 800 # A useful post by Alex Martelli on this topic:
803 801 # Re: inconsistent value from __builtins__
804 802 # Von: Alex Martelli <aleaxit@yahoo.com>
805 803 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
806 804 # Gruppen: comp.lang.python
807 805
808 806 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
809 807 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
810 808 # > <type 'dict'>
811 809 # > >>> print type(__builtins__)
812 810 # > <type 'module'>
813 811 # > Is this difference in return value intentional?
814 812
815 813 # Well, it's documented that '__builtins__' can be either a dictionary
816 814 # or a module, and it's been that way for a long time. Whether it's
817 815 # intentional (or sensible), I don't know. In any case, the idea is
818 816 # that if you need to access the built-in namespace directly, you
819 817 # should start with "import __builtin__" (note, no 's') which will
820 818 # definitely give you a module. Yeah, it's somewhat confusing:-(.
821 819
822 820 # These routines return properly built dicts as needed by the rest of
823 821 # the code, and can also be used by extension writers to generate
824 822 # properly initialized namespaces.
825 823 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
826 824 user_global_ns)
827 825
828 826 # Assign namespaces
829 827 # This is the namespace where all normal user variables live
830 828 self.user_ns = user_ns
831 829 self.user_global_ns = user_global_ns
832 830
833 831 # An auxiliary namespace that checks what parts of the user_ns were
834 832 # loaded at startup, so we can list later only variables defined in
835 833 # actual interactive use. Since it is always a subset of user_ns, it
836 834 # doesn't need to be separately tracked in the ns_table.
837 835 self.user_ns_hidden = {}
838 836
839 837 # A namespace to keep track of internal data structures to prevent
840 838 # them from cluttering user-visible stuff. Will be updated later
841 839 self.internal_ns = {}
842 840
843 841 # Now that FakeModule produces a real module, we've run into a nasty
844 842 # problem: after script execution (via %run), the module where the user
845 843 # code ran is deleted. Now that this object is a true module (needed
846 844 # so docetst and other tools work correctly), the Python module
847 845 # teardown mechanism runs over it, and sets to None every variable
848 846 # present in that module. Top-level references to objects from the
849 847 # script survive, because the user_ns is updated with them. However,
850 848 # calling functions defined in the script that use other things from
851 849 # the script will fail, because the function's closure had references
852 850 # to the original objects, which are now all None. So we must protect
853 851 # these modules from deletion by keeping a cache.
854 852 #
855 853 # To avoid keeping stale modules around (we only need the one from the
856 854 # last run), we use a dict keyed with the full path to the script, so
857 855 # only the last version of the module is held in the cache. Note,
858 856 # however, that we must cache the module *namespace contents* (their
859 857 # __dict__). Because if we try to cache the actual modules, old ones
860 858 # (uncached) could be destroyed while still holding references (such as
861 859 # those held by GUI objects that tend to be long-lived)>
862 860 #
863 861 # The %reset command will flush this cache. See the cache_main_mod()
864 862 # and clear_main_mod_cache() methods for details on use.
865 863
866 864 # This is the cache used for 'main' namespaces
867 865 self._main_ns_cache = {}
868 866 # And this is the single instance of FakeModule whose __dict__ we keep
869 867 # copying and clearing for reuse on each %run
870 868 self._user_main_module = FakeModule()
871 869
872 870 # A table holding all the namespaces IPython deals with, so that
873 871 # introspection facilities can search easily.
874 872 self.ns_table = {'user':user_ns,
875 873 'user_global':user_global_ns,
876 874 'internal':self.internal_ns,
877 875 'builtin':__builtin__.__dict__
878 876 }
879 877
880 878 # Similarly, track all namespaces where references can be held and that
881 879 # we can safely clear (so it can NOT include builtin). This one can be
882 880 # a simple list. Note that the main execution namespaces, user_ns and
883 881 # user_global_ns, can NOT be listed here, as clearing them blindly
884 882 # causes errors in object __del__ methods. Instead, the reset() method
885 883 # clears them manually and carefully.
886 884 self.ns_refs_table = [ self.user_ns_hidden,
887 885 self.internal_ns, self._main_ns_cache ]
888 886
889 887 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
890 888 """Return a valid local and global user interactive namespaces.
891 889
892 890 This builds a dict with the minimal information needed to operate as a
893 891 valid IPython user namespace, which you can pass to the various
894 892 embedding classes in ipython. The default implementation returns the
895 893 same dict for both the locals and the globals to allow functions to
896 894 refer to variables in the namespace. Customized implementations can
897 895 return different dicts. The locals dictionary can actually be anything
898 896 following the basic mapping protocol of a dict, but the globals dict
899 897 must be a true dict, not even a subclass. It is recommended that any
900 898 custom object for the locals namespace synchronize with the globals
901 899 dict somehow.
902 900
903 901 Raises TypeError if the provided globals namespace is not a true dict.
904 902
905 903 Parameters
906 904 ----------
907 905 user_ns : dict-like, optional
908 906 The current user namespace. The items in this namespace should
909 907 be included in the output. If None, an appropriate blank
910 908 namespace should be created.
911 909 user_global_ns : dict, optional
912 910 The current user global namespace. The items in this namespace
913 911 should be included in the output. If None, an appropriate
914 912 blank namespace should be created.
915 913
916 914 Returns
917 915 -------
918 916 A pair of dictionary-like object to be used as the local namespace
919 917 of the interpreter and a dict to be used as the global namespace.
920 918 """
921 919
922 920
923 921 # We must ensure that __builtin__ (without the final 's') is always
924 922 # available and pointing to the __builtin__ *module*. For more details:
925 923 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
926 924
927 925 if user_ns is None:
928 926 # Set __name__ to __main__ to better match the behavior of the
929 927 # normal interpreter.
930 928 user_ns = {'__name__' :'__main__',
931 929 '__builtin__' : __builtin__,
932 930 '__builtins__' : __builtin__,
933 931 }
934 932 else:
935 933 user_ns.setdefault('__name__','__main__')
936 934 user_ns.setdefault('__builtin__',__builtin__)
937 935 user_ns.setdefault('__builtins__',__builtin__)
938 936
939 937 if user_global_ns is None:
940 938 user_global_ns = user_ns
941 939 if type(user_global_ns) is not dict:
942 940 raise TypeError("user_global_ns must be a true dict; got %r"
943 941 % type(user_global_ns))
944 942
945 943 return user_ns, user_global_ns
946 944
947 945 def init_sys_modules(self):
948 946 # We need to insert into sys.modules something that looks like a
949 947 # module but which accesses the IPython namespace, for shelve and
950 948 # pickle to work interactively. Normally they rely on getting
951 949 # everything out of __main__, but for embedding purposes each IPython
952 950 # instance has its own private namespace, so we can't go shoving
953 951 # everything into __main__.
954 952
955 953 # note, however, that we should only do this for non-embedded
956 954 # ipythons, which really mimic the __main__.__dict__ with their own
957 955 # namespace. Embedded instances, on the other hand, should not do
958 956 # this because they need to manage the user local/global namespaces
959 957 # only, but they live within a 'normal' __main__ (meaning, they
960 958 # shouldn't overtake the execution environment of the script they're
961 959 # embedded in).
962 960
963 961 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
964 962
965 963 try:
966 964 main_name = self.user_ns['__name__']
967 965 except KeyError:
968 966 raise KeyError('user_ns dictionary MUST have a "__name__" key')
969 967 else:
970 968 sys.modules[main_name] = FakeModule(self.user_ns)
971 969
972 970 def init_user_ns(self):
973 971 """Initialize all user-visible namespaces to their minimum defaults.
974 972
975 973 Certain history lists are also initialized here, as they effectively
976 974 act as user namespaces.
977 975
978 976 Notes
979 977 -----
980 978 All data structures here are only filled in, they are NOT reset by this
981 979 method. If they were not empty before, data will simply be added to
982 980 therm.
983 981 """
984 982 # This function works in two parts: first we put a few things in
985 983 # user_ns, and we sync that contents into user_ns_hidden so that these
986 984 # initial variables aren't shown by %who. After the sync, we add the
987 985 # rest of what we *do* want the user to see with %who even on a new
988 986 # session (probably nothing, so theye really only see their own stuff)
989 987
990 988 # The user dict must *always* have a __builtin__ reference to the
991 989 # Python standard __builtin__ namespace, which must be imported.
992 990 # This is so that certain operations in prompt evaluation can be
993 991 # reliably executed with builtins. Note that we can NOT use
994 992 # __builtins__ (note the 's'), because that can either be a dict or a
995 993 # module, and can even mutate at runtime, depending on the context
996 994 # (Python makes no guarantees on it). In contrast, __builtin__ is
997 995 # always a module object, though it must be explicitly imported.
998 996
999 997 # For more details:
1000 998 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1001 999 ns = dict(__builtin__ = __builtin__)
1002 1000
1003 1001 # Put 'help' in the user namespace
1004 1002 try:
1005 1003 from site import _Helper
1006 1004 ns['help'] = _Helper()
1007 1005 except ImportError:
1008 1006 warn('help() not available - check site.py')
1009 1007
1010 1008 # make global variables for user access to the histories
1011 1009 ns['_ih'] = self.history_manager.input_hist_parsed
1012 1010 ns['_oh'] = self.history_manager.output_hist
1013 1011 ns['_dh'] = self.history_manager.dir_hist
1014 1012
1015 1013 ns['_sh'] = shadowns
1016 1014
1017 1015 # user aliases to input and output histories. These shouldn't show up
1018 1016 # in %who, as they can have very large reprs.
1019 1017 ns['In'] = self.history_manager.input_hist_parsed
1020 1018 ns['Out'] = self.history_manager.output_hist
1021 1019
1022 1020 # Store myself as the public api!!!
1023 1021 ns['get_ipython'] = self.get_ipython
1024 1022
1025 1023 ns['exit'] = self.exiter
1026 1024 ns['quit'] = self.exiter
1027 1025
1028 1026 # Sync what we've added so far to user_ns_hidden so these aren't seen
1029 1027 # by %who
1030 1028 self.user_ns_hidden.update(ns)
1031 1029
1032 1030 # Anything put into ns now would show up in %who. Think twice before
1033 1031 # putting anything here, as we really want %who to show the user their
1034 1032 # stuff, not our variables.
1035 1033
1036 1034 # Finally, update the real user's namespace
1037 1035 self.user_ns.update(ns)
1038 1036
1039 1037 def reset(self, new_session=True):
1040 1038 """Clear all internal namespaces, and attempt to release references to
1041 1039 user objects.
1042 1040
1043 1041 If new_session is True, a new history session will be opened.
1044 1042 """
1045 1043 # Clear histories
1046 1044 self.history_manager.reset(new_session)
1047 1045 # Reset counter used to index all histories
1048 1046 if new_session:
1049 1047 self.execution_count = 1
1050 1048
1051 1049 # Flush cached output items
1052 1050 if self.displayhook.do_full_cache:
1053 1051 self.displayhook.flush()
1054 1052
1055 1053 # Restore the user namespaces to minimal usability
1056 1054 for ns in self.ns_refs_table:
1057 1055 ns.clear()
1058 1056
1059 1057 # The main execution namespaces must be cleared very carefully,
1060 1058 # skipping the deletion of the builtin-related keys, because doing so
1061 1059 # would cause errors in many object's __del__ methods.
1062 1060 for ns in [self.user_ns, self.user_global_ns]:
1063 1061 drop_keys = set(ns.keys())
1064 1062 drop_keys.discard('__builtin__')
1065 1063 drop_keys.discard('__builtins__')
1066 1064 for k in drop_keys:
1067 1065 del ns[k]
1068 1066
1069 1067 # Restore the user namespaces to minimal usability
1070 1068 self.init_user_ns()
1071 1069
1072 1070 # Restore the default and user aliases
1073 1071 self.alias_manager.clear_aliases()
1074 1072 self.alias_manager.init_aliases()
1075 1073
1076 1074 # Flush the private list of module references kept for script
1077 1075 # execution protection
1078 1076 self.clear_main_mod_cache()
1079 1077
1080 1078 # Clear out the namespace from the last %run
1081 1079 self.new_main_mod()
1082 1080
1083 1081 def reset_selective(self, regex=None):
1084 1082 """Clear selective variables from internal namespaces based on a
1085 1083 specified regular expression.
1086 1084
1087 1085 Parameters
1088 1086 ----------
1089 1087 regex : string or compiled pattern, optional
1090 1088 A regular expression pattern that will be used in searching
1091 1089 variable names in the users namespaces.
1092 1090 """
1093 1091 if regex is not None:
1094 1092 try:
1095 1093 m = re.compile(regex)
1096 1094 except TypeError:
1097 1095 raise TypeError('regex must be a string or compiled pattern')
1098 1096 # Search for keys in each namespace that match the given regex
1099 1097 # If a match is found, delete the key/value pair.
1100 1098 for ns in self.ns_refs_table:
1101 1099 for var in ns:
1102 1100 if m.search(var):
1103 1101 del ns[var]
1104 1102
1105 1103 def push(self, variables, interactive=True):
1106 1104 """Inject a group of variables into the IPython user namespace.
1107 1105
1108 1106 Parameters
1109 1107 ----------
1110 1108 variables : dict, str or list/tuple of str
1111 1109 The variables to inject into the user's namespace. If a dict, a
1112 1110 simple update is done. If a str, the string is assumed to have
1113 1111 variable names separated by spaces. A list/tuple of str can also
1114 1112 be used to give the variable names. If just the variable names are
1115 1113 give (list/tuple/str) then the variable values looked up in the
1116 1114 callers frame.
1117 1115 interactive : bool
1118 1116 If True (default), the variables will be listed with the ``who``
1119 1117 magic.
1120 1118 """
1121 1119 vdict = None
1122 1120
1123 1121 # We need a dict of name/value pairs to do namespace updates.
1124 1122 if isinstance(variables, dict):
1125 1123 vdict = variables
1126 1124 elif isinstance(variables, (basestring, list, tuple)):
1127 1125 if isinstance(variables, basestring):
1128 1126 vlist = variables.split()
1129 1127 else:
1130 1128 vlist = variables
1131 1129 vdict = {}
1132 1130 cf = sys._getframe(1)
1133 1131 for name in vlist:
1134 1132 try:
1135 1133 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1136 1134 except:
1137 1135 print ('Could not get variable %s from %s' %
1138 1136 (name,cf.f_code.co_name))
1139 1137 else:
1140 1138 raise ValueError('variables must be a dict/str/list/tuple')
1141 1139
1142 1140 # Propagate variables to user namespace
1143 1141 self.user_ns.update(vdict)
1144 1142
1145 1143 # And configure interactive visibility
1146 1144 config_ns = self.user_ns_hidden
1147 1145 if interactive:
1148 1146 for name, val in vdict.iteritems():
1149 1147 config_ns.pop(name, None)
1150 1148 else:
1151 1149 for name,val in vdict.iteritems():
1152 1150 config_ns[name] = val
1153 1151
1154 1152 #-------------------------------------------------------------------------
1155 1153 # Things related to object introspection
1156 1154 #-------------------------------------------------------------------------
1157 1155
1158 1156 def _ofind(self, oname, namespaces=None):
1159 1157 """Find an object in the available namespaces.
1160 1158
1161 1159 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1162 1160
1163 1161 Has special code to detect magic functions.
1164 1162 """
1165 1163 #oname = oname.strip()
1166 1164 #print '1- oname: <%r>' % oname # dbg
1167 1165 try:
1168 1166 oname = oname.strip().encode('ascii')
1169 1167 #print '2- oname: <%r>' % oname # dbg
1170 1168 except UnicodeEncodeError:
1171 1169 print 'Python identifiers can only contain ascii characters.'
1172 1170 return dict(found=False)
1173 1171
1174 1172 alias_ns = None
1175 1173 if namespaces is None:
1176 1174 # Namespaces to search in:
1177 1175 # Put them in a list. The order is important so that we
1178 1176 # find things in the same order that Python finds them.
1179 1177 namespaces = [ ('Interactive', self.user_ns),
1180 1178 ('IPython internal', self.internal_ns),
1181 1179 ('Python builtin', __builtin__.__dict__),
1182 1180 ('Alias', self.alias_manager.alias_table),
1183 1181 ]
1184 1182 alias_ns = self.alias_manager.alias_table
1185 1183
1186 1184 # initialize results to 'null'
1187 1185 found = False; obj = None; ospace = None; ds = None;
1188 1186 ismagic = False; isalias = False; parent = None
1189 1187
1190 1188 # We need to special-case 'print', which as of python2.6 registers as a
1191 1189 # function but should only be treated as one if print_function was
1192 1190 # loaded with a future import. In this case, just bail.
1193 1191 if (oname == 'print' and not (self.compile.compiler_flags &
1194 1192 __future__.CO_FUTURE_PRINT_FUNCTION)):
1195 1193 return {'found':found, 'obj':obj, 'namespace':ospace,
1196 1194 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1197 1195
1198 1196 # Look for the given name by splitting it in parts. If the head is
1199 1197 # found, then we look for all the remaining parts as members, and only
1200 1198 # declare success if we can find them all.
1201 1199 oname_parts = oname.split('.')
1202 1200 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1203 1201 for nsname,ns in namespaces:
1204 1202 try:
1205 1203 obj = ns[oname_head]
1206 1204 except KeyError:
1207 1205 continue
1208 1206 else:
1209 1207 #print 'oname_rest:', oname_rest # dbg
1210 1208 for part in oname_rest:
1211 1209 try:
1212 1210 parent = obj
1213 1211 obj = getattr(obj,part)
1214 1212 except:
1215 1213 # Blanket except b/c some badly implemented objects
1216 1214 # allow __getattr__ to raise exceptions other than
1217 1215 # AttributeError, which then crashes IPython.
1218 1216 break
1219 1217 else:
1220 1218 # If we finish the for loop (no break), we got all members
1221 1219 found = True
1222 1220 ospace = nsname
1223 1221 if ns == alias_ns:
1224 1222 isalias = True
1225 1223 break # namespace loop
1226 1224
1227 1225 # Try to see if it's magic
1228 1226 if not found:
1229 1227 if oname.startswith(ESC_MAGIC):
1230 1228 oname = oname[1:]
1231 1229 obj = getattr(self,'magic_'+oname,None)
1232 1230 if obj is not None:
1233 1231 found = True
1234 1232 ospace = 'IPython internal'
1235 1233 ismagic = True
1236 1234
1237 1235 # Last try: special-case some literals like '', [], {}, etc:
1238 1236 if not found and oname_head in ["''",'""','[]','{}','()']:
1239 1237 obj = eval(oname_head)
1240 1238 found = True
1241 1239 ospace = 'Interactive'
1242 1240
1243 1241 return {'found':found, 'obj':obj, 'namespace':ospace,
1244 1242 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1245 1243
1246 1244 def _ofind_property(self, oname, info):
1247 1245 """Second part of object finding, to look for property details."""
1248 1246 if info.found:
1249 1247 # Get the docstring of the class property if it exists.
1250 1248 path = oname.split('.')
1251 1249 root = '.'.join(path[:-1])
1252 1250 if info.parent is not None:
1253 1251 try:
1254 1252 target = getattr(info.parent, '__class__')
1255 1253 # The object belongs to a class instance.
1256 1254 try:
1257 1255 target = getattr(target, path[-1])
1258 1256 # The class defines the object.
1259 1257 if isinstance(target, property):
1260 1258 oname = root + '.__class__.' + path[-1]
1261 1259 info = Struct(self._ofind(oname))
1262 1260 except AttributeError: pass
1263 1261 except AttributeError: pass
1264 1262
1265 1263 # We return either the new info or the unmodified input if the object
1266 1264 # hadn't been found
1267 1265 return info
1268 1266
1269 1267 def _object_find(self, oname, namespaces=None):
1270 1268 """Find an object and return a struct with info about it."""
1271 1269 inf = Struct(self._ofind(oname, namespaces))
1272 1270 return Struct(self._ofind_property(oname, inf))
1273 1271
1274 1272 def _inspect(self, meth, oname, namespaces=None, **kw):
1275 1273 """Generic interface to the inspector system.
1276 1274
1277 1275 This function is meant to be called by pdef, pdoc & friends."""
1278 1276 info = self._object_find(oname)
1279 1277 if info.found:
1280 1278 pmethod = getattr(self.inspector, meth)
1281 1279 formatter = format_screen if info.ismagic else None
1282 1280 if meth == 'pdoc':
1283 1281 pmethod(info.obj, oname, formatter)
1284 1282 elif meth == 'pinfo':
1285 1283 pmethod(info.obj, oname, formatter, info, **kw)
1286 1284 else:
1287 1285 pmethod(info.obj, oname)
1288 1286 else:
1289 1287 print 'Object `%s` not found.' % oname
1290 1288 return 'not found' # so callers can take other action
1291 1289
1292 1290 def object_inspect(self, oname):
1293 1291 with self.builtin_trap:
1294 1292 info = self._object_find(oname)
1295 1293 if info.found:
1296 1294 return self.inspector.info(info.obj, oname, info=info)
1297 1295 else:
1298 1296 return oinspect.object_info(name=oname, found=False)
1299 1297
1300 1298 #-------------------------------------------------------------------------
1301 1299 # Things related to history management
1302 1300 #-------------------------------------------------------------------------
1303 1301
1304 1302 def init_history(self):
1305 1303 """Sets up the command history, and starts regular autosaves."""
1306 1304 self.history_manager = HistoryManager(shell=self, config=self.config)
1307 1305
1308 1306 #-------------------------------------------------------------------------
1309 1307 # Things related to exception handling and tracebacks (not debugging)
1310 1308 #-------------------------------------------------------------------------
1311 1309
1312 1310 def init_traceback_handlers(self, custom_exceptions):
1313 1311 # Syntax error handler.
1314 1312 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1315 1313
1316 1314 # The interactive one is initialized with an offset, meaning we always
1317 1315 # want to remove the topmost item in the traceback, which is our own
1318 1316 # internal code. Valid modes: ['Plain','Context','Verbose']
1319 1317 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1320 1318 color_scheme='NoColor',
1321 1319 tb_offset = 1,
1322 1320 check_cache=self.compile.check_cache)
1323 1321
1324 1322 # The instance will store a pointer to the system-wide exception hook,
1325 1323 # so that runtime code (such as magics) can access it. This is because
1326 1324 # during the read-eval loop, it may get temporarily overwritten.
1327 1325 self.sys_excepthook = sys.excepthook
1328 1326
1329 1327 # and add any custom exception handlers the user may have specified
1330 1328 self.set_custom_exc(*custom_exceptions)
1331 1329
1332 1330 # Set the exception mode
1333 1331 self.InteractiveTB.set_mode(mode=self.xmode)
1334 1332
1335 1333 def set_custom_exc(self, exc_tuple, handler):
1336 1334 """set_custom_exc(exc_tuple,handler)
1337 1335
1338 1336 Set a custom exception handler, which will be called if any of the
1339 1337 exceptions in exc_tuple occur in the mainloop (specifically, in the
1340 1338 run_code() method.
1341 1339
1342 1340 Inputs:
1343 1341
1344 1342 - exc_tuple: a *tuple* of valid exceptions to call the defined
1345 1343 handler for. It is very important that you use a tuple, and NOT A
1346 1344 LIST here, because of the way Python's except statement works. If
1347 1345 you only want to trap a single exception, use a singleton tuple:
1348 1346
1349 1347 exc_tuple == (MyCustomException,)
1350 1348
1351 1349 - handler: this must be defined as a function with the following
1352 1350 basic interface::
1353 1351
1354 1352 def my_handler(self, etype, value, tb, tb_offset=None)
1355 1353 ...
1356 1354 # The return value must be
1357 1355 return structured_traceback
1358 1356
1359 1357 This will be made into an instance method (via types.MethodType)
1360 1358 of IPython itself, and it will be called if any of the exceptions
1361 1359 listed in the exc_tuple are caught. If the handler is None, an
1362 1360 internal basic one is used, which just prints basic info.
1363 1361
1364 1362 WARNING: by putting in your own exception handler into IPython's main
1365 1363 execution loop, you run a very good chance of nasty crashes. This
1366 1364 facility should only be used if you really know what you are doing."""
1367 1365
1368 1366 assert type(exc_tuple)==type(()) , \
1369 1367 "The custom exceptions must be given AS A TUPLE."
1370 1368
1371 1369 def dummy_handler(self,etype,value,tb):
1372 1370 print '*** Simple custom exception handler ***'
1373 1371 print 'Exception type :',etype
1374 1372 print 'Exception value:',value
1375 1373 print 'Traceback :',tb
1376 1374 #print 'Source code :','\n'.join(self.buffer)
1377 1375
1378 1376 if handler is None: handler = dummy_handler
1379 1377
1380 1378 self.CustomTB = types.MethodType(handler,self)
1381 1379 self.custom_exceptions = exc_tuple
1382 1380
1383 1381 def excepthook(self, etype, value, tb):
1384 1382 """One more defense for GUI apps that call sys.excepthook.
1385 1383
1386 1384 GUI frameworks like wxPython trap exceptions and call
1387 1385 sys.excepthook themselves. I guess this is a feature that
1388 1386 enables them to keep running after exceptions that would
1389 1387 otherwise kill their mainloop. This is a bother for IPython
1390 1388 which excepts to catch all of the program exceptions with a try:
1391 1389 except: statement.
1392 1390
1393 1391 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1394 1392 any app directly invokes sys.excepthook, it will look to the user like
1395 1393 IPython crashed. In order to work around this, we can disable the
1396 1394 CrashHandler and replace it with this excepthook instead, which prints a
1397 1395 regular traceback using our InteractiveTB. In this fashion, apps which
1398 1396 call sys.excepthook will generate a regular-looking exception from
1399 1397 IPython, and the CrashHandler will only be triggered by real IPython
1400 1398 crashes.
1401 1399
1402 1400 This hook should be used sparingly, only in places which are not likely
1403 1401 to be true IPython errors.
1404 1402 """
1405 1403 self.showtraceback((etype,value,tb),tb_offset=0)
1406 1404
1407 1405 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1408 1406 exception_only=False):
1409 1407 """Display the exception that just occurred.
1410 1408
1411 1409 If nothing is known about the exception, this is the method which
1412 1410 should be used throughout the code for presenting user tracebacks,
1413 1411 rather than directly invoking the InteractiveTB object.
1414 1412
1415 1413 A specific showsyntaxerror() also exists, but this method can take
1416 1414 care of calling it if needed, so unless you are explicitly catching a
1417 1415 SyntaxError exception, don't try to analyze the stack manually and
1418 1416 simply call this method."""
1419 1417
1420 1418 try:
1421 1419 if exc_tuple is None:
1422 1420 etype, value, tb = sys.exc_info()
1423 1421 else:
1424 1422 etype, value, tb = exc_tuple
1425 1423
1426 1424 if etype is None:
1427 1425 if hasattr(sys, 'last_type'):
1428 1426 etype, value, tb = sys.last_type, sys.last_value, \
1429 1427 sys.last_traceback
1430 1428 else:
1431 1429 self.write_err('No traceback available to show.\n')
1432 1430 return
1433 1431
1434 1432 if etype is SyntaxError:
1435 1433 # Though this won't be called by syntax errors in the input
1436 1434 # line, there may be SyntaxError cases whith imported code.
1437 1435 self.showsyntaxerror(filename)
1438 1436 elif etype is UsageError:
1439 1437 print "UsageError:", value
1440 1438 else:
1441 1439 # WARNING: these variables are somewhat deprecated and not
1442 1440 # necessarily safe to use in a threaded environment, but tools
1443 1441 # like pdb depend on their existence, so let's set them. If we
1444 1442 # find problems in the field, we'll need to revisit their use.
1445 1443 sys.last_type = etype
1446 1444 sys.last_value = value
1447 1445 sys.last_traceback = tb
1448 1446 if etype in self.custom_exceptions:
1449 1447 # FIXME: Old custom traceback objects may just return a
1450 1448 # string, in that case we just put it into a list
1451 1449 stb = self.CustomTB(etype, value, tb, tb_offset)
1452 1450 if isinstance(ctb, basestring):
1453 1451 stb = [stb]
1454 1452 else:
1455 1453 if exception_only:
1456 1454 stb = ['An exception has occurred, use %tb to see '
1457 1455 'the full traceback.\n']
1458 1456 stb.extend(self.InteractiveTB.get_exception_only(etype,
1459 1457 value))
1460 1458 else:
1461 1459 stb = self.InteractiveTB.structured_traceback(etype,
1462 1460 value, tb, tb_offset=tb_offset)
1463 1461
1464 1462 if self.call_pdb:
1465 1463 # drop into debugger
1466 1464 self.debugger(force=True)
1467 1465
1468 1466 # Actually show the traceback
1469 1467 self._showtraceback(etype, value, stb)
1470 1468
1471 1469 except KeyboardInterrupt:
1472 1470 self.write_err("\nKeyboardInterrupt\n")
1473 1471
1474 1472 def _showtraceback(self, etype, evalue, stb):
1475 1473 """Actually show a traceback.
1476 1474
1477 1475 Subclasses may override this method to put the traceback on a different
1478 1476 place, like a side channel.
1479 1477 """
1480 1478 print >> io.stdout, self.InteractiveTB.stb2text(stb)
1481 1479
1482 1480 def showsyntaxerror(self, filename=None):
1483 1481 """Display the syntax error that just occurred.
1484 1482
1485 1483 This doesn't display a stack trace because there isn't one.
1486 1484
1487 1485 If a filename is given, it is stuffed in the exception instead
1488 1486 of what was there before (because Python's parser always uses
1489 1487 "<string>" when reading from a string).
1490 1488 """
1491 1489 etype, value, last_traceback = sys.exc_info()
1492 1490
1493 1491 # See note about these variables in showtraceback() above
1494 1492 sys.last_type = etype
1495 1493 sys.last_value = value
1496 1494 sys.last_traceback = last_traceback
1497 1495
1498 1496 if filename and etype is SyntaxError:
1499 1497 # Work hard to stuff the correct filename in the exception
1500 1498 try:
1501 1499 msg, (dummy_filename, lineno, offset, line) = value
1502 1500 except:
1503 1501 # Not the format we expect; leave it alone
1504 1502 pass
1505 1503 else:
1506 1504 # Stuff in the right filename
1507 1505 try:
1508 1506 # Assume SyntaxError is a class exception
1509 1507 value = SyntaxError(msg, (filename, lineno, offset, line))
1510 1508 except:
1511 1509 # If that failed, assume SyntaxError is a string
1512 1510 value = msg, (filename, lineno, offset, line)
1513 1511 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1514 1512 self._showtraceback(etype, value, stb)
1515 1513
1516 1514 #-------------------------------------------------------------------------
1517 1515 # Things related to readline
1518 1516 #-------------------------------------------------------------------------
1519 1517
1520 1518 def init_readline(self):
1521 1519 """Command history completion/saving/reloading."""
1522 1520
1523 1521 if self.readline_use:
1524 1522 import IPython.utils.rlineimpl as readline
1525 1523
1526 1524 self.rl_next_input = None
1527 1525 self.rl_do_indent = False
1528 1526
1529 1527 if not self.readline_use or not readline.have_readline:
1530 1528 self.has_readline = False
1531 1529 self.readline = None
1532 1530 # Set a number of methods that depend on readline to be no-op
1533 1531 self.set_readline_completer = no_op
1534 1532 self.set_custom_completer = no_op
1535 1533 self.set_completer_frame = no_op
1536 1534 warn('Readline services not available or not loaded.')
1537 1535 else:
1538 1536 self.has_readline = True
1539 1537 self.readline = readline
1540 1538 sys.modules['readline'] = readline
1541 1539
1542 1540 # Platform-specific configuration
1543 1541 if os.name == 'nt':
1544 1542 # FIXME - check with Frederick to see if we can harmonize
1545 1543 # naming conventions with pyreadline to avoid this
1546 1544 # platform-dependent check
1547 1545 self.readline_startup_hook = readline.set_pre_input_hook
1548 1546 else:
1549 1547 self.readline_startup_hook = readline.set_startup_hook
1550 1548
1551 1549 # Load user's initrc file (readline config)
1552 1550 # Or if libedit is used, load editrc.
1553 1551 inputrc_name = os.environ.get('INPUTRC')
1554 1552 if inputrc_name is None:
1555 1553 home_dir = get_home_dir()
1556 1554 if home_dir is not None:
1557 1555 inputrc_name = '.inputrc'
1558 1556 if readline.uses_libedit:
1559 1557 inputrc_name = '.editrc'
1560 1558 inputrc_name = os.path.join(home_dir, inputrc_name)
1561 1559 if os.path.isfile(inputrc_name):
1562 1560 try:
1563 1561 readline.read_init_file(inputrc_name)
1564 1562 except:
1565 1563 warn('Problems reading readline initialization file <%s>'
1566 1564 % inputrc_name)
1567 1565
1568 1566 # Configure readline according to user's prefs
1569 1567 # This is only done if GNU readline is being used. If libedit
1570 1568 # is being used (as on Leopard) the readline config is
1571 1569 # not run as the syntax for libedit is different.
1572 1570 if not readline.uses_libedit:
1573 1571 for rlcommand in self.readline_parse_and_bind:
1574 1572 #print "loading rl:",rlcommand # dbg
1575 1573 readline.parse_and_bind(rlcommand)
1576 1574
1577 1575 # Remove some chars from the delimiters list. If we encounter
1578 1576 # unicode chars, discard them.
1579 1577 delims = readline.get_completer_delims().encode("ascii", "ignore")
1580 1578 delims = delims.translate(None, self.readline_remove_delims)
1581 1579 delims = delims.replace(ESC_MAGIC, '')
1582 1580 readline.set_completer_delims(delims)
1583 1581 # otherwise we end up with a monster history after a while:
1584 1582 readline.set_history_length(self.history_length)
1585 1583
1586 1584 self.refill_readline_hist()
1587 1585 self.readline_no_record = ReadlineNoRecord(self)
1588 1586
1589 1587 # Configure auto-indent for all platforms
1590 1588 self.set_autoindent(self.autoindent)
1591 1589
1592 1590 def refill_readline_hist(self):
1593 1591 # Load the last 1000 lines from history
1594 1592 self.readline.clear_history()
1595 1593 stdin_encoding = sys.stdin.encoding or "utf-8"
1596 1594 for _, _, cell in self.history_manager.get_tail(1000,
1597 1595 include_latest=True):
1598 1596 if cell.strip(): # Ignore blank lines
1599 1597 for line in cell.splitlines():
1600 1598 self.readline.add_history(line.encode(stdin_encoding, 'replace'))
1601 1599
1602 1600 def set_next_input(self, s):
1603 1601 """ Sets the 'default' input string for the next command line.
1604 1602
1605 1603 Requires readline.
1606 1604
1607 1605 Example:
1608 1606
1609 1607 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1610 1608 [D:\ipython]|2> Hello Word_ # cursor is here
1611 1609 """
1612 1610
1613 1611 self.rl_next_input = s
1614 1612
1615 1613 # Maybe move this to the terminal subclass?
1616 1614 def pre_readline(self):
1617 1615 """readline hook to be used at the start of each line.
1618 1616
1619 1617 Currently it handles auto-indent only."""
1620 1618
1621 1619 if self.rl_do_indent:
1622 1620 self.readline.insert_text(self._indent_current_str())
1623 1621 if self.rl_next_input is not None:
1624 1622 self.readline.insert_text(self.rl_next_input)
1625 1623 self.rl_next_input = None
1626 1624
1627 1625 def _indent_current_str(self):
1628 1626 """return the current level of indentation as a string"""
1629 1627 return self.input_splitter.indent_spaces * ' '
1630 1628
1631 1629 #-------------------------------------------------------------------------
1632 1630 # Things related to text completion
1633 1631 #-------------------------------------------------------------------------
1634 1632
1635 1633 def init_completer(self):
1636 1634 """Initialize the completion machinery.
1637 1635
1638 1636 This creates completion machinery that can be used by client code,
1639 1637 either interactively in-process (typically triggered by the readline
1640 1638 library), programatically (such as in test suites) or out-of-prcess
1641 1639 (typically over the network by remote frontends).
1642 1640 """
1643 1641 from IPython.core.completer import IPCompleter
1644 1642 from IPython.core.completerlib import (module_completer,
1645 1643 magic_run_completer, cd_completer)
1646 1644
1647 1645 self.Completer = IPCompleter(self,
1648 1646 self.user_ns,
1649 1647 self.user_global_ns,
1650 1648 self.readline_omit__names,
1651 1649 self.alias_manager.alias_table,
1652 1650 self.has_readline)
1653 1651
1654 1652 # Add custom completers to the basic ones built into IPCompleter
1655 1653 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1656 1654 self.strdispatchers['complete_command'] = sdisp
1657 1655 self.Completer.custom_completers = sdisp
1658 1656
1659 1657 self.set_hook('complete_command', module_completer, str_key = 'import')
1660 1658 self.set_hook('complete_command', module_completer, str_key = 'from')
1661 1659 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1662 1660 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1663 1661
1664 1662 # Only configure readline if we truly are using readline. IPython can
1665 1663 # do tab-completion over the network, in GUIs, etc, where readline
1666 1664 # itself may be absent
1667 1665 if self.has_readline:
1668 1666 self.set_readline_completer()
1669 1667
1670 1668 def complete(self, text, line=None, cursor_pos=None):
1671 1669 """Return the completed text and a list of completions.
1672 1670
1673 1671 Parameters
1674 1672 ----------
1675 1673
1676 1674 text : string
1677 1675 A string of text to be completed on. It can be given as empty and
1678 1676 instead a line/position pair are given. In this case, the
1679 1677 completer itself will split the line like readline does.
1680 1678
1681 1679 line : string, optional
1682 1680 The complete line that text is part of.
1683 1681
1684 1682 cursor_pos : int, optional
1685 1683 The position of the cursor on the input line.
1686 1684
1687 1685 Returns
1688 1686 -------
1689 1687 text : string
1690 1688 The actual text that was completed.
1691 1689
1692 1690 matches : list
1693 1691 A sorted list with all possible completions.
1694 1692
1695 1693 The optional arguments allow the completion to take more context into
1696 1694 account, and are part of the low-level completion API.
1697 1695
1698 1696 This is a wrapper around the completion mechanism, similar to what
1699 1697 readline does at the command line when the TAB key is hit. By
1700 1698 exposing it as a method, it can be used by other non-readline
1701 1699 environments (such as GUIs) for text completion.
1702 1700
1703 1701 Simple usage example:
1704 1702
1705 1703 In [1]: x = 'hello'
1706 1704
1707 1705 In [2]: _ip.complete('x.l')
1708 1706 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1709 1707 """
1710 1708
1711 1709 # Inject names into __builtin__ so we can complete on the added names.
1712 1710 with self.builtin_trap:
1713 1711 return self.Completer.complete(text, line, cursor_pos)
1714 1712
1715 1713 def set_custom_completer(self, completer, pos=0):
1716 1714 """Adds a new custom completer function.
1717 1715
1718 1716 The position argument (defaults to 0) is the index in the completers
1719 1717 list where you want the completer to be inserted."""
1720 1718
1721 1719 newcomp = types.MethodType(completer,self.Completer)
1722 1720 self.Completer.matchers.insert(pos,newcomp)
1723 1721
1724 1722 def set_readline_completer(self):
1725 1723 """Reset readline's completer to be our own."""
1726 1724 self.readline.set_completer(self.Completer.rlcomplete)
1727 1725
1728 1726 def set_completer_frame(self, frame=None):
1729 1727 """Set the frame of the completer."""
1730 1728 if frame:
1731 1729 self.Completer.namespace = frame.f_locals
1732 1730 self.Completer.global_namespace = frame.f_globals
1733 1731 else:
1734 1732 self.Completer.namespace = self.user_ns
1735 1733 self.Completer.global_namespace = self.user_global_ns
1736 1734
1737 1735 #-------------------------------------------------------------------------
1738 1736 # Things related to magics
1739 1737 #-------------------------------------------------------------------------
1740 1738
1741 1739 def init_magics(self):
1742 1740 # FIXME: Move the color initialization to the DisplayHook, which
1743 1741 # should be split into a prompt manager and displayhook. We probably
1744 1742 # even need a centralize colors management object.
1745 1743 self.magic_colors(self.colors)
1746 1744 # History was moved to a separate module
1747 1745 from . import history
1748 1746 history.init_ipython(self)
1749 1747
1750 1748 def magic(self,arg_s):
1751 1749 """Call a magic function by name.
1752 1750
1753 1751 Input: a string containing the name of the magic function to call and
1754 1752 any additional arguments to be passed to the magic.
1755 1753
1756 1754 magic('name -opt foo bar') is equivalent to typing at the ipython
1757 1755 prompt:
1758 1756
1759 1757 In[1]: %name -opt foo bar
1760 1758
1761 1759 To call a magic without arguments, simply use magic('name').
1762 1760
1763 1761 This provides a proper Python function to call IPython's magics in any
1764 1762 valid Python code you can type at the interpreter, including loops and
1765 1763 compound statements.
1766 1764 """
1767 1765 args = arg_s.split(' ',1)
1768 1766 magic_name = args[0]
1769 1767 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1770 1768
1771 1769 try:
1772 1770 magic_args = args[1]
1773 1771 except IndexError:
1774 1772 magic_args = ''
1775 1773 fn = getattr(self,'magic_'+magic_name,None)
1776 1774 if fn is None:
1777 1775 error("Magic function `%s` not found." % magic_name)
1778 1776 else:
1779 1777 magic_args = self.var_expand(magic_args,1)
1780 1778 # Grab local namespace if we need it:
1781 1779 if getattr(fn, "needs_local_scope", False):
1782 1780 self._magic_locals = sys._getframe(1).f_locals
1783 1781 with self.builtin_trap:
1784 1782 result = fn(magic_args)
1785 1783 # Ensure we're not keeping object references around:
1786 1784 self._magic_locals = {}
1787 1785 return result
1788 1786
1789 1787 def define_magic(self, magicname, func):
1790 1788 """Expose own function as magic function for ipython
1791 1789
1792 1790 def foo_impl(self,parameter_s=''):
1793 1791 'My very own magic!. (Use docstrings, IPython reads them).'
1794 1792 print 'Magic function. Passed parameter is between < >:'
1795 1793 print '<%s>' % parameter_s
1796 1794 print 'The self object is:',self
1797 1795
1798 1796 self.define_magic('foo',foo_impl)
1799 1797 """
1800 1798
1801 1799 import new
1802 1800 im = types.MethodType(func,self)
1803 1801 old = getattr(self, "magic_" + magicname, None)
1804 1802 setattr(self, "magic_" + magicname, im)
1805 1803 return old
1806 1804
1807 1805 #-------------------------------------------------------------------------
1808 1806 # Things related to macros
1809 1807 #-------------------------------------------------------------------------
1810 1808
1811 1809 def define_macro(self, name, themacro):
1812 1810 """Define a new macro
1813 1811
1814 1812 Parameters
1815 1813 ----------
1816 1814 name : str
1817 1815 The name of the macro.
1818 1816 themacro : str or Macro
1819 1817 The action to do upon invoking the macro. If a string, a new
1820 1818 Macro object is created by passing the string to it.
1821 1819 """
1822 1820
1823 1821 from IPython.core import macro
1824 1822
1825 1823 if isinstance(themacro, basestring):
1826 1824 themacro = macro.Macro(themacro)
1827 1825 if not isinstance(themacro, macro.Macro):
1828 1826 raise ValueError('A macro must be a string or a Macro instance.')
1829 1827 self.user_ns[name] = themacro
1830 1828
1831 1829 #-------------------------------------------------------------------------
1832 1830 # Things related to the running of system commands
1833 1831 #-------------------------------------------------------------------------
1834 1832
1835 1833 def system(self, cmd):
1836 1834 """Call the given cmd in a subprocess.
1837 1835
1838 1836 Parameters
1839 1837 ----------
1840 1838 cmd : str
1841 1839 Command to execute (can not end in '&', as bacground processes are
1842 1840 not supported.
1843 1841 """
1844 1842 # We do not support backgrounding processes because we either use
1845 1843 # pexpect or pipes to read from. Users can always just call
1846 1844 # os.system() if they really want a background process.
1847 1845 if cmd.endswith('&'):
1848 1846 raise OSError("Background processes not supported.")
1849 1847
1850 1848 return system(self.var_expand(cmd, depth=2))
1851 1849
1852 1850 def getoutput(self, cmd, split=True):
1853 1851 """Get output (possibly including stderr) from a subprocess.
1854 1852
1855 1853 Parameters
1856 1854 ----------
1857 1855 cmd : str
1858 1856 Command to execute (can not end in '&', as background processes are
1859 1857 not supported.
1860 1858 split : bool, optional
1861 1859
1862 1860 If True, split the output into an IPython SList. Otherwise, an
1863 1861 IPython LSString is returned. These are objects similar to normal
1864 1862 lists and strings, with a few convenience attributes for easier
1865 1863 manipulation of line-based output. You can use '?' on them for
1866 1864 details.
1867 1865 """
1868 1866 if cmd.endswith('&'):
1869 1867 raise OSError("Background processes not supported.")
1870 1868 out = getoutput(self.var_expand(cmd, depth=2))
1871 1869 if split:
1872 1870 out = SList(out.splitlines())
1873 1871 else:
1874 1872 out = LSString(out)
1875 1873 return out
1876 1874
1877 1875 #-------------------------------------------------------------------------
1878 1876 # Things related to aliases
1879 1877 #-------------------------------------------------------------------------
1880 1878
1881 1879 def init_alias(self):
1882 1880 self.alias_manager = AliasManager(shell=self, config=self.config)
1883 1881 self.ns_table['alias'] = self.alias_manager.alias_table,
1884 1882
1885 1883 #-------------------------------------------------------------------------
1886 1884 # Things related to extensions and plugins
1887 1885 #-------------------------------------------------------------------------
1888 1886
1889 1887 def init_extension_manager(self):
1890 1888 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1891 1889
1892 1890 def init_plugin_manager(self):
1893 1891 self.plugin_manager = PluginManager(config=self.config)
1894 1892
1895 1893 #-------------------------------------------------------------------------
1896 1894 # Things related to payloads
1897 1895 #-------------------------------------------------------------------------
1898 1896
1899 1897 def init_payload(self):
1900 1898 self.payload_manager = PayloadManager(config=self.config)
1901 1899
1902 1900 #-------------------------------------------------------------------------
1903 1901 # Things related to the prefilter
1904 1902 #-------------------------------------------------------------------------
1905 1903
1906 1904 def init_prefilter(self):
1907 1905 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1908 1906 # Ultimately this will be refactored in the new interpreter code, but
1909 1907 # for now, we should expose the main prefilter method (there's legacy
1910 1908 # code out there that may rely on this).
1911 1909 self.prefilter = self.prefilter_manager.prefilter_lines
1912 1910
1913 1911 def auto_rewrite_input(self, cmd):
1914 1912 """Print to the screen the rewritten form of the user's command.
1915 1913
1916 1914 This shows visual feedback by rewriting input lines that cause
1917 1915 automatic calling to kick in, like::
1918 1916
1919 1917 /f x
1920 1918
1921 1919 into::
1922 1920
1923 1921 ------> f(x)
1924 1922
1925 1923 after the user's input prompt. This helps the user understand that the
1926 1924 input line was transformed automatically by IPython.
1927 1925 """
1928 1926 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1929 1927
1930 1928 try:
1931 1929 # plain ascii works better w/ pyreadline, on some machines, so
1932 1930 # we use it and only print uncolored rewrite if we have unicode
1933 1931 rw = str(rw)
1934 1932 print >> io.stdout, rw
1935 1933 except UnicodeEncodeError:
1936 1934 print "------> " + cmd
1937 1935
1938 1936 #-------------------------------------------------------------------------
1939 1937 # Things related to extracting values/expressions from kernel and user_ns
1940 1938 #-------------------------------------------------------------------------
1941 1939
1942 1940 def _simple_error(self):
1943 1941 etype, value = sys.exc_info()[:2]
1944 1942 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1945 1943
1946 1944 def user_variables(self, names):
1947 1945 """Get a list of variable names from the user's namespace.
1948 1946
1949 1947 Parameters
1950 1948 ----------
1951 1949 names : list of strings
1952 1950 A list of names of variables to be read from the user namespace.
1953 1951
1954 1952 Returns
1955 1953 -------
1956 1954 A dict, keyed by the input names and with the repr() of each value.
1957 1955 """
1958 1956 out = {}
1959 1957 user_ns = self.user_ns
1960 1958 for varname in names:
1961 1959 try:
1962 1960 value = repr(user_ns[varname])
1963 1961 except:
1964 1962 value = self._simple_error()
1965 1963 out[varname] = value
1966 1964 return out
1967 1965
1968 1966 def user_expressions(self, expressions):
1969 1967 """Evaluate a dict of expressions in the user's namespace.
1970 1968
1971 1969 Parameters
1972 1970 ----------
1973 1971 expressions : dict
1974 1972 A dict with string keys and string values. The expression values
1975 1973 should be valid Python expressions, each of which will be evaluated
1976 1974 in the user namespace.
1977 1975
1978 1976 Returns
1979 1977 -------
1980 1978 A dict, keyed like the input expressions dict, with the repr() of each
1981 1979 value.
1982 1980 """
1983 1981 out = {}
1984 1982 user_ns = self.user_ns
1985 1983 global_ns = self.user_global_ns
1986 1984 for key, expr in expressions.iteritems():
1987 1985 try:
1988 1986 value = repr(eval(expr, global_ns, user_ns))
1989 1987 except:
1990 1988 value = self._simple_error()
1991 1989 out[key] = value
1992 1990 return out
1993 1991
1994 1992 #-------------------------------------------------------------------------
1995 1993 # Things related to the running of code
1996 1994 #-------------------------------------------------------------------------
1997 1995
1998 1996 def ex(self, cmd):
1999 1997 """Execute a normal python statement in user namespace."""
2000 1998 with self.builtin_trap:
2001 1999 exec cmd in self.user_global_ns, self.user_ns
2002 2000
2003 2001 def ev(self, expr):
2004 2002 """Evaluate python expression expr in user namespace.
2005 2003
2006 2004 Returns the result of evaluation
2007 2005 """
2008 2006 with self.builtin_trap:
2009 2007 return eval(expr, self.user_global_ns, self.user_ns)
2010 2008
2011 2009 def safe_execfile(self, fname, *where, **kw):
2012 2010 """A safe version of the builtin execfile().
2013 2011
2014 2012 This version will never throw an exception, but instead print
2015 2013 helpful error messages to the screen. This only works on pure
2016 2014 Python files with the .py extension.
2017 2015
2018 2016 Parameters
2019 2017 ----------
2020 2018 fname : string
2021 2019 The name of the file to be executed.
2022 2020 where : tuple
2023 2021 One or two namespaces, passed to execfile() as (globals,locals).
2024 2022 If only one is given, it is passed as both.
2025 2023 exit_ignore : bool (False)
2026 2024 If True, then silence SystemExit for non-zero status (it is always
2027 2025 silenced for zero status, as it is so common).
2028 2026 """
2029 2027 kw.setdefault('exit_ignore', False)
2030 2028
2031 2029 fname = os.path.abspath(os.path.expanduser(fname))
2032 2030 # Make sure we have a .py file
2033 2031 if not fname.endswith('.py'):
2034 2032 warn('File must end with .py to be run using execfile: <%s>' % fname)
2035 2033
2036 2034 # Make sure we can open the file
2037 2035 try:
2038 2036 with open(fname) as thefile:
2039 2037 pass
2040 2038 except:
2041 2039 warn('Could not open file <%s> for safe execution.' % fname)
2042 2040 return
2043 2041
2044 2042 # Find things also in current directory. This is needed to mimic the
2045 2043 # behavior of running a script from the system command line, where
2046 2044 # Python inserts the script's directory into sys.path
2047 2045 dname = os.path.dirname(fname)
2048 2046
2049 2047 if isinstance(fname, unicode):
2050 2048 # execfile uses default encoding instead of filesystem encoding
2051 2049 # so unicode filenames will fail
2052 2050 fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
2053 2051
2054 2052 with prepended_to_syspath(dname):
2055 2053 try:
2056 2054 execfile(fname,*where)
2057 2055 except SystemExit, status:
2058 2056 # If the call was made with 0 or None exit status (sys.exit(0)
2059 2057 # or sys.exit() ), don't bother showing a traceback, as both of
2060 2058 # these are considered normal by the OS:
2061 2059 # > python -c'import sys;sys.exit(0)'; echo $?
2062 2060 # 0
2063 2061 # > python -c'import sys;sys.exit()'; echo $?
2064 2062 # 0
2065 2063 # For other exit status, we show the exception unless
2066 2064 # explicitly silenced, but only in short form.
2067 2065 if status.code not in (0, None) and not kw['exit_ignore']:
2068 2066 self.showtraceback(exception_only=True)
2069 2067 except:
2070 2068 self.showtraceback()
2071 2069
2072 2070 def safe_execfile_ipy(self, fname):
2073 2071 """Like safe_execfile, but for .ipy files with IPython syntax.
2074 2072
2075 2073 Parameters
2076 2074 ----------
2077 2075 fname : str
2078 2076 The name of the file to execute. The filename must have a
2079 2077 .ipy extension.
2080 2078 """
2081 2079 fname = os.path.abspath(os.path.expanduser(fname))
2082 2080
2083 2081 # Make sure we have a .py file
2084 2082 if not fname.endswith('.ipy'):
2085 2083 warn('File must end with .py to be run using execfile: <%s>' % fname)
2086 2084
2087 2085 # Make sure we can open the file
2088 2086 try:
2089 2087 with open(fname) as thefile:
2090 2088 pass
2091 2089 except:
2092 2090 warn('Could not open file <%s> for safe execution.' % fname)
2093 2091 return
2094 2092
2095 2093 # Find things also in current directory. This is needed to mimic the
2096 2094 # behavior of running a script from the system command line, where
2097 2095 # Python inserts the script's directory into sys.path
2098 2096 dname = os.path.dirname(fname)
2099 2097
2100 2098 with prepended_to_syspath(dname):
2101 2099 try:
2102 2100 with open(fname) as thefile:
2103 2101 # self.run_cell currently captures all exceptions
2104 2102 # raised in user code. It would be nice if there were
2105 2103 # versions of runlines, execfile that did raise, so
2106 2104 # we could catch the errors.
2107 2105 self.run_cell(thefile.read(), store_history=False)
2108 2106 except:
2109 2107 self.showtraceback()
2110 2108 warn('Unknown failure executing file: <%s>' % fname)
2111 2109
2112 2110 def run_cell(self, raw_cell, store_history=True):
2113 2111 """Run a complete IPython cell.
2114 2112
2115 2113 Parameters
2116 2114 ----------
2117 2115 raw_cell : str
2118 2116 The code (including IPython code such as %magic functions) to run.
2119 2117 store_history : bool
2120 2118 If True, the raw and translated cell will be stored in IPython's
2121 2119 history. For user code calling back into IPython's machinery, this
2122 2120 should be set to False.
2123 2121 """
2124 2122 if (not raw_cell) or raw_cell.isspace():
2125 2123 return
2126 2124
2127 2125 for line in raw_cell.splitlines():
2128 2126 self.input_splitter.push(line)
2129 2127 cell = self.input_splitter.source_reset()
2130 2128
2131 2129 with self.builtin_trap:
2132 2130 prefilter_failed = False
2133 2131 if len(cell.splitlines()) == 1:
2134 2132 try:
2135 2133 cell = self.prefilter_manager.prefilter_lines(cell)
2136 2134 except AliasError as e:
2137 2135 error(e)
2138 2136 prefilter_failed=True
2139 2137 except Exception:
2140 2138 # don't allow prefilter errors to crash IPython
2141 2139 self.showtraceback()
2142 2140 prefilter_failed = True
2143 2141
2144 2142 # Store raw and processed history
2145 2143 if store_history:
2146 2144 self.history_manager.store_inputs(self.execution_count,
2147 2145 cell, raw_cell)
2148 2146
2149 2147 self.logger.log(cell, raw_cell)
2150 2148
2151 2149 if not prefilter_failed:
2152 2150 # don't run if prefilter failed
2153 2151 cell_name = self.compile.cache(cell, self.execution_count)
2154 2152
2155 2153 with self.display_trap:
2156 2154 try:
2157 2155 code_ast = ast.parse(cell, filename=cell_name)
2158 2156 except (OverflowError, SyntaxError, ValueError, TypeError,
2159 2157 MemoryError):
2160 2158 self.showsyntaxerror()
2161 2159 self.execution_count += 1
2162 2160 return None
2163 2161
2164 2162 self.run_ast_nodes(code_ast.body, cell_name,
2165 2163 interactivity="last_expr")
2166 2164
2167 2165 # Execute any registered post-execution functions.
2168 2166 for func, status in self._post_execute.iteritems():
2169 2167 if not status:
2170 2168 continue
2171 2169 try:
2172 2170 func()
2173 2171 except:
2174 2172 self.showtraceback()
2175 2173 # Deactivate failing function
2176 2174 self._post_execute[func] = False
2177 2175
2178 2176 if store_history:
2179 2177 # Write output to the database. Does nothing unless
2180 2178 # history output logging is enabled.
2181 2179 self.history_manager.store_output(self.execution_count)
2182 2180 # Each cell is a *single* input, regardless of how many lines it has
2183 2181 self.execution_count += 1
2184 2182
2185 2183 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr'):
2186 2184 """Run a sequence of AST nodes. The execution mode depends on the
2187 2185 interactivity parameter.
2188 2186
2189 2187 Parameters
2190 2188 ----------
2191 2189 nodelist : list
2192 2190 A sequence of AST nodes to run.
2193 2191 cell_name : str
2194 2192 Will be passed to the compiler as the filename of the cell. Typically
2195 2193 the value returned by ip.compile.cache(cell).
2196 2194 interactivity : str
2197 2195 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2198 2196 run interactively (displaying output from expressions). 'last_expr'
2199 2197 will run the last node interactively only if it is an expression (i.e.
2200 2198 expressions in loops or other blocks are not displayed. Other values
2201 2199 for this parameter will raise a ValueError.
2202 2200 """
2203 2201 if not nodelist:
2204 2202 return
2205 2203
2206 2204 if interactivity == 'last_expr':
2207 2205 if isinstance(nodelist[-1], ast.Expr):
2208 2206 interactivity = "last"
2209 2207 else:
2210 2208 interactivity = "none"
2211 2209
2212 2210 if interactivity == 'none':
2213 2211 to_run_exec, to_run_interactive = nodelist, []
2214 2212 elif interactivity == 'last':
2215 2213 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2216 2214 elif interactivity == 'all':
2217 2215 to_run_exec, to_run_interactive = [], nodelist
2218 2216 else:
2219 2217 raise ValueError("Interactivity was %r" % interactivity)
2220 2218
2221 2219 exec_count = self.execution_count
2222 2220
2223 2221 for i, node in enumerate(to_run_exec):
2224 2222 mod = ast.Module([node])
2225 2223 code = self.compile(mod, cell_name, "exec")
2226 2224 if self.run_code(code):
2227 2225 return True
2228 2226
2229 2227 for i, node in enumerate(to_run_interactive):
2230 2228 mod = ast.Interactive([node])
2231 2229 code = self.compile(mod, cell_name, "single")
2232 2230 if self.run_code(code):
2233 2231 return True
2234 2232
2235 2233 return False
2236 2234
2237 2235 def run_code(self, code_obj):
2238 2236 """Execute a code object.
2239 2237
2240 2238 When an exception occurs, self.showtraceback() is called to display a
2241 2239 traceback.
2242 2240
2243 2241 Parameters
2244 2242 ----------
2245 2243 code_obj : code object
2246 2244 A compiled code object, to be executed
2247 2245 post_execute : bool [default: True]
2248 2246 whether to call post_execute hooks after this particular execution.
2249 2247
2250 2248 Returns
2251 2249 -------
2252 2250 False : successful execution.
2253 2251 True : an error occurred.
2254 2252 """
2255 2253
2256 2254 # Set our own excepthook in case the user code tries to call it
2257 2255 # directly, so that the IPython crash handler doesn't get triggered
2258 2256 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2259 2257
2260 2258 # we save the original sys.excepthook in the instance, in case config
2261 2259 # code (such as magics) needs access to it.
2262 2260 self.sys_excepthook = old_excepthook
2263 2261 outflag = 1 # happens in more places, so it's easier as default
2264 2262 try:
2265 2263 try:
2266 2264 self.hooks.pre_run_code_hook()
2267 2265 #rprint('Running code', repr(code_obj)) # dbg
2268 2266 exec code_obj in self.user_global_ns, self.user_ns
2269 2267 finally:
2270 2268 # Reset our crash handler in place
2271 2269 sys.excepthook = old_excepthook
2272 2270 except SystemExit:
2273 2271 self.showtraceback(exception_only=True)
2274 2272 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2275 2273 except self.custom_exceptions:
2276 2274 etype,value,tb = sys.exc_info()
2277 2275 self.CustomTB(etype,value,tb)
2278 2276 except:
2279 2277 self.showtraceback()
2280 2278 else:
2281 2279 outflag = 0
2282 2280 if softspace(sys.stdout, 0):
2283 2281 print
2284 2282
2285 2283 return outflag
2286 2284
2287 2285 # For backwards compatibility
2288 2286 runcode = run_code
2289 2287
2290 2288 #-------------------------------------------------------------------------
2291 2289 # Things related to GUI support and pylab
2292 2290 #-------------------------------------------------------------------------
2293 2291
2294 2292 def enable_pylab(self, gui=None):
2295 2293 raise NotImplementedError('Implement enable_pylab in a subclass')
2296 2294
2297 2295 #-------------------------------------------------------------------------
2298 2296 # Utilities
2299 2297 #-------------------------------------------------------------------------
2300 2298
2301 2299 def var_expand(self,cmd,depth=0):
2302 2300 """Expand python variables in a string.
2303 2301
2304 2302 The depth argument indicates how many frames above the caller should
2305 2303 be walked to look for the local namespace where to expand variables.
2306 2304
2307 2305 The global namespace for expansion is always the user's interactive
2308 2306 namespace.
2309 2307 """
2310 2308 res = ItplNS(cmd, self.user_ns, # globals
2311 2309 # Skip our own frame in searching for locals:
2312 2310 sys._getframe(depth+1).f_locals # locals
2313 2311 )
2314 2312 return str(res).decode(res.codec)
2315 2313
2316 2314 def mktempfile(self, data=None, prefix='ipython_edit_'):
2317 2315 """Make a new tempfile and return its filename.
2318 2316
2319 2317 This makes a call to tempfile.mktemp, but it registers the created
2320 2318 filename internally so ipython cleans it up at exit time.
2321 2319
2322 2320 Optional inputs:
2323 2321
2324 2322 - data(None): if data is given, it gets written out to the temp file
2325 2323 immediately, and the file is closed again."""
2326 2324
2327 2325 filename = tempfile.mktemp('.py', prefix)
2328 2326 self.tempfiles.append(filename)
2329 2327
2330 2328 if data:
2331 2329 tmp_file = open(filename,'w')
2332 2330 tmp_file.write(data)
2333 2331 tmp_file.close()
2334 2332 return filename
2335 2333
2336 2334 # TODO: This should be removed when Term is refactored.
2337 2335 def write(self,data):
2338 2336 """Write a string to the default output"""
2339 2337 io.stdout.write(data)
2340 2338
2341 2339 # TODO: This should be removed when Term is refactored.
2342 2340 def write_err(self,data):
2343 2341 """Write a string to the default error output"""
2344 2342 io.stderr.write(data)
2345 2343
2346 2344 def ask_yes_no(self,prompt,default=True):
2347 2345 if self.quiet:
2348 2346 return True
2349 2347 return ask_yes_no(prompt,default)
2350 2348
2351 2349 def show_usage(self):
2352 2350 """Show a usage message"""
2353 2351 page.page(IPython.core.usage.interactive_usage)
2354 2352
2355 2353 def find_user_code(self, target, raw=True):
2356 2354 """Get a code string from history, file, or a string or macro.
2357 2355
2358 2356 This is mainly used by magic functions.
2359 2357
2360 2358 Parameters
2361 2359 ----------
2362 2360 target : str
2363 2361 A string specifying code to retrieve. This will be tried respectively
2364 2362 as: ranges of input history (see %history for syntax), a filename, or
2365 2363 an expression evaluating to a string or Macro in the user namespace.
2366 2364 raw : bool
2367 2365 If true (default), retrieve raw history. Has no effect on the other
2368 2366 retrieval mechanisms.
2369 2367
2370 2368 Returns
2371 2369 -------
2372 2370 A string of code.
2373 2371
2374 2372 ValueError is raised if nothing is found, and TypeError if it evaluates
2375 2373 to an object of another type. In each case, .args[0] is a printable
2376 2374 message.
2377 2375 """
2378 2376 code = self.extract_input_lines(target, raw=raw) # Grab history
2379 2377 if code:
2380 2378 return code
2381 2379 if os.path.isfile(target): # Read file
2382 2380 return open(target, "r").read()
2383 2381
2384 2382 try: # User namespace
2385 2383 codeobj = eval(target, self.user_ns)
2386 2384 except Exception:
2387 2385 raise ValueError(("'%s' was not found in history, as a file, nor in"
2388 2386 " the user namespace.") % target)
2389 2387 if isinstance(codeobj, basestring):
2390 2388 return codeobj
2391 2389 elif isinstance(codeobj, Macro):
2392 2390 return codeobj.value
2393 2391
2394 2392 raise TypeError("%s is neither a string nor a macro." % target,
2395 2393 codeobj)
2396 2394
2397 2395 #-------------------------------------------------------------------------
2398 2396 # Things related to IPython exiting
2399 2397 #-------------------------------------------------------------------------
2400 2398 def atexit_operations(self):
2401 2399 """This will be executed at the time of exit.
2402 2400
2403 2401 Cleanup operations and saving of persistent data that is done
2404 2402 unconditionally by IPython should be performed here.
2405 2403
2406 2404 For things that may depend on startup flags or platform specifics (such
2407 2405 as having readline or not), register a separate atexit function in the
2408 2406 code that has the appropriate information, rather than trying to
2409 2407 clutter
2410 2408 """
2411 2409 # Cleanup all tempfiles left around
2412 2410 for tfile in self.tempfiles:
2413 2411 try:
2414 2412 os.unlink(tfile)
2415 2413 except OSError:
2416 2414 pass
2417 2415
2418 2416 # Close the history session (this stores the end time and line count)
2419 2417 self.history_manager.end_session()
2420 2418
2421 2419 # Clear all user namespaces to release all references cleanly.
2422 2420 self.reset(new_session=False)
2423 2421
2424 2422 # Run user hooks
2425 2423 self.hooks.shutdown_hook()
2426 2424
2427 2425 def cleanup(self):
2428 2426 self.restore_sys_module_state()
2429 2427
2430 2428
2431 2429 class InteractiveShellABC(object):
2432 2430 """An abstract base class for InteractiveShell."""
2433 2431 __metaclass__ = abc.ABCMeta
2434 2432
2435 2433 InteractiveShellABC.register(InteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now