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