##// END OF EJS Templates
fix at least some command-line unicode options
fix at least some command-line unicode options

File last commit:

r3464:f71f71c1
r3464:f71f71c1
Show More
interactiveshell.py
2534 lines | 100.5 KiB | text/x-python | PythonLexer
/ IPython / core / interactiveshell.py
Ville M. Vainio
crlf -> lf
r1032 # -*- coding: utf-8 -*-
Brian Granger
First draft of refactored Component->Configurable.
r2731 """Main IPython class."""
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Massive, crazy refactoring of everything....
r2202 #-----------------------------------------------------------------------------
# Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
# Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
Fernando Perez
Improve docs and comments of some internal tools, and of testing code
r3297 # Copyright (C) 2008-2011 The IPython Development Team
Ville M. Vainio
crlf -> lf
r1032 #
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
Brian Granger
Massive, crazy refactoring of everything....
r2202 #-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
Brian Granger
Created context manager for the things injected into __builtin__.
r2227 from __future__ import with_statement
Fernando Perez
Fix %history magics....
r2421 from __future__ import absolute_import
Brian Granger
Created context manager for the things injected into __builtin__.
r2227
Ville M. Vainio
crlf -> lf
r1032 import __builtin__
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 import __future__
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 import abc
Fernando Perez
Fix bug where atexit operations were only done if readline was present.
r2953 import atexit
Ville M. Vainio
crlf -> lf
r1032 import codeop
import os
import re
import sys
import tempfile
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 import types
Brian Granger
sys.displayhook is now managed dynamically by display_trap.
r2231 from contextlib import nested
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 from IPython.config.configurable import Configurable
Brian Granger
OInspect.py => core/oinspect.py and imports updated.
r2037 from IPython.core import debugger, oinspect
Brian Granger
Massive, crazy refactoring of everything....
r2202 from IPython.core import history as ipcorehist
Fernando Perez
Get naked '?' to work, and in-spec with the new inputsplitter design.
r2876 from IPython.core import page
Brian Granger
Massive, crazy refactoring of everything....
r2202 from IPython.core import prefilter
Fernando Perez
First semi-complete support for -pylab and %pylab....
r2363 from IPython.core import shadowns
from IPython.core import ultratb
Brian Granger
More work on componentizing everything....
r2243 from IPython.core.alias import AliasManager
Brian Granger
Created context manager for the things injected into __builtin__.
r2227 from IPython.core.builtin_trap import BuiltinTrap
Fernando Perez
Complete implementation of interactive traceback support....
r3175 from IPython.core.compilerop import CachingCompiler
Brian Granger
sys.displayhook is now managed dynamically by display_trap.
r2231 from IPython.core.display_trap import DisplayTrap
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 from IPython.core.displayhook import DisplayHook
Brian Granger
Mostly final version of display data....
r3277 from IPython.core.displaypub import DisplayPublisher
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 from IPython.core.error import TryNext, UsageError
Brian Granger
First draft of refactored Component->Configurable.
r2731 from IPython.core.extensions import ExtensionManager
Brian Granger
FakeModule.py => core/fakemodule.py and updated tests and imports.
r2020 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
Brian Granger
Display system is fully working now....
r3278 from IPython.core.formatters import DisplayFormatter
MinRK
merge interactiveshell.py
r3122 from IPython.core.history import HistoryManager
Fernando Perez
Add experimental support for cell-based execution....
r2967 from IPython.core.inputsplitter import IPythonInputSplitter
Brian Granger
Logger.py => core/logger.py and updated imports.
r2032 from IPython.core.logger import Logger
Brian Granger
Magic.py => core/magic.py and imports updated.
r2036 from IPython.core.magic import Magic
Brian Granger
Fixing imports and syntax errors.
r2812 from IPython.core.payload import PayloadManager
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 from IPython.core.plugin import PluginManager
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
Brian Granger
Massive, crazy refactoring of everything....
r2202 from IPython.external.Itpl import ItplNS
from IPython.utils import PyColorize
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 from IPython.utils import io
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 from IPython.utils.doctestreload import doctest_reload
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 from IPython.utils.io import ask_yes_no, rprint
Fernando Perez
First semi-complete support for -pylab and %pylab....
r2363 from IPython.utils.ipstruct import Struct
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 from IPython.utils.pickleshare import PickleShareDB
Fernando Perez
Fully refactored subprocess handling on all platforms....
r2908 from IPython.utils.process import system, getoutput
Brian Granger
Work on startup related things....
r2252 from IPython.utils.strdispatch import StrDispatch
from IPython.utils.syspathcontext import prepended_to_syspath
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
List, Unicode, Instance, Type)
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 from IPython.utils.warn import warn, error, fatal
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 import IPython.core.hooks
Brian Granger
Massive, crazy refactoring of everything....
r2202
#-----------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032 # Globals
Brian Granger
Massive, crazy refactoring of everything....
r2202 #-----------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032 # compiled regexps for autoindent management
dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
Brian Granger
Massive, crazy refactoring of everything....
r2202 #-----------------------------------------------------------------------------
# Utilities
#-----------------------------------------------------------------------------
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # store the builtin raw_input globally, and use this always, in case user code
# overwrites it (like wx.py.PyShell does)
raw_input_original = raw_input
Brian Granger
Massive, crazy refactoring of everything....
r2202
Ville M. Vainio
crlf -> lf
r1032 def softspace(file, newvalue):
"""Copied from code.py, to remove the dependency"""
oldvalue = 0
try:
oldvalue = file.softspace
except AttributeError:
pass
try:
file.softspace = newvalue
except (AttributeError, TypeError):
# "attribute-less object" or "read-only attributes"
pass
return oldvalue
Fernando Perez
Better handling of no-readline.
r2377 def no_op(*a, **kw): pass
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 class SpaceInInput(Exception): pass
Ville M. Vainio
crlf -> lf
r1032
class Bunch: pass
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226
Brian Granger
Make the default colors OS dependent.
r2319 def get_default_colors():
if sys.platform=='darwin':
return "LightBG"
elif os.name=='nt':
return 'Linux'
else:
return 'Linux'
Brian Granger
Moved a few things back to InteractiveShell....
r2766 class SeparateStr(Str):
"""A Str subclass to validate separate_in, separate_out, etc.
This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
"""
def validate(self, obj, value):
if value == '0': value = ''
value = value.replace('\\n','\n')
return super(SeparateStr, self).validate(obj, value)
Brian Granger
Fixes to docs and InteractiveShell.instance()...
r2799 class MultipleInstanceError(Exception):
pass
Brian Granger
Moved a few things back to InteractiveShell....
r2766
Brian Granger
Massive, crazy refactoring of everything....
r2202 #-----------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032 # Main IPython class
Brian Granger
Massive, crazy refactoring of everything....
r2202 #-----------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
First draft of refactored Component->Configurable.
r2731 class InteractiveShell(Configurable, Magic):
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 """An enhanced, interactive shell for Python."""
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Finished fixing InteractiveShell.instance().
r2802 _instance = None
Brian Granger
ipcontroller/ipengine use the new clusterdir.py module.
r2301 autocall = Enum((0,1,2), default_value=1, config=True)
Brian Granger
Moved a few things back to InteractiveShell....
r2766 # TODO: remove all autoindent logic and put into frontends.
# We can't do this yet because even runlines uses the autoindent.
autoindent = CBool(True, config=True)
Brian Granger
Massive refactoring of of the core....
r2245 automagic = CBool(True, config=True)
cache_size = Int(1000, config=True)
color_info = CBool(True, config=True)
Brian Granger
More work on getting rid of ipmaker.
r2203 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
Brian Granger
Make the default colors OS dependent.
r2319 default_value=get_default_colors(), config=True)
Brian Granger
Massive refactoring of of the core....
r2245 debug = CBool(False, config=True)
deep_reload = CBool(False, config=True)
Brian Granger
Display system is fully working now....
r3278 display_formatter = Instance(DisplayFormatter)
Brian Granger
Initial support in ipkernel for proper displayhook handling.
r2786 displayhook_class = Type(DisplayHook)
Brian Granger
Mostly final version of display data....
r3277 display_pub_class = Type(DisplayPublisher)
Fernando Perez
Implement exit/quit/Exit/Quit recognition....
r2950 exit_now = CBool(False)
Fernando Perez
Small fixes in response to code review for gh-163.
r3136 # Monotonically increasing execution counter
execution_count = Int(1)
MinRK
fix at least some command-line unicode options
r3464 filename = Unicode("<ipython console>")
Brian Granger
Lots of work on command line options and env vars....
r2322 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
Fernando Perez
Initialize input_splitter automatically via traitlets mechanism.
r3049
# Input splitter, to split entire cells of input into either individual
# interactive statements or whole blocks.
input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
(), {})
Brian Granger
Massive refactoring of of the core....
r2245 logstart = CBool(False, config=True)
MinRK
fix at least some command-line unicode options
r3464 logfile = Unicode('', config=True)
logappend = Unicode('', config=True)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 object_info_string_level = Enum((0,1,2), default_value=0,
Brian Granger
Massive refactoring of of the core....
r2245 config=True)
pdb = CBool(False, config=True)
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987
MinRK
fix at least some command-line unicode options
r3464 profile = Unicode('', config=True)
Brian Granger
Massive refactoring of of the core....
r2245 prompt_in1 = Str('In [\\#]: ', config=True)
prompt_in2 = Str(' .\\D.: ', config=True)
prompt_out = Str('Out[\\#]: ', config=True)
prompts_pad_left = CBool(True, config=True)
quiet = CBool(False, config=True)
Satrajit Ghosh
History refactored and saved to json file...
r3240 history_length = Int(10000, config=True)
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # The readline stuff will eventually be moved to the terminal subclass
# but for now, we can't do that as readline is welded in everywhere.
Brian Granger
Massive refactoring of of the core....
r2245 readline_use = CBool(True, config=True)
readline_merge_completions = CBool(True, config=True)
Fernando Perez
Hide private names by default in tab completion....
r3238 readline_omit__names = Enum((0,1,2), default_value=2, config=True)
Brian Granger
Massive refactoring of of the core....
r2245 readline_remove_delims = Str('-/~', config=True)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 readline_parse_and_bind = List([
'tab: complete',
Fernando Perez
Set Control-L to clear the screen when readline supports it....
r2567 '"\C-l": clear-screen',
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 'set show-all-if-ambiguous on',
'"\C-o": tab-insert',
Thomas Kluyver
Disable readline \M-i, so characters 0x9000-0x9fff don't crash IPython....
r3428 # See bug gh-58 - with \M-i enabled, chars 0x9000-0x9fff
# crash IPython.
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 '"\M-o": "\d\d\d\d"',
'"\M-I": "\d\d\d\d"',
'"\C-r": reverse-search-history',
'"\C-s": forward-search-history',
'"\C-p": history-search-backward',
'"\C-n": history-search-forward',
'"\e[A": history-search-backward',
'"\e[B": history-search-forward',
'"\C-k": kill-line',
'"\C-u": unix-line-discard',
Brian Granger
Massive refactoring of of the core....
r2245 ], allow_none=False, config=True)
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
Moved a few things back to InteractiveShell....
r2766 # TODO: this part of prompt management should be moved to the frontends.
# Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
separate_in = SeparateStr('\n', config=True)
Brian Granger
Initial GUI support in kernel.
r2868 separate_out = SeparateStr('', config=True)
separate_out2 = SeparateStr('', config=True)
Brian Granger
Massive refactoring of of the core....
r2245 wildcards_case_sensitive = CBool(True, config=True)
Brian Granger
More work on getting rid of ipmaker.
r2203 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
Brian Granger
Massive refactoring of of the core....
r2245 default_value='Context', config=True)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204
Brian Granger
First draft of refactored Component->Configurable.
r2731 # Subcomponents of InteractiveShell
alias_manager = Instance('IPython.core.alias.AliasManager')
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
display_trap = Instance('IPython.core.display_trap.DisplayTrap')
extension_manager = Instance('IPython.core.extensions.ExtensionManager')
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 plugin_manager = Instance('IPython.core.plugin.PluginManager')
Brian Granger
Fixing imports and syntax errors.
r2812 payload_manager = Instance('IPython.core.payload.PayloadManager')
MinRK
merge interactiveshell.py
r3122 history_manager = Instance('IPython.core.history.HistoryManager')
Brian Granger
First draft of refactored Component->Configurable.
r2731
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987 # Private interface
_post_execute = set()
Brian Granger
Complete reorganization of InteractiveShell....
r2761 def __init__(self, config=None, ipython_dir=None,
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 user_ns=None, user_global_ns=None,
Fernando Perez
Add experimental support for cell-based execution....
r2967 custom_exceptions=((), None)):
Ville M. Vainio
crlf -> lf
r1032
Dav Clark
Final changes traitlet -> trait for review
r2385 # This is where traits with a config_key argument are updated
Brian Granger
More work on getting rid of ipmaker.
r2203 # from the values on config.
Brian Granger
First draft of refactored Component->Configurable.
r2731 super(InteractiveShell, self).__init__(config=config)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 # These are relatively independent and stateless
Brian Granger
Lots of work on command line options and env vars....
r2322 self.init_ipython_dir(ipython_dir)
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.init_instance_attrs()
Fernando Perez
Add init_environment(), %less, %more, %man and %clear/%cls, in zmq shell....
r3005 self.init_environment()
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226
Brian Granger
Massive refactoring of of the core....
r2245 # Create namespaces (user_ns, user_global_ns, etc.)
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.init_create_namespaces(user_ns, user_global_ns)
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 # This has to be done after init_create_namespaces because it uses
# something in self.user_ns, but before init_sys_modules, which
# is the first thing to modify sys.
Brian Granger
Moved init_io and init_traceback_handlers after readline_init.
r2804 # TODO: When we override sys.stdout and sys.stderr before this class
# is created, we are saving the overridden ones here. Not sure if this
# is what we want to do.
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 self.save_sys_module_state()
self.init_sys_modules()
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388
# While we're trying to have each part of the code directly access what
# it needs without keeping redundant references to objects, we have too
# much legacy code that expects ip.db to exist.
self.db = PickleShareDB(os.path.join(self.ipython_dir, 'db'))
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.init_history()
self.init_encoding()
Brian Granger
More work on refactoring things into components....
r2244 self.init_prefilter()
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Massive, crazy refactoring of everything....
r2202 Magic.__init__(self, self)
self.init_syntax_highlighting()
self.init_hooks()
self.init_pushd_popd_magic()
Brian Granger
Moved init_io and init_traceback_handlers after readline_init.
r2804 # self.init_traceback_handlers use to be here, but we moved it below
# because it and init_io have to come after init_readline.
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 self.init_user_ns()
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.init_logger()
Brian Granger
More work on componentizing everything....
r2243 self.init_alias()
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.init_builtins()
Brian Granger
Reenabling output trapping in the kernel.
r2767
Brian Granger
More work on getting rid of ipmaker.
r2203 # pre_config_initialization
Fernando Perez
Add experimental support for cell-based execution....
r2967 # The next section should contain everything that was in ipmaker.
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.init_logstart()
Brian Granger
More work on getting rid of ipmaker.
r2203
# The following was in post_config_initialization
self.init_inspector()
Brian Granger
Moved init_io and init_traceback_handlers after readline_init.
r2804 # init_readline() must come before init_io(), because init_io uses
# readline related things.
Brian Granger
More work on getting rid of ipmaker.
r2203 self.init_readline()
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 # init_completer must come after init_readline, because it needs to
# know whether readline is present or not system-wide to configure the
# completers, since the completion machinery can now operate
# independently of readline (e.g. over the network)
self.init_completer()
Brian Granger
Moved init_io and init_traceback_handlers after readline_init.
r2804 # TODO: init_io() needs to happen before init_traceback handlers
# because the traceback handlers hardcode the stdout/stderr streams.
# This logic in in debugger.Pdb and should eventually be changed.
self.init_io()
self.init_traceback_handlers(custom_exceptions)
Brian Granger
More work on getting rid of ipmaker.
r2203 self.init_prompts()
Brian Granger
Display system is fully working now....
r3278 self.init_display_formatter()
Brian Granger
Mostly final version of display data....
r3277 self.init_display_pub()
Brian Granger
More work on getting rid of ipmaker.
r2203 self.init_displayhook()
self.init_reload_doctest()
self.init_magics()
self.init_pdb()
Brian Granger
First draft of refactored Component->Configurable.
r2731 self.init_extension_manager()
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 self.init_plugin_manager()
Brian Granger
Final attempt to fix init_io logic.
r2810 self.init_payload()
Brian Granger
More work on getting rid of ipmaker.
r2203 self.hooks.late_startup_hook()
Fernando Perez
Fix bug where atexit operations were only done if readline was present.
r2953 atexit.register(self.atexit_operations)
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
First draft of refactored Component->Configurable.
r2731 @classmethod
def instance(cls, *args, **kwargs):
"""Returns a global InteractiveShell instance."""
Brian Granger
Finished fixing InteractiveShell.instance().
r2802 if cls._instance is None:
inst = cls(*args, **kwargs)
Brian Granger
Added additional logic to InteractiveShell.instance()....
r2798 # Now make sure that the instance will also be returned by
# the subclasses instance attribute.
Brian Granger
Finished fixing InteractiveShell.instance().
r2802 for subclass in cls.mro():
Fernando Perez
Small cleanups, no functional changes.
r2955 if issubclass(cls, subclass) and \
issubclass(subclass, InteractiveShell):
Brian Granger
Finished fixing InteractiveShell.instance().
r2802 subclass._instance = inst
else:
break
if isinstance(cls._instance, cls):
return cls._instance
else:
raise MultipleInstanceError(
'Multiple incompatible subclass instances of '
'InteractiveShell are being created.'
)
Brian Granger
First draft of refactored Component->Configurable.
r2731
@classmethod
def initialized(cls):
return hasattr(cls, "_instance")
Brian Granger
Massive refactoring of of the core....
r2245 def get_ipython(self):
Fernando Perez
A few small fixes so ipythonx works, and PEP-8 cleanups I found along the way.
r2400 """Return the currently running IPython instance."""
Brian Granger
Massive refactoring of of the core....
r2245 return self
Brian Granger
More work on getting rid of ipmaker.
r2203 #-------------------------------------------------------------------------
Dav Clark
Final changes traitlet -> trait for review
r2385 # Trait changed handlers
Brian Granger
More work on getting rid of ipmaker.
r2203 #-------------------------------------------------------------------------
Brian Granger
Lots of work on command line options and env vars....
r2322 def _ipython_dir_changed(self, name, new):
Brian Granger
Massive refactoring of of the core....
r2245 if not os.path.isdir(new):
os.makedirs(new, mode = 0777)
Brian Granger
More re-organization of InteractiveShell.
r2242 def set_autoindent(self,value=None):
"""Set the autoindent flag, checking for readline support.
If called with no arguments, it acts as a toggle."""
if not self.has_readline:
if os.name == 'posix':
warn("The auto-indent feature requires the readline library")
self.autoindent = 0
return
if value is None:
self.autoindent = not self.autoindent
else:
self.autoindent = value
Brian Granger
More work on getting rid of ipmaker.
r2203 #-------------------------------------------------------------------------
# init_* methods called by __init__
#-------------------------------------------------------------------------
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
Lots of work on command line options and env vars....
r2322 def init_ipython_dir(self, ipython_dir):
if ipython_dir is not None:
self.ipython_dir = ipython_dir
self.config.Global.ipython_dir = self.ipython_dir
Brian Granger
Minor work on how ipythondir is handled.
r2223 return
Brian Granger
Lots of work on command line options and env vars....
r2322 if hasattr(self.config.Global, 'ipython_dir'):
self.ipython_dir = self.config.Global.ipython_dir
Brian Granger
Massive refactoring of of the core....
r2245 else:
Brian Granger
Lots of work on command line options and env vars....
r2322 self.ipython_dir = get_ipython_dir()
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226
# All children can just read this
Brian Granger
Lots of work on command line options and env vars....
r2322 self.config.Global.ipython_dir = self.ipython_dir
Brian Granger
Minor work on how ipythondir is handled.
r2223
Brian Granger
Massive, crazy refactoring of everything....
r2202 def init_instance_attrs(self):
self.more = False
Ville M. Vainio
crlf -> lf
r1032
# command compiler
Fernando Perez
Using R. Kern's code to try to get better tracebacks....
r3172 self.compile = CachingCompiler()
MinRK
merge interactiveshell.py
r3122 # User input buffers
Fernando Perez
Small fixes in response to code review for gh-163.
r3136 # NOTE: these variables are slated for full removal, once we are 100%
# sure that the new execution logic is solid. We will delte runlines,
# push_line and these buffers, as all input will be managed by the
# frontends via an inputsplitter instance.
Ville M. Vainio
crlf -> lf
r1032 self.buffer = []
MinRK
merge interactiveshell.py
r3122 self.buffer_raw = []
Ville M. Vainio
crlf -> lf
r1032
# Make an empty namespace, which extension writers can rely on both
# existing and NEVER being used by ipython itself. This gives them a
# convenient location for storing additional information and state
# their extensions may require, without fear of collisions with other
# ipython names that may develop later.
self.meta = Struct()
Brian Granger
Massive, crazy refactoring of everything....
r2202 # Object variable to store code object waiting execution. This is
# used mainly by the multithreaded shells, but it can come in handy in
# other situations. No need to use a Queue here, since it's a single
# item which gets cleared once run.
self.code_to_run = None
# Temporary files used for various purposes. Deleted at exit.
self.tempfiles = []
# Keep track of readline usage (later set by init_readline)
self.has_readline = False
# keep track of where we started running (mainly for crash post-mortem)
# This is not being used anywhere currently.
self.starting_dir = os.getcwd()
# Indentation management
self.indent_current_nsp = 0
Fernando Perez
Add init_environment(), %less, %more, %man and %clear/%cls, in zmq shell....
r3005 def init_environment(self):
"""Any changes we need to make to the user's environment."""
pass
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_encoding(self):
# Get system encoding at startup time. Certain terminals (like Emacs
# under Win32 have it set to None, and we need to have a known valid
# encoding to use in the raw_input() method
try:
self.stdin_encoding = sys.stdin.encoding or 'ascii'
except AttributeError:
self.stdin_encoding = 'ascii'
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_syntax_highlighting(self):
# Python source parser/formatter for syntax highlighting
pyformat = PyColorize.Parser().format
self.pycolorize = lambda src: pyformat(src,'str',self.colors)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_pushd_popd_magic(self):
# for pushd/popd management
try:
self.home_dir = get_home_dir()
except HomeDirError, msg:
fatal(msg)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 self.dir_stack = []
Robert Kern
ENH: Allow non-dict namespaces. This involves a change in the ipapi for setting user namespaces.
r1419
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_logger(self):
MinRK
merge interactiveshell.py
r3122 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
logmode='rotate')
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_logstart(self):
MinRK
merge interactiveshell.py
r3122 """Initialize logging in case it was requested at the command line.
"""
Brian Granger
Minor changes to make sure logging is working well....
r2265 if self.logappend:
self.magic_logstart(self.logappend + ' append')
Brian Granger
Work on startup related things....
r2252 elif self.logfile:
Brian Granger
More re-organization of InteractiveShell.
r2242 self.magic_logstart(self.logfile)
elif self.logstart:
self.magic_logstart()
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_builtins(self):
Brian Granger
Adding support for HasTraits to take keyword arguments.
r2740 self.builtin_trap = BuiltinTrap(shell=self)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_inspector(self):
# Object inspector
self.inspector = oinspect.Inspector(oinspect.InspectColors,
PyColorize.ANSICodeColors,
'NoColor',
self.object_info_string_level)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Changing how IPython.utils.io.Term is handled....
r2775 def init_io(self):
Fernando Perez
Fixed broken coloring on Windows....
r2974 # This will just use sys.stdout and sys.stderr. If you want to
# override sys.stdout and sys.stderr themselves, you need to do that
# *before* instantiating this class, because Term holds onto
# references to the underlying streams.
Brian Granger
Second attempt to fix init_io readline test.
r2808 if sys.platform == 'win32' and self.has_readline:
Fernando Perez
Fixed broken coloring on Windows....
r2974 Term = io.IOTerm(cout=self.readline._outputfile,
cerr=self.readline._outputfile)
Brian Granger
Changing how IPython.utils.io.Term is handled....
r2775 else:
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 Term = io.IOTerm()
io.Term = Term
Brian Granger
Changing how IPython.utils.io.Term is handled....
r2775
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_prompts(self):
Brian Granger
Refactor of prompts and the displayhook....
r2781 # TODO: This is a pass for now because the prompts are managed inside
# the DisplayHook. Once there is a separate prompt manager, this
# will initialize that object and all prompt related information.
pass
Brian Granger
Display system is fully working now....
r3278 def init_display_formatter(self):
self.display_formatter = DisplayFormatter(config=self.config)
Brian Granger
Mostly final version of display data....
r3277 def init_display_pub(self):
self.display_pub = self.display_pub_class(config=self.config)
Brian Granger
Refactor of prompts and the displayhook....
r2781 def init_displayhook(self):
# Initialize displayhook, set in/out prompts and printing system
Brian Granger
Initial support in ipkernel for proper displayhook handling.
r2786 self.displayhook = self.displayhook_class(
Robert Kern
ENH: Allow configurability of the DefaultFormatter and the DisplayHook.
r3210 config=self.config,
Brian Granger
Initial support in ipkernel for proper displayhook handling.
r2786 shell=self,
cache_size=self.cache_size,
input_sep = self.separate_in,
output_sep = self.separate_out,
output_sep2 = self.separate_out2,
ps1 = self.prompt_in1,
ps2 = self.prompt_in2,
ps_out = self.prompt_out,
pad_left = self.prompts_pad_left
)
Brian Granger
Refactor of prompts and the displayhook....
r2781 # This is a context manager that installs/revmoes the displayhook at
# the appropriate time.
self.display_trap = DisplayTrap(hook=self.displayhook)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_reload_doctest(self):
# Do a proper resetting of doctest, including the necessary displayhook
# monkeypatching
try:
doctest_reload()
except ImportError:
warn("doctest module does not exist.")
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to injections into the sys module
#-------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def save_sys_module_state(self):
"""Save the state of hooks in the sys module.
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226
Brian Granger
More re-organization of InteractiveShell.
r2242 This has to be called after self.user_ns is created.
"""
self._orig_sys_module_state = {}
self._orig_sys_module_state['stdin'] = sys.stdin
self._orig_sys_module_state['stdout'] = sys.stdout
self._orig_sys_module_state['stderr'] = sys.stderr
self._orig_sys_module_state['excepthook'] = sys.excepthook
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 try:
Brian Granger
More re-organization of InteractiveShell.
r2242 self._orig_sys_modules_main_name = self.user_ns['__name__']
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 except KeyError:
Brian Granger
More re-organization of InteractiveShell.
r2242 pass
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
More re-organization of InteractiveShell.
r2242 def restore_sys_module_state(self):
"""Restore the state of the sys module."""
try:
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 for k, v in self._orig_sys_module_state.iteritems():
Brian Granger
More re-organization of InteractiveShell.
r2242 setattr(sys, k, v)
except AttributeError:
pass
# Reset what what done in self.init_sys_modules
try:
sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
except (AttributeError, KeyError):
pass
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to hooks
#-------------------------------------------------------------------------
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_hooks(self):
# hooks holds pointers used for user-side customizations
self.hooks = Struct()
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 self.strdispatchers = {}
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 # Set all default hooks, defined in the IPython.hooks module.
hooks = IPython.core.hooks
for hook_name in hooks.__all__:
# default hooks have priority 100, i.e. low; user hooks should have
# 0-100 priority
self.set_hook(hook_name,getattr(hooks,hook_name), 100)
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
"""set_hook(name,hook) -> sets an internal IPython hook.
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 IPython exposes some of its internal API as user-modifiable hooks. By
adding your function to one of these hooks, you can modify IPython's
behavior to call at runtime your own routines."""
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 # At some point in the future, this should validate the hook before it
# accepts it. Probably at least check that the hook takes the number
# of args it's supposed to.
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 f = types.MethodType(hook,self)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 # check if the hook is for strdispatcher first
if str_key is not None:
sdp = self.strdispatchers.get(name, StrDispatch())
sdp.add_s(str_key, f, priority )
self.strdispatchers[name] = sdp
return
if re_key is not None:
sdp = self.strdispatchers.get(name, StrDispatch())
sdp.add_re(re.compile(re_key), f, priority )
self.strdispatchers[name] = sdp
return
dp = getattr(self.hooks, name, None)
if name not in IPython.core.hooks.__all__:
Fernando Perez
Small cleanups, no functional changes.
r2955 print "Warning! Hook '%s' is not one of %s" % \
(name, IPython.core.hooks.__all__ )
Brian Granger
More re-organization of InteractiveShell.
r2242 if not dp:
dp = IPython.core.hooks.CommandChainDispatcher()
Ville M. Vainio
crlf -> lf
r1032 try:
Brian Granger
More re-organization of InteractiveShell.
r2242 dp.add(f,priority)
except AttributeError:
# it was not commandchain, plain old func - replace
dp = f
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 setattr(self.hooks,name, dp)
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987 def register_post_execute(self, func):
"""Register a function for calling after code execution.
"""
if not callable(func):
raise ValueError('argument %s must be callable' % func)
self._post_execute.add(func)
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to the "main" module
#-------------------------------------------------------------------------
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
More re-organization of InteractiveShell.
r2242 def new_main_mod(self,ns=None):
"""Return a new 'main' module object for user code execution.
"""
main_mod = self._user_main_module
init_fakemod_dict(main_mod,ns)
return main_mod
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 def cache_main_mod(self,ns,fname):
"""Cache a main module's namespace.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 When scripts are executed via %run, we must keep a reference to the
namespace of their __main__ module (a FakeModule instance) around so
that Python doesn't clear it, rendering objects defined therein
useless.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 This method keeps said reference in a private dict, keyed by the
absolute path of the module object (which corresponds to the script
path). This way, for multiple executions of the same script we only
keep one copy of the namespace (the last one), thus preventing memory
leaks from old references while allowing the objects from the last
execution to be accessible.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 Note: we can not allow the actual FakeModule instances to be deleted,
because of how Python tears down modules (it hard-sets all their
references to None without regard for reference counts). This method
must therefore make a *copy* of the given namespace, to allow the
original module's __dict__ to be cleared and reused.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 Parameters
----------
ns : a namespace (a dict, typically)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 fname : str
Filename associated with the namespace.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 Examples
--------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 In [10]: import IPython
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 In [12]: IPython.__file__ in _ip._main_ns_cache
Out[12]: True
"""
self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def clear_main_mod_cache(self):
"""Clear the cache of main modules.
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
More re-organization of InteractiveShell.
r2242 Mainly for use by utilities like %reset.
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
More re-organization of InteractiveShell.
r2242 Examples
--------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 In [15]: import IPython
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 In [17]: len(_ip._main_ns_cache) > 0
Out[17]: True
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 In [18]: _ip.clear_main_mod_cache()
Fernando Perez
Fix bug: https://bugs.launchpad.net/ipython/+bug/269966...
r1856
Brian Granger
More re-organization of InteractiveShell.
r2242 In [19]: len(_ip._main_ns_cache) == 0
Out[19]: True
"""
self._main_ns_cache.clear()
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to debugging
#-------------------------------------------------------------------------
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_pdb(self):
# Set calling of pdb on exceptions
# self.call_pdb is a property
self.call_pdb = self.pdb
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def _get_call_pdb(self):
return self._call_pdb
def _set_call_pdb(self,val):
if val not in (0,1,False,True):
raise ValueError,'new call_pdb value must be boolean'
# store value in instance
self._call_pdb = val
# notify the actual exception handlers
self.InteractiveTB.call_pdb = val
call_pdb = property(_get_call_pdb,_set_call_pdb,None,
'Control auto-activation of pdb at exceptions')
def debugger(self,force=False):
"""Call the pydb/pdb debugger.
Keywords:
- force(False): by default, this routine checks the instance call_pdb
flag and does not actually invoke the debugger if the flag is false.
The 'force' option forces the debugger to activate even if the flag
is false.
"""
if not (force or self.call_pdb):
Brian Granger
More work on getting rid of ipmaker.
r2203 return
Brian Granger
More re-organization of InteractiveShell.
r2242 if not hasattr(sys,'last_traceback'):
error('No traceback has been produced, nothing to debug.')
return
# use pydb if available
if debugger.has_pydb:
from pydb import pm
Brian Granger
More work on getting rid of ipmaker.
r2203 else:
Brian Granger
More re-organization of InteractiveShell.
r2242 # fallback to our internal debugger
pm = lambda : self.InteractiveTB.debugger(force=True)
self.history_saving_wrapper(pm)()
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to IPython's various namespaces
#-------------------------------------------------------------------------
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
# Create the namespace where the user will operate. user_ns is
# normally the only one used, and it is passed to the exec calls as
# the locals argument. But we do carry a user_global_ns namespace
# given as the exec 'globals' argument, This is useful in embedding
# situations where the ipython shell opens in a context where the
# distinction between locals and globals is meaningful. For
# non-embedded contexts, it is just the same object as the user_ns dict.
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 # FIXME. For some strange reason, __builtins__ is showing up at user
# level as a dict instead of a module. This is a manual fix, but I
# should really track down where the problem is coming from. Alex
# Schmolck reported this problem first.
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 # A useful post by Alex Martelli on this topic:
# Re: inconsistent value from __builtins__
# Von: Alex Martelli <aleaxit@yahoo.com>
# Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
# Gruppen: comp.lang.python
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
# > >>> print type(builtin_check.get_global_binding('__builtins__'))
# > <type 'dict'>
# > >>> print type(__builtins__)
# > <type 'module'>
# > Is this difference in return value intentional?
# Well, it's documented that '__builtins__' can be either a dictionary
# or a module, and it's been that way for a long time. Whether it's
# intentional (or sensible), I don't know. In any case, the idea is
# that if you need to access the built-in namespace directly, you
# should start with "import __builtin__" (note, no 's') which will
# definitely give you a module. Yeah, it's somewhat confusing:-(.
# These routines return properly built dicts as needed by the rest of
# the code, and can also be used by extension writers to generate
# properly initialized namespaces.
Fernando Perez
Small cleanups, no functional changes.
r2955 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
user_global_ns)
Brian Granger
More re-organization of InteractiveShell.
r2242
# Assign namespaces
# This is the namespace where all normal user variables live
self.user_ns = user_ns
self.user_global_ns = user_global_ns
# An auxiliary namespace that checks what parts of the user_ns were
# loaded at startup, so we can list later only variables defined in
# actual interactive use. Since it is always a subset of user_ns, it
Fernando Perez
Added --gui to match %gui use, better docs and behavior for %pylab code....
r2388 # doesn't need to be separately tracked in the ns_table.
Brian Granger
More work to address review comments....
r2509 self.user_ns_hidden = {}
Brian Granger
More re-organization of InteractiveShell.
r2242
# A namespace to keep track of internal data structures to prevent
# them from cluttering user-visible stuff. Will be updated later
self.internal_ns = {}
# Now that FakeModule produces a real module, we've run into a nasty
# problem: after script execution (via %run), the module where the user
# code ran is deleted. Now that this object is a true module (needed
# so docetst and other tools work correctly), the Python module
# teardown mechanism runs over it, and sets to None every variable
# present in that module. Top-level references to objects from the
# script survive, because the user_ns is updated with them. However,
# calling functions defined in the script that use other things from
# the script will fail, because the function's closure had references
# to the original objects, which are now all None. So we must protect
# these modules from deletion by keeping a cache.
#
# To avoid keeping stale modules around (we only need the one from the
# last run), we use a dict keyed with the full path to the script, so
# only the last version of the module is held in the cache. Note,
# however, that we must cache the module *namespace contents* (their
# __dict__). Because if we try to cache the actual modules, old ones
# (uncached) could be destroyed while still holding references (such as
# those held by GUI objects that tend to be long-lived)>
#
# The %reset command will flush this cache. See the cache_main_mod()
# and clear_main_mod_cache() methods for details on use.
# This is the cache used for 'main' namespaces
self._main_ns_cache = {}
# And this is the single instance of FakeModule whose __dict__ we keep
# copying and clearing for reuse on each %run
self._user_main_module = FakeModule()
# A table holding all the namespaces IPython deals with, so that
# introspection facilities can search easily.
self.ns_table = {'user':user_ns,
'user_global':user_global_ns,
'internal':self.internal_ns,
'builtin':__builtin__.__dict__
}
# Similarly, track all namespaces where references can be held and that
# we can safely clear (so it can NOT include builtin). This one can be
Thomas Kluyver
Restore Fernando's fix for the __del__ methods on exit bug.
r3157 # a simple list. Note that the main execution namespaces, user_ns and
# user_global_ns, can NOT be listed here, as clearing them blindly
# causes errors in object __del__ methods. Instead, the reset() method
# clears them manually and carefully.
self.ns_refs_table = [ self.user_ns_hidden,
Brian Granger
Massive refactoring of of the core....
r2245 self.internal_ns, self._main_ns_cache ]
Brian Granger
More re-organization of InteractiveShell.
r2242
Brian Granger
More work addressing review comments for Fernando's branch....
r2499 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
"""Return a valid local and global user interactive namespaces.
This builds a dict with the minimal information needed to operate as a
valid IPython user namespace, which you can pass to the various
embedding classes in ipython. The default implementation returns the
same dict for both the locals and the globals to allow functions to
refer to variables in the namespace. Customized implementations can
return different dicts. The locals dictionary can actually be anything
following the basic mapping protocol of a dict, but the globals dict
must be a true dict, not even a subclass. It is recommended that any
custom object for the locals namespace synchronize with the globals
dict somehow.
Raises TypeError if the provided globals namespace is not a true dict.
Parameters
----------
user_ns : dict-like, optional
The current user namespace. The items in this namespace should
be included in the output. If None, an appropriate blank
namespace should be created.
user_global_ns : dict, optional
The current user global namespace. The items in this namespace
should be included in the output. If None, an appropriate
blank namespace should be created.
Returns
-------
A pair of dictionary-like object to be used as the local namespace
of the interpreter and a dict to be used as the global namespace.
"""
# We must ensure that __builtin__ (without the final 's') is always
# available and pointing to the __builtin__ *module*. For more details:
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
if user_ns is None:
# Set __name__ to __main__ to better match the behavior of the
# normal interpreter.
user_ns = {'__name__' :'__main__',
'__builtin__' : __builtin__,
'__builtins__' : __builtin__,
}
else:
user_ns.setdefault('__name__','__main__')
user_ns.setdefault('__builtin__',__builtin__)
user_ns.setdefault('__builtins__',__builtin__)
if user_global_ns is None:
user_global_ns = user_ns
if type(user_global_ns) is not dict:
raise TypeError("user_global_ns must be a true dict; got %r"
% type(user_global_ns))
return user_ns, user_global_ns
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_sys_modules(self):
# We need to insert into sys.modules something that looks like a
# module but which accesses the IPython namespace, for shelve and
# pickle to work interactively. Normally they rely on getting
# everything out of __main__, but for embedding purposes each IPython
# instance has its own private namespace, so we can't go shoving
# everything into __main__.
# note, however, that we should only do this for non-embedded
# ipythons, which really mimic the __main__.__dict__ with their own
# namespace. Embedded instances, on the other hand, should not do
# this because they need to manage the user local/global namespaces
# only, but they live within a 'normal' __main__ (meaning, they
# shouldn't overtake the execution environment of the script they're
# embedded in).
Brian Granger
More work on getting rid of ipmaker.
r2203
Brian Granger
More re-organization of InteractiveShell.
r2242 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
Ville M. Vainio
crlf -> lf
r1032
try:
Brian Granger
More re-organization of InteractiveShell.
r2242 main_name = self.user_ns['__name__']
except KeyError:
raise KeyError('user_ns dictionary MUST have a "__name__" key')
else:
sys.modules[main_name] = FakeModule(self.user_ns)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226 def init_user_ns(self):
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859 """Initialize all user-visible namespaces to their minimum defaults.
Certain history lists are also initialized here, as they effectively
act as user namespaces.
Brian Granger
Merging -r 1182 from lp:ipython....
r2131 Notes
-----
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859 All data structures here are only filled in, they are NOT reset by this
method. If they were not empty before, data will simply be added to
therm.
"""
Fernando Perez
Work in multiple places to improve state of the test suite....
r2398 # This function works in two parts: first we put a few things in
Brian Granger
More work to address review comments....
r2509 # user_ns, and we sync that contents into user_ns_hidden so that these
Fernando Perez
Work in multiple places to improve state of the test suite....
r2398 # initial variables aren't shown by %who. After the sync, we add the
# rest of what we *do* want the user to see with %who even on a new
Fernando Perez
Ensure that __builtin__ is always available and compute prompts from it....
r2485 # session (probably nothing, so theye really only see their own stuff)
# The user dict must *always* have a __builtin__ reference to the
# Python standard __builtin__ namespace, which must be imported.
# This is so that certain operations in prompt evaluation can be
# reliably executed with builtins. Note that we can NOT use
# __builtins__ (note the 's'), because that can either be a dict or a
# module, and can even mutate at runtime, depending on the context
# (Python makes no guarantees on it). In contrast, __builtin__ is
# always a module object, though it must be explicitly imported.
# For more details:
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
ns = dict(__builtin__ = __builtin__)
Fernando Perez
Work in multiple places to improve state of the test suite....
r2398
# Put 'help' in the user namespace
try:
from site import _Helper
ns['help'] = _Helper()
except ImportError:
warn('help() not available - check site.py')
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
# make global variables for user access to the histories
Satrajit Ghosh
History refactored and saved to json file...
r3240 ns['_ih'] = self.history_manager.input_hist_parsed
ns['_oh'] = self.history_manager.output_hist
ns['_dh'] = self.history_manager.dir_hist
Fernando Perez
Work in multiple places to improve state of the test suite....
r2398
ns['_sh'] = shadowns
Fernando Perez
Clean up output of %who
r2472 # user aliases to input and output histories. These shouldn't show up
# in %who, as they can have very large reprs.
Satrajit Ghosh
History refactored and saved to json file...
r3240 ns['In'] = self.history_manager.input_hist_parsed
ns['Out'] = self.history_manager.output_hist
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Fernando Perez
Work in multiple places to improve state of the test suite....
r2398 # Store myself as the public api!!!
ns['get_ipython'] = self.get_ipython
Fernando Perez
Clean up output of %who
r2472
Brian Granger
More work to address review comments....
r2509 # Sync what we've added so far to user_ns_hidden so these aren't seen
Fernando Perez
Clean up output of %who
r2472 # by %who
Brian Granger
More work to address review comments....
r2509 self.user_ns_hidden.update(ns)
Fernando Perez
Clean up output of %who
r2472
# Anything put into ns now would show up in %who. Think twice before
# putting anything here, as we really want %who to show the user their
# stuff, not our variables.
Fernando Perez
Work in multiple places to improve state of the test suite....
r2398
Fernando Perez
Clean up output of %who
r2472 # Finally, update the real user's namespace
Fernando Perez
Work in multiple places to improve state of the test suite....
r2398 self.user_ns.update(ns)
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Thomas Kluyver
ipython-qtconsole now calls the right function.
r3397 def reset(self, new_session=True):
Brian Granger
More re-organization of InteractiveShell.
r2242 """Clear all internal namespaces.
Note that this is much more aggressive than %reset, since it clears
fully all namespaces, as well as all input/output lists.
Thomas Kluyver
ipython-qtconsole now calls the right function.
r3397
If new_session is True, a new history session will be opened.
Brian Granger
More re-organization of InteractiveShell.
r2242 """
MinRK
merge interactiveshell.py
r3122 # Clear histories
Thomas Kluyver
ipython-qtconsole now calls the right function.
r3397 self.history_manager.reset(new_session)
Brian Granger
Massive refactoring of of the core....
r2245
MinRK
merge interactiveshell.py
r3122 # Reset counter used to index all histories
self.execution_count = 0
# Restore the user namespaces to minimal usability
Fernando Perez
Fix bug with reset() that was causing errors in __del__ methods....
r3099 for ns in self.ns_refs_table:
ns.clear()
Thomas Kluyver
Restore Fernando's fix for the __del__ methods on exit bug.
r3157
# The main execution namespaces must be cleared very carefully,
# skipping the deletion of the builtin-related keys, because doing so
# would cause errors in many object's __del__ methods.
for ns in [self.user_ns, self.user_global_ns]:
drop_keys = set(ns.keys())
drop_keys.discard('__builtin__')
drop_keys.discard('__builtins__')
for k in drop_keys:
del ns[k]
# Restore the user namespaces to minimal usability
Brian Granger
More re-organization of InteractiveShell.
r2242 self.init_user_ns()
MinRK
merge interactiveshell.py
r3122
Brian Granger
Massive refactoring of of the core....
r2245 # Restore the default and user aliases
MinRK
merge interactiveshell.py
r3122 self.alias_manager.clear_aliases()
Brian Granger
Massive refactoring of of the core....
r2245 self.alias_manager.init_aliases()
Brad Reisfeld
New magic: %reset_selective....
r2577 def reset_selective(self, regex=None):
Fernando Perez
Small cleanups, no functional changes.
r2955 """Clear selective variables from internal namespaces based on a
specified regular expression.
Brad Reisfeld
New magic: %reset_selective....
r2577
Parameters
----------
regex : string or compiled pattern, optional
Fernando Perez
Small cleanups, no functional changes.
r2955 A regular expression pattern that will be used in searching
variable names in the users namespaces.
Brad Reisfeld
New magic: %reset_selective....
r2577 """
if regex is not None:
try:
m = re.compile(regex)
except TypeError:
raise TypeError('regex must be a string or compiled pattern')
# Search for keys in each namespace that match the given regex
# If a match is found, delete the key/value pair.
for ns in self.ns_refs_table:
for var in ns:
if m.search(var):
del ns[var]
Brian Granger
More re-organization of InteractiveShell.
r2242 def push(self, variables, interactive=True):
"""Inject a group of variables into the IPython user namespace.
Parameters
----------
variables : dict, str or list/tuple of str
Fernando Perez
Small cleanups, no functional changes.
r2955 The variables to inject into the user's namespace. If a dict, a
simple update is done. If a str, the string is assumed to have
variable names separated by spaces. A list/tuple of str can also
be used to give the variable names. If just the variable names are
give (list/tuple/str) then the variable values looked up in the
callers frame.
Brian Granger
More re-organization of InteractiveShell.
r2242 interactive : bool
If True (default), the variables will be listed with the ``who``
magic.
"""
vdict = None
# We need a dict of name/value pairs to do namespace updates.
if isinstance(variables, dict):
vdict = variables
elif isinstance(variables, (basestring, list, tuple)):
if isinstance(variables, basestring):
vlist = variables.split()
else:
vlist = variables
vdict = {}
cf = sys._getframe(1)
for name in vlist:
try:
vdict[name] = eval(name, cf.f_globals, cf.f_locals)
except:
print ('Could not get variable %s from %s' %
(name,cf.f_code.co_name))
else:
raise ValueError('variables must be a dict/str/list/tuple')
# Propagate variables to user namespace
self.user_ns.update(vdict)
# And configure interactive visibility
Brian Granger
More work to address review comments....
r2509 config_ns = self.user_ns_hidden
Brian Granger
More re-organization of InteractiveShell.
r2242 if interactive:
for name, val in vdict.iteritems():
config_ns.pop(name, None)
else:
for name,val in vdict.iteritems():
config_ns[name] = val
#-------------------------------------------------------------------------
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 # Things related to object introspection
#-------------------------------------------------------------------------
Fernando Perez
Initialize input_splitter automatically via traitlets mechanism.
r3049
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 def _ofind(self, oname, namespaces=None):
"""Find an object in the available namespaces.
self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
Has special code to detect magic functions.
"""
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 #oname = oname.strip()
#print '1- oname: <%r>' % oname # dbg
try:
oname = oname.strip().encode('ascii')
#print '2- oname: <%r>' % oname # dbg
except UnicodeEncodeError:
print 'Python identifiers can only contain ascii characters.'
return dict(found=False)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 alias_ns = None
if namespaces is None:
# Namespaces to search in:
# Put them in a list. The order is important so that we
# find things in the same order that Python finds them.
Fernando Perez
Clean up unnecessary references to self.shell (which are circular)
r2928 namespaces = [ ('Interactive', self.user_ns),
('IPython internal', self.internal_ns),
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 ('Python builtin', __builtin__.__dict__),
Fernando Perez
Clean up unnecessary references to self.shell (which are circular)
r2928 ('Alias', self.alias_manager.alias_table),
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 ]
Fernando Perez
Clean up unnecessary references to self.shell (which are circular)
r2928 alias_ns = self.alias_manager.alias_table
Fernando Perez
Move object inspection machinery out of the magics code....
r2927
# initialize results to 'null'
found = False; obj = None; ospace = None; ds = None;
ismagic = False; isalias = False; parent = None
# We need to special-case 'print', which as of python2.6 registers as a
# function but should only be treated as one if print_function was
# loaded with a future import. In this case, just bail.
Fernando Perez
Complete implementation of interactive traceback support....
r3175 if (oname == 'print' and not (self.compile.compiler_flags &
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 __future__.CO_FUTURE_PRINT_FUNCTION)):
return {'found':found, 'obj':obj, 'namespace':ospace,
'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
# Look for the given name by splitting it in parts. If the head is
# found, then we look for all the remaining parts as members, and only
# declare success if we can find them all.
oname_parts = oname.split('.')
oname_head, oname_rest = oname_parts[0],oname_parts[1:]
for nsname,ns in namespaces:
try:
obj = ns[oname_head]
except KeyError:
continue
else:
#print 'oname_rest:', oname_rest # dbg
for part in oname_rest:
try:
parent = obj
obj = getattr(obj,part)
except:
# Blanket except b/c some badly implemented objects
# allow __getattr__ to raise exceptions other than
# AttributeError, which then crashes IPython.
break
else:
# If we finish the for loop (no break), we got all members
found = True
ospace = nsname
if ns == alias_ns:
isalias = True
break # namespace loop
# Try to see if it's magic
if not found:
if oname.startswith(ESC_MAGIC):
oname = oname[1:]
obj = getattr(self,'magic_'+oname,None)
if obj is not None:
found = True
ospace = 'IPython internal'
ismagic = True
# Last try: special-case some literals like '', [], {}, etc:
if not found and oname_head in ["''",'""','[]','{}','()']:
obj = eval(oname_head)
found = True
ospace = 'Interactive'
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 return {'found':found, 'obj':obj, 'namespace':ospace,
'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 def _ofind_property(self, oname, info):
"""Second part of object finding, to look for property details."""
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 if info.found:
# Get the docstring of the class property if it exists.
path = oname.split('.')
root = '.'.join(path[:-1])
if info.parent is not None:
try:
target = getattr(info.parent, '__class__')
# The object belongs to a class instance.
try:
target = getattr(target, path[-1])
# The class defines the object.
if isinstance(target, property):
oname = root + '.__class__.' + path[-1]
info = Struct(self._ofind(oname))
except AttributeError: pass
except AttributeError: pass
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929
# We return either the new info or the unmodified input if the object
# hadn't been found
return info
def _object_find(self, oname, namespaces=None):
"""Find an object and return a struct with info about it."""
inf = Struct(self._ofind(oname, namespaces))
return Struct(self._ofind_property(oname, inf))
def _inspect(self, meth, oname, namespaces=None, **kw):
"""Generic interface to the inspector system.
This function is meant to be called by pdef, pdoc & friends."""
info = self._object_find(oname)
if info.found:
pmethod = getattr(self.inspector, meth)
formatter = format_screen if info.ismagic else None
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 if meth == 'pdoc':
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 pmethod(info.obj, oname, formatter)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 elif meth == 'pinfo':
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 pmethod(info.obj, oname, formatter, info, **kw)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 else:
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 pmethod(info.obj, oname)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 else:
print 'Object `%s` not found.' % oname
return 'not found' # so callers can take other action
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929
def object_inspect(self, oname):
info = self._object_find(oname)
Fernando Perez
Implement object info protocol....
r2931 if info.found:
Fernando Perez
Add function signature info to calltips....
r3051 return self.inspector.info(info.obj, oname, info=info)
Fernando Perez
Implement object info protocol....
r2931 else:
Robert Kern
BUG: mk_object_info -> object_info
r3053 return oinspect.object_info(name=oname, found=False)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 #-------------------------------------------------------------------------
Brian Granger
More re-organization of InteractiveShell.
r2242 # Things related to history management
#-------------------------------------------------------------------------
def init_history(self):
Thomas Kluyver
Move history thread initialisation to init_history, and expand docstrings.
r3259 """Sets up the command history, and starts regular autosaves."""
Thomas Kluyver
Make HistoryManager configurable.
r3393 self.history_manager = HistoryManager(shell=self, config=self.config)
Brian Granger
More re-organization of InteractiveShell.
r2242
def history_saving_wrapper(self, func):
""" Wrap func for readline history saving
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226
Brian Granger
More re-organization of InteractiveShell.
r2242 Convert func into callable that saves & restores
history around the call """
Brian Granger
Removed shell.py entirely and made the embedded shell a proper subclass....
r2206
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 if self.has_readline:
from IPython.utils import rlineimpl as readline
else:
Brian Granger
More re-organization of InteractiveShell.
r2242 return func
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def wrapper():
Satrajit Ghosh
History refactored and saved to json file...
r3240 self.save_history()
Brian Granger
More re-organization of InteractiveShell.
r2242 try:
func()
finally:
Satrajit Ghosh
History refactored and saved to json file...
r3240 self.reload_history()
Brian Granger
More re-organization of InteractiveShell.
r2242 return wrapper
Satrajit Ghosh
enabled qtconsole to retrieve history
r3242
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to exception handling and tracebacks (not debugging)
#-------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_traceback_handlers(self, custom_exceptions):
# Syntax error handler.
Brian Granger
Initial refactoring to support structured traceback information.
r2792 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 # The interactive one is initialized with an offset, meaning we always
# want to remove the topmost item in the traceback, which is our own
# internal code. Valid modes: ['Plain','Context','Verbose']
self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
color_scheme='NoColor',
Fernando Perez
Complete implementation of interactive traceback support....
r3175 tb_offset = 1,
check_cache=self.compile.check_cache)
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Move crash handling to the application level and simplify class structure....
r2403 # The instance will store a pointer to the system-wide exception hook,
# so that runtime code (such as magics) can access it. This is because
# during the read-eval loop, it may get temporarily overwritten.
self.sys_excepthook = sys.excepthook
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 # and add any custom exception handlers the user may have specified
self.set_custom_exc(*custom_exceptions)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Work to address the review comments on Fernando's branch....
r2498 # Set the exception mode
self.InteractiveTB.set_mode(mode=self.xmode)
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 def set_custom_exc(self, exc_tuple, handler):
Ville M. Vainio
crlf -> lf
r1032 """set_custom_exc(exc_tuple,handler)
Set a custom exception handler, which will be called if any of the
exceptions in exc_tuple occur in the mainloop (specifically, in the
MinRK
merge interactiveshell.py
r3122 run_code() method.
Ville M. Vainio
crlf -> lf
r1032
Inputs:
- exc_tuple: a *tuple* of valid exceptions to call the defined
handler for. It is very important that you use a tuple, and NOT A
LIST here, because of the way Python's except statement works. If
you only want to trap a single exception, use a singleton tuple:
exc_tuple == (MyCustomException,)
- handler: this must be defined as a function with the following
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 basic interface::
def my_handler(self, etype, value, tb, tb_offset=None)
...
# The return value must be
return structured_traceback
Ville M. Vainio
crlf -> lf
r1032
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 This will be made into an instance method (via types.MethodType)
Ville M. Vainio
crlf -> lf
r1032 of IPython itself, and it will be called if any of the exceptions
listed in the exc_tuple are caught. If the handler is None, an
internal basic one is used, which just prints basic info.
WARNING: by putting in your own exception handler into IPython's main
execution loop, you run a very good chance of nasty crashes. This
facility should only be used if you really know what you are doing."""
assert type(exc_tuple)==type(()) , \
"The custom exceptions must be given AS A TUPLE."
def dummy_handler(self,etype,value,tb):
print '*** Simple custom exception handler ***'
print 'Exception type :',etype
print 'Exception value:',value
print 'Traceback :',tb
print 'Source code :','\n'.join(self.buffer)
if handler is None: handler = dummy_handler
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 self.CustomTB = types.MethodType(handler,self)
Ville M. Vainio
crlf -> lf
r1032 self.custom_exceptions = exc_tuple
Brian Granger
More re-organization of InteractiveShell.
r2242 def excepthook(self, etype, value, tb):
"""One more defense for GUI apps that call sys.excepthook.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 GUI frameworks like wxPython trap exceptions and call
sys.excepthook themselves. I guess this is a feature that
enables them to keep running after exceptions that would
otherwise kill their mainloop. This is a bother for IPython
which excepts to catch all of the program exceptions with a try:
except: statement.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
any app directly invokes sys.excepthook, it will look to the user like
IPython crashed. In order to work around this, we can disable the
CrashHandler and replace it with this excepthook instead, which prints a
regular traceback using our InteractiveTB. In this fashion, apps which
call sys.excepthook will generate a regular-looking exception from
IPython, and the CrashHandler will only be triggered by real IPython
crashes.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 This hook should be used sparingly, only in places which are not likely
to be true IPython errors.
"""
self.showtraceback((etype,value,tb),tb_offset=0)
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
exception_only=False):
Brian Granger
More re-organization of InteractiveShell.
r2242 """Display the exception that just occurred.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 If nothing is known about the exception, this is the method which
should be used throughout the code for presenting user tracebacks,
rather than directly invoking the InteractiveTB object.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 A specific showsyntaxerror() also exists, but this method can take
care of calling it if needed, so unless you are explicitly catching a
SyntaxError exception, don't try to analyze the stack manually and
simply call this method."""
Ville M. Vainio
crlf -> lf
r1032 try:
Brian Granger
More re-organization of InteractiveShell.
r2242 if exc_tuple is None:
etype, value, tb = sys.exc_info()
else:
etype, value, tb = exc_tuple
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440
if etype is None:
if hasattr(sys, 'last_type'):
etype, value, tb = sys.last_type, sys.last_value, \
sys.last_traceback
else:
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 self.write_err('No traceback available to show.\n')
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 return
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 if etype is SyntaxError:
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 # Though this won't be called by syntax errors in the input
# line, there may be SyntaxError cases whith imported code.
Brian Granger
More re-organization of InteractiveShell.
r2242 self.showsyntaxerror(filename)
elif etype is UsageError:
print "UsageError:", value
else:
# WARNING: these variables are somewhat deprecated and not
# necessarily safe to use in a threaded environment, but tools
# like pdb depend on their existence, so let's set them. If we
# find problems in the field, we'll need to revisit their use.
sys.last_type = etype
sys.last_value = value
sys.last_traceback = tb
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 if etype in self.custom_exceptions:
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 # FIXME: Old custom traceback objects may just return a
# string, in that case we just put it into a list
stb = self.CustomTB(etype, value, tb, tb_offset)
if isinstance(ctb, basestring):
stb = [stb]
Brian Granger
More re-organization of InteractiveShell.
r2242 else:
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 if exception_only:
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 stb = ['An exception has occurred, use %tb to see '
Fernando Perez
Multiple improvements to tab completion....
r2839 'the full traceback.\n']
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 stb.extend(self.InteractiveTB.get_exception_only(etype,
value))
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 else:
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 stb = self.InteractiveTB.structured_traceback(etype,
value, tb, tb_offset=tb_offset)
# FIXME: the pdb calling should be done by us, not by
# the code computing the traceback.
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 if self.InteractiveTB.call_pdb:
# pdb mucks up readline, fix it back
Fernando Perez
Simplify completer handling by isolating readline-specific logic more....
r2952 self.set_readline_completer()
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838
# Actually show the traceback
self._showtraceback(etype, value, stb)
Brian Granger
More re-organization of InteractiveShell.
r2242 except KeyboardInterrupt:
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 self.write_err("\nKeyboardInterrupt\n")
def _showtraceback(self, etype, evalue, stb):
"""Actually show a traceback.
Subclasses may override this method to put the traceback on a different
place, like a side channel.
"""
Fernando Perez
Fixed broken coloring on Windows....
r2974 print >> io.Term.cout, self.InteractiveTB.stb2text(stb)
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred.
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 This doesn't display a stack trace because there isn't one.
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
More re-organization of InteractiveShell.
r2242 If a filename is given, it is stuffed in the exception instead
of what was there before (because Python's parser always uses
"<string>" when reading from a string).
"""
etype, value, last_traceback = sys.exc_info()
Brian Granger
Massive, crazy refactoring of everything....
r2202
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 # See note about these variables in showtraceback() above
Brian Granger
More re-organization of InteractiveShell.
r2242 sys.last_type = etype
sys.last_value = value
sys.last_traceback = last_traceback
Brian Granger
Massive, crazy refactoring of everything....
r2202
Brian Granger
More re-organization of InteractiveShell.
r2242 if filename and etype is SyntaxError:
# Work hard to stuff the correct filename in the exception
try:
msg, (dummy_filename, lineno, offset, line) = value
except:
# Not the format we expect; leave it alone
pass
else:
# Stuff in the right filename
try:
# Assume SyntaxError is a class exception
value = SyntaxError(msg, (filename, lineno, offset, line))
except:
# If that failed, assume SyntaxError is a string
value = msg, (filename, lineno, offset, line)
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 stb = self.SyntaxTB.structured_traceback(etype, value, [])
self._showtraceback(etype, value, stb)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to readline
#-------------------------------------------------------------------------
def init_readline(self):
"""Command history completion/saving/reloading."""
Fernando Perez
Better handling of no-readline.
r2377 if self.readline_use:
import IPython.utils.rlineimpl as readline
Brian Granger
Second attempt to fix init_io readline test.
r2808
Brian Granger
More re-organization of InteractiveShell.
r2242 self.rl_next_input = None
self.rl_do_indent = False
Fernando Perez
Better handling of no-readline.
r2377 if not self.readline_use or not readline.have_readline:
self.has_readline = False
Brian Granger
More re-organization of InteractiveShell.
r2242 self.readline = None
Fernando Perez
Better handling of no-readline.
r2377 # Set a number of methods that depend on readline to be no-op
Fernando Perez
Simplify completer handling by isolating readline-specific logic more....
r2952 self.set_readline_completer = no_op
Fernando Perez
Better handling of no-readline.
r2377 self.set_custom_completer = no_op
self.set_completer_frame = no_op
warn('Readline services not available or not loaded.')
Brian Granger
More re-organization of InteractiveShell.
r2242 else:
Fernando Perez
Better handling of no-readline.
r2377 self.has_readline = True
self.readline = readline
Brian Granger
More re-organization of InteractiveShell.
r2242 sys.modules['readline'] = readline
Fernando Perez
Simplify completer handling by isolating readline-specific logic more....
r2952
Brian Granger
More re-organization of InteractiveShell.
r2242 # Platform-specific configuration
if os.name == 'nt':
Fernando Perez
Fix bug where atexit operations were only done if readline was present.
r2953 # FIXME - check with Frederick to see if we can harmonize
# naming conventions with pyreadline to avoid this
# platform-dependent check
Brian Granger
More re-organization of InteractiveShell.
r2242 self.readline_startup_hook = readline.set_pre_input_hook
else:
self.readline_startup_hook = readline.set_startup_hook
# Load user's initrc file (readline config)
# Or if libedit is used, load editrc.
inputrc_name = os.environ.get('INPUTRC')
if inputrc_name is None:
home_dir = get_home_dir()
if home_dir is not None:
inputrc_name = '.inputrc'
if readline.uses_libedit:
inputrc_name = '.editrc'
inputrc_name = os.path.join(home_dir, inputrc_name)
if os.path.isfile(inputrc_name):
try:
readline.read_init_file(inputrc_name)
except:
warn('Problems reading readline initialization file <%s>'
% inputrc_name)
# Configure readline according to user's prefs
# This is only done if GNU readline is being used. If libedit
# is being used (as on Leopard) the readline config is
# not run as the syntax for libedit is different.
if not readline.uses_libedit:
for rlcommand in self.readline_parse_and_bind:
#print "loading rl:",rlcommand # dbg
readline.parse_and_bind(rlcommand)
# Remove some chars from the delimiters list. If we encounter
# unicode chars, discard them.
delims = readline.get_completer_delims().encode("ascii", "ignore")
Thomas Kluyver
No need for string module now.
r3159 delims = delims.translate(None, self.readline_remove_delims)
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 delims = delims.replace(ESC_MAGIC, '')
Brian Granger
More re-organization of InteractiveShell.
r2242 readline.set_completer_delims(delims)
# otherwise we end up with a monster history after a while:
Satrajit Ghosh
History refactored and saved to json file...
r3240 readline.set_history_length(self.history_length)
Thomas Kluyver
Reworking magic %hist, %macro and %edit commands to work with new history system.
r3380
Thomas Kluyver
Fix up so tests pass again. input_splitter now uses ast module instead of compiler, bringing it closer to the Python 3 implementation.
r3454 stdin_encoding = sys.stdin.encoding or "utf-8"
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 # Load the last 1000 lines from history
Thomas Kluyver
Rename history retrieval methods, and improve docstrings.
r3435 for _, _, cell in self.history_manager.get_tail(1000,
Thomas Kluyver
Further refinements to history interfaces.
r3420 include_latest=True):
Thomas Kluyver
Initial conversion of history to SQLite database.
r3388 if cell.strip(): # Ignore blank lines
for line in cell.splitlines():
Thomas Kluyver
Fix up so tests pass again. input_splitter now uses ast module instead of compiler, bringing it closer to the Python 3 implementation.
r3454 readline.add_history(line.encode(stdin_encoding))
Brian Granger
More re-organization of InteractiveShell.
r2242
# Configure auto-indent for all platforms
self.set_autoindent(self.autoindent)
Brian Granger
Continuing a massive refactor of everything.
r2205
def set_next_input(self, s):
""" Sets the 'default' input string for the next command line.
Requires readline.
Example:
[D:\ipython]|1> _ip.set_next_input("Hello Word")
[D:\ipython]|2> Hello Word_ # cursor is here
"""
self.rl_next_input = s
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # Maybe move this to the terminal subclass?
Brian Granger
More re-organization of InteractiveShell.
r2242 def pre_readline(self):
"""readline hook to be used at the start of each line.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 Currently it handles auto-indent only."""
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 if self.rl_do_indent:
self.readline.insert_text(self._indent_current_str())
if self.rl_next_input is not None:
self.readline.insert_text(self.rl_next_input)
self.rl_next_input = None
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def _indent_current_str(self):
"""return the current level of indentation as a string"""
MinRK
merge interactiveshell.py
r3122 return self.input_splitter.indent_spaces * ' '
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 # Things related to text completion
#-------------------------------------------------------------------------
def init_completer(self):
"""Initialize the completion machinery.
This creates completion machinery that can be used by client code,
either interactively in-process (typically triggered by the readline
library), programatically (such as in test suites) or out-of-prcess
(typically over the network by remote frontends).
"""
from IPython.core.completer import IPCompleter
Fernando Perez
Restored major default completer functionality (cd, import, run)....
r2959 from IPython.core.completerlib import (module_completer,
magic_run_completer, cd_completer)
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 self.Completer = IPCompleter(self,
self.user_ns,
self.user_global_ns,
self.readline_omit__names,
self.alias_manager.alias_table,
self.has_readline)
Fernando Perez
Restored major default completer functionality (cd, import, run)....
r2959
# Add custom completers to the basic ones built into IPCompleter
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
self.strdispatchers['complete_command'] = sdisp
self.Completer.custom_completers = sdisp
Fernando Perez
Restored major default completer functionality (cd, import, run)....
r2959 self.set_hook('complete_command', module_completer, str_key = 'import')
self.set_hook('complete_command', module_completer, str_key = 'from')
self.set_hook('complete_command', magic_run_completer, str_key = '%run')
self.set_hook('complete_command', cd_completer, str_key = '%cd')
# Only configure readline if we truly are using readline. IPython can
# do tab-completion over the network, in GUIs, etc, where readline
# itself may be absent
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 if self.has_readline:
self.set_readline_completer()
def complete(self, text, line=None, cursor_pos=None):
"""Return the completed text and a list of completions.
Parameters
----------
text : string
A string of text to be completed on. It can be given as empty and
instead a line/position pair are given. In this case, the
completer itself will split the line like readline does.
line : string, optional
The complete line that text is part of.
cursor_pos : int, optional
The position of the cursor on the input line.
Returns
-------
text : string
The actual text that was completed.
matches : list
A sorted list with all possible completions.
The optional arguments allow the completion to take more context into
account, and are part of the low-level completion API.
This is a wrapper around the completion mechanism, similar to what
readline does at the command line when the TAB key is hit. By
exposing it as a method, it can be used by other non-readline
environments (such as GUIs) for text completion.
Simple usage example:
In [1]: x = 'hello'
In [2]: _ip.complete('x.l')
Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
"""
# Inject names into __builtin__ so we can complete on the added names.
with self.builtin_trap:
return self.Completer.complete(text, line, cursor_pos)
def set_custom_completer(self, completer, pos=0):
"""Adds a new custom completer function.
The position argument (defaults to 0) is the index in the completers
list where you want the completer to be inserted."""
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 newcomp = types.MethodType(completer,self.Completer)
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 self.Completer.matchers.insert(pos,newcomp)
def set_readline_completer(self):
"""Reset readline's completer to be our own."""
self.readline.set_completer(self.Completer.rlcomplete)
def set_completer_frame(self, frame=None):
"""Set the frame of the completer."""
if frame:
self.Completer.namespace = frame.f_locals
self.Completer.global_namespace = frame.f_globals
else:
self.Completer.namespace = self.user_ns
self.Completer.global_namespace = self.user_global_ns
#-------------------------------------------------------------------------
Brian Granger
More re-organization of InteractiveShell.
r2242 # Things related to magics
#-------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_magics(self):
Brian Granger
Refactor of prompts and the displayhook....
r2781 # FIXME: Move the color initialization to the DisplayHook, which
# should be split into a prompt manager and displayhook. We probably
# even need a centralize colors management object.
Brian Granger
More re-organization of InteractiveShell.
r2242 self.magic_colors(self.colors)
Fernando Perez
Fix %history magics....
r2421 # History was moved to a separate module
from . import history
history.init_ipython(self)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def magic(self,arg_s):
"""Call a magic function by name.
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Fernando Perez
Small cleanups, no functional changes.
r2955 Input: a string containing the name of the magic function to call and
any additional arguments to be passed to the magic.
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Brian Granger
More re-organization of InteractiveShell.
r2242 magic('name -opt foo bar') is equivalent to typing at the ipython
prompt:
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Brian Granger
More re-organization of InteractiveShell.
r2242 In[1]: %name -opt foo bar
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Brian Granger
More re-organization of InteractiveShell.
r2242 To call a magic without arguments, simply use magic('name').
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 This provides a proper Python function to call IPython's magics in any
valid Python code you can type at the interpreter, including loops and
compound statements.
"""
args = arg_s.split(' ',1)
magic_name = args[0]
Brian Granger
More work on refactoring things into components....
r2244 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 try:
magic_args = args[1]
except IndexError:
magic_args = ''
fn = getattr(self,'magic_'+magic_name,None)
if fn is None:
error("Magic function `%s` not found." % magic_name)
else:
magic_args = self.var_expand(magic_args,1)
Brian Granger
Massive refactoring of of the core....
r2245 with nested(self.builtin_trap,):
result = fn(magic_args)
Brian Granger
The pretty.py extension has been ported to the new extension API....
r2281 return result
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def define_magic(self, magicname, func):
"""Expose own function as magic function for ipython
def foo_impl(self,parameter_s=''):
'My very own magic!. (Use docstrings, IPython reads them).'
print 'Magic function. Passed parameter is between < >:'
print '<%s>' % parameter_s
print 'The self object is:',self
MinRK
merge interactiveshell.py
r3122
Brian Granger
More re-organization of InteractiveShell.
r2242 self.define_magic('foo',foo_impl)
"""
Ville M. Vainio
crlf -> lf
r1032
MinRK
merge interactiveshell.py
r3122 import new
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 im = types.MethodType(func,self)
Brian Granger
More re-organization of InteractiveShell.
r2242 old = getattr(self, "magic_" + magicname, None)
setattr(self, "magic_" + magicname, im)
return old
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to macros
#-------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def define_macro(self, name, themacro):
"""Define a new macro
Fernando Perez
Fix bug: https://bugs.launchpad.net/ipython/+bug/269966...
r1856
Brian Granger
More re-organization of InteractiveShell.
r2242 Parameters
----------
name : str
The name of the macro.
themacro : str or Macro
The action to do upon invoking the macro. If a string, a new
Macro object is created by passing the string to it.
Fernando Perez
Work again on bug 269966....
r1916 """
Brian Granger
More re-organization of InteractiveShell.
r2242
from IPython.core import macro
Fernando Perez
Work again on bug 269966....
r1916
Brian Granger
More re-organization of InteractiveShell.
r2242 if isinstance(themacro, basestring):
themacro = macro.Macro(themacro)
if not isinstance(themacro, macro.Macro):
raise ValueError('A macro must be a string or a Macro instance.')
self.user_ns[name] = themacro
Fernando Perez
Fix bug: https://bugs.launchpad.net/ipython/+bug/269966...
r1856
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to the running of system commands
#-------------------------------------------------------------------------
Fernando Perez
Fix bug: https://bugs.launchpad.net/ipython/+bug/269966...
r1856
Brian Granger
More re-organization of InteractiveShell.
r2242 def system(self, cmd):
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 """Call the given cmd in a subprocess.
Parameters
----------
cmd : str
Command to execute (can not end in '&', as bacground processes are
not supported.
"""
Fernando Perez
Remove shell hook and system_verbose magic....
r2905 # We do not support backgrounding processes because we either use
# pexpect or pipes to read from. Users can always just call
# os.system() if they really want a background process.
if cmd.endswith('&'):
raise OSError("Background processes not supported.")
return system(self.var_expand(cmd, depth=2))
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 def getoutput(self, cmd, split=True):
"""Get output (possibly including stderr) from a subprocess.
Parameters
----------
cmd : str
Fernando Perez
Add init_environment(), %less, %more, %man and %clear/%cls, in zmq shell....
r3005 Command to execute (can not end in '&', as background processes are
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 not supported.
split : bool, optional
If True, split the output into an IPython SList. Otherwise, an
IPython LSString is returned. These are objects similar to normal
lists and strings, with a few convenience attributes for easier
manipulation of line-based output. You can use '?' on them for
details.
"""
Fernando Perez
Remove shell hook and system_verbose magic....
r2905 if cmd.endswith('&'):
raise OSError("Background processes not supported.")
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 out = getoutput(self.var_expand(cmd, depth=2))
if split:
out = SList(out.splitlines())
else:
out = LSString(out)
return out
Fernando Perez
Remove shell hook and system_verbose magic....
r2905
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to aliases
#-------------------------------------------------------------------------
Brian Granger
More work on componentizing everything....
r2243 def init_alias(self):
Brian Granger
Adding support for HasTraits to take keyword arguments.
r2740 self.alias_manager = AliasManager(shell=self, config=self.config)
Brian Granger
Massive refactoring of of the core....
r2245 self.ns_table['alias'] = self.alias_manager.alias_table,
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 # Things related to extensions and plugins
Brian Granger
First draft of refactored Component->Configurable.
r2731 #-------------------------------------------------------------------------
def init_extension_manager(self):
Brian Granger
Adding support for HasTraits to take keyword arguments.
r2740 self.extension_manager = ExtensionManager(shell=self, config=self.config)
Brian Granger
First draft of refactored Component->Configurable.
r2731
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 def init_plugin_manager(self):
self.plugin_manager = PluginManager(config=self.config)
Brian Granger
First draft of refactored Component->Configurable.
r2731 #-------------------------------------------------------------------------
Brian Granger
Final attempt to fix init_io logic.
r2810 # Things related to payloads
#-------------------------------------------------------------------------
def init_payload(self):
self.payload_manager = PayloadManager(config=self.config)
#-------------------------------------------------------------------------
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # Things related to the prefilter
#-------------------------------------------------------------------------
def init_prefilter(self):
self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
# Ultimately this will be refactored in the new interpreter code, but
# for now, we should expose the main prefilter method (there's legacy
# code out there that may rely on this).
self.prefilter = self.prefilter_manager.prefilter_lines
Fernando Perez
Put auto_rewrite functionality into a method so subclasses can do the...
r2951 def auto_rewrite_input(self, cmd):
"""Print to the screen the rewritten form of the user's command.
Fernando Perez
Change wording of example so
r2954 This shows visual feedback by rewriting input lines that cause
automatic calling to kick in, like::
/f x
into::
Fernando Perez
Put auto_rewrite functionality into a method so subclasses can do the...
r2951
Fernando Perez
Change wording of example so
r2954 ------> f(x)
after the user's input prompt. This helps the user understand that the
input line was transformed automatically by IPython.
Fernando Perez
Put auto_rewrite functionality into a method so subclasses can do the...
r2951 """
rw = self.displayhook.prompt1.auto_rewrite() + cmd
try:
# plain ascii works better w/ pyreadline, on some machines, so
# we use it and only print uncolored rewrite if we have unicode
rw = str(rw)
print >> IPython.utils.io.Term.cout, rw
except UnicodeEncodeError:
print "------> " + cmd
Brian Granger
Complete reorganization of InteractiveShell....
r2761 #-------------------------------------------------------------------------
Fernando Perez
Rework messaging to better conform to our spec....
r2926 # Things related to extracting values/expressions from kernel and user_ns
#-------------------------------------------------------------------------
def _simple_error(self):
etype, value = sys.exc_info()[:2]
return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
Fernando Perez
Document the code execution semantics much more carefully....
r3050 def user_variables(self, names):
Fernando Perez
Rework messaging to better conform to our spec....
r2926 """Get a list of variable names from the user's namespace.
Fernando Perez
Document the code execution semantics much more carefully....
r3050 Parameters
----------
names : list of strings
A list of names of variables to be read from the user namespace.
Returns
-------
A dict, keyed by the input names and with the repr() of each value.
Fernando Perez
Rework messaging to better conform to our spec....
r2926 """
out = {}
user_ns = self.user_ns
for varname in names:
try:
value = repr(user_ns[varname])
except:
value = self._simple_error()
out[varname] = value
return out
Fernando Perez
Document the code execution semantics much more carefully....
r3050 def user_expressions(self, expressions):
Fernando Perez
Rework messaging to better conform to our spec....
r2926 """Evaluate a dict of expressions in the user's namespace.
Fernando Perez
Document the code execution semantics much more carefully....
r3050 Parameters
----------
expressions : dict
A dict with string keys and string values. The expression values
should be valid Python expressions, each of which will be evaluated
in the user namespace.
Returns
-------
A dict, keyed like the input expressions dict, with the repr() of each
value.
Fernando Perez
Rework messaging to better conform to our spec....
r2926 """
out = {}
user_ns = self.user_ns
global_ns = self.user_global_ns
for key, expr in expressions.iteritems():
try:
value = repr(eval(expr, global_ns, user_ns))
except:
value = self._simple_error()
out[key] = value
return out
#-------------------------------------------------------------------------
Brian Granger
More re-organization of InteractiveShell.
r2242 # Things related to the running of code
#-------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def ex(self, cmd):
"""Execute a normal python statement in user namespace."""
Brian Granger
Massive refactoring of of the core....
r2245 with nested(self.builtin_trap,):
Brian Granger
More re-organization of InteractiveShell.
r2242 exec cmd in self.user_global_ns, self.user_ns
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def ev(self, expr):
"""Evaluate python expression expr in user namespace.
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 Returns the result of evaluation
"""
Brian Granger
Massive refactoring of of the core....
r2245 with nested(self.builtin_trap,):
Brian Granger
More re-organization of InteractiveShell.
r2242 return eval(expr, self.user_global_ns, self.user_ns)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Work on startup related things....
r2252 def safe_execfile(self, fname, *where, **kw):
Brian Granger
More re-organization of InteractiveShell.
r2242 """A safe version of the builtin execfile().
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Work on startup related things....
r2252 This version will never throw an exception, but instead print
helpful error messages to the screen. This only works on pure
Python files with the .py extension.
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
Work on startup related things....
r2252 Parameters
----------
fname : string
The name of the file to be executed.
where : tuple
Brian Granger
More re-organization of InteractiveShell.
r2242 One or two namespaces, passed to execfile() as (globals,locals).
If only one is given, it is passed as both.
Brian Granger
Work on startup related things....
r2252 exit_ignore : bool (False)
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 If True, then silence SystemExit for non-zero status (it is always
silenced for zero status, as it is so common).
Brian Granger
Work on startup related things....
r2252 """
kw.setdefault('exit_ignore', False)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Work on startup related things....
r2252 fname = os.path.abspath(os.path.expanduser(fname))
# Make sure we have a .py file
if not fname.endswith('.py'):
warn('File must end with .py to be run using execfile: <%s>' % fname)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Work on startup related things....
r2252 # Make sure we can open the file
try:
with open(fname) as thefile:
pass
except:
warn('Could not open file <%s> for safe execution.' % fname)
return
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 # Find things also in current directory. This is needed to mimic the
# behavior of running a script from the system command line, where
# Python inserts the script's directory into sys.path
Brian Granger
Work on startup related things....
r2252 dname = os.path.dirname(fname)
MinRK
fix at least some command-line unicode options
r3464
if isinstance(fname, unicode):
# execfile uses default encoding instead of filesystem encoding
# so unicode filenames will fail
fname = fname.encode(sys.getfilesystemencoding() or sys.getdefaultencoding())
Brian Granger
More re-organization of InteractiveShell.
r2242
Brian Granger
Work on startup related things....
r2252 with prepended_to_syspath(dname):
Brian Granger
More re-organization of InteractiveShell.
r2242 try:
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 execfile(fname,*where)
Brian Granger
Work on startup related things....
r2252 except SystemExit, status:
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 # If the call was made with 0 or None exit status (sys.exit(0)
# or sys.exit() ), don't bother showing a traceback, as both of
# these are considered normal by the OS:
# > python -c'import sys;sys.exit(0)'; echo $?
# 0
# > python -c'import sys;sys.exit()'; echo $?
# 0
# For other exit status, we show the exception unless
# explicitly silenced, but only in short form.
if status.code not in (0, None) and not kw['exit_ignore']:
self.showtraceback(exception_only=True)
Brian Granger
More re-organization of InteractiveShell.
r2242 except:
self.showtraceback()
Brian Granger
Work on startup related things....
r2252 def safe_execfile_ipy(self, fname):
"""Like safe_execfile, but for .ipy files with IPython syntax.
Parameters
----------
fname : str
The name of the file to execute. The filename must have a
.ipy extension.
"""
fname = os.path.abspath(os.path.expanduser(fname))
# Make sure we have a .py file
if not fname.endswith('.ipy'):
warn('File must end with .py to be run using execfile: <%s>' % fname)
# Make sure we can open the file
try:
with open(fname) as thefile:
pass
except:
warn('Could not open file <%s> for safe execution.' % fname)
return
# Find things also in current directory. This is needed to mimic the
# behavior of running a script from the system command line, where
# Python inserts the script's directory into sys.path
dname = os.path.dirname(fname)
with prepended_to_syspath(dname):
try:
with open(fname) as thefile:
MinRK
merge interactiveshell.py
r3122 # self.run_cell currently captures all exceptions
# raised in user code. It would be nice if there were
Brian Granger
Work on startup related things....
r2252 # versions of runlines, execfile that did raise, so
# we could catch the errors.
MinRK
merge interactiveshell.py
r3122 self.run_cell(thefile.read())
Brian Granger
Work on startup related things....
r2252 except:
self.showtraceback()
warn('Unknown failure executing file: <%s>' % fname)
Brian Granger
Continuing a massive refactor of everything.
r2205
Thomas Kluyver
Give .run_cell a store_history option, so that it can be used to run raw IPython code outside of the sequence of commands making the session. This also doesn't incremement the execution_count.
r3423 def run_cell(self, cell, store_history=True):
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 """Run the contents of an entire multiline 'cell' of code, and store it
in the history.
Fernando Perez
Add experimental support for cell-based execution....
r2967
The cell is split into separate blocks which can be executed
individually. Then, based on how many blocks there are, they are
executed as follows:
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 - A single block: 'single' mode. If it is also a single line, dynamic
transformations, including automagic and macros, will be applied.
Fernando Perez
Add experimental support for cell-based execution....
r2967
If there's more than one block, it depends:
Fernando Perez
Document the code execution semantics much more carefully....
r3050 - if the last one is no more than two lines long, run all but the last
in 'exec' mode and the very last one in 'single' mode. This makes it
easy to type simple expressions at the end to see computed values. -
otherwise (last one is also multiline), run all in 'exec' mode
Fernando Perez
Add experimental support for cell-based execution....
r2967
When code is executed in 'single' mode, :func:`sys.displayhook` fires,
results are displayed and output prompts are computed. In 'exec' mode,
no results are displayed unless :func:`print` is called explicitly;
this mode is more akin to running a script.
Parameters
----------
cell : str
A single or multiline string.
"""
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 # Store the untransformed code
raw_cell = cell
Fernando Perez
Fix missing history in cell execution mode....
r2973 # We need to break up the input into executable blocks that can be run
# in 'single' mode, to provide comfortable user behavior.
Fernando Perez
Add experimental support for cell-based execution....
r2967 blocks = self.input_splitter.split_blocks(cell)
Fernando Perez
Fix missing history in cell execution mode....
r2973
Thomas Kluyver
Fix blank input crashing IPython, +unittest
r3441 if not blocks: # Blank cell
Fernando Perez
Add experimental support for cell-based execution....
r2967 return
Thomas Kluyver
Fix blank input crashing IPython, +unittest
r3441
# We only do dynamic transforms on a single line. But a macro can
# be expanded to several lines, so we need to split it into input
# blocks again.
if len(cell.splitlines()) <= 1:
cell = self.prefilter_manager.prefilter_line(blocks[0])
blocks = self.input_splitter.split_blocks(cell)
Fernando Perez
Add experimental support for cell-based execution....
r2967
MinRK
merge interactiveshell.py
r3122 # Store the 'ipython' version of the cell as well, since that's what
# needs to go into the translated history and get executed (the
# original cell may contain non-python syntax).
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 cell = ''.join(blocks)
MinRK
merge interactiveshell.py
r3122
# Store raw and processed history
Thomas Kluyver
Give .run_cell a store_history option, so that it can be used to run raw IPython code outside of the sequence of commands making the session. This also doesn't incremement the execution_count.
r3423 if store_history:
self.history_manager.store_inputs(self.execution_count,
cell, raw_cell)
MinRK
merge interactiveshell.py
r3122
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 self.logger.log(cell, raw_cell)
MinRK
merge interactiveshell.py
r3122
# All user code execution must happen with our context managers active
with nested(self.builtin_trap, self.display_trap):
# Single-block input should behave like an interactive prompt
if len(blocks) == 1:
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 out = self.run_source(blocks[0])
Thomas Kluyver
Allow history to store multiple outputs for a single input line.
r3415 # Write output to the database. Does nothing unless
# history output logging is enabled.
Thomas Kluyver
Give .run_cell a store_history option, so that it can be used to run raw IPython code outside of the sequence of commands making the session. This also doesn't incremement the execution_count.
r3423 if store_history:
self.history_manager.store_output(self.execution_count)
# since we return here, we need to update the execution count
self.execution_count += 1
MinRK
merge interactiveshell.py
r3122 return out
# In multi-block input, if the last block is a simple (one-two
# lines) expression, run it in single mode so it produces output.
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 # Otherwise just run it all in 'exec' mode. This seems like a
# reasonable usability design.
MinRK
merge interactiveshell.py
r3122 last = blocks[-1]
last_nlines = len(last.splitlines())
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414
MinRK
merge interactiveshell.py
r3122 if last_nlines < 2:
# Here we consider the cell split between 'body' and 'last',
# store all history and execute 'body', and if successful, then
# proceed to execute 'last'.
# Get the main body to run as a cell
ipy_body = ''.join(blocks[:-1])
Fernando Perez
Complete implementation of interactive traceback support....
r3175 retcode = self.run_source(ipy_body, symbol='exec',
post_execute=False)
MinRK
merge interactiveshell.py
r3122 if retcode==0:
Thomas Kluyver
Refactor execution logic, so that a multi-line macro is correctly expanded and executed (+ unit test). History is now stored after all input transformations have been done.
r3414 # Last expression compiled as 'single' so it produces output
self.run_source(last)
MinRK
merge interactiveshell.py
r3122 else:
# Run the whole cell as one entity, storing both raw and
# processed input in history
Fernando Perez
Complete implementation of interactive traceback support....
r3175 self.run_source(ipy_cell, symbol='exec')
MinRK
merge interactiveshell.py
r3122
Thomas Kluyver
Allow history to store multiple outputs for a single input line.
r3415 # Write output to the database. Does nothing unless
# history output logging is enabled.
Thomas Kluyver
Give .run_cell a store_history option, so that it can be used to run raw IPython code outside of the sequence of commands making the session. This also doesn't incremement the execution_count.
r3423 if store_history:
self.history_manager.store_output(self.execution_count)
# Each cell is a *single* input, regardless of how many lines it has
self.execution_count += 1
Fernando Perez
Add experimental support for cell-based execution....
r2967
Fernando Perez
Add pending removal comments regarding the input handling methods in the kernel
r3139 # PENDING REMOVAL: this method is slated for deletion, once our new
# input logic has been 100% moved to frontends and is stable.
Brian Granger
Continuing a massive refactor of everything.
r2205 def runlines(self, lines, clean=False):
Ville M. Vainio
crlf -> lf
r1032 """Run a string of one or more lines of source.
This method is capable of running a string containing multiple source
lines, as if they had been entered at the IPython prompt. Since it
exposes IPython's processing machinery, the given strings can contain
Brian Granger
Continuing a massive refactor of everything.
r2205 magic calls (%magic), special shell access (!cmd), etc.
"""
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838
Thomas Kluyver
ipython-qtconsole now calls the right function.
r3397 if not isinstance(lines, (list, tuple)):
lines = lines.splitlines()
Brian Granger
Continuing a massive refactor of everything.
r2205
if clean:
Brian Granger
Complete reorganization of InteractiveShell....
r2761 lines = self._cleanup_ipy_script(lines)
Ville M. Vainio
crlf -> lf
r1032
# We must start with a clean buffer, in case this is run from an
# interactive IPython session (via a magic, for example).
MinRK
merge interactiveshell.py
r3122 self.reset_buffer()
# Since we will prefilter all lines, store the user's raw input too
# before we apply any transformations
self.buffer_raw[:] = [ l+'\n' for l in lines]
more = False
prefilter_lines = self.prefilter_manager.prefilter_lines
Brian Granger
sys.displayhook is now managed dynamically by display_trap.
r2231 with nested(self.builtin_trap, self.display_trap):
Brian Granger
Created context manager for the things injected into __builtin__.
r2227 for line in lines:
Fernando Perez
Small cleanups, no functional changes.
r2955 # skip blank lines so we don't mess up the prompt counter, but
# do NOT skip even a blank line if we are in a code block (more
# is true)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Created context manager for the things injected into __builtin__.
r2227 if line or more:
MinRK
merge interactiveshell.py
r3122 more = self.push_line(prefilter_lines(line, more))
# IPython's run_source returns None if there was an error
Fernando Perez
Small cleanups, no functional changes.
r2955 # compiling the code. This allows us to stop processing
# right away, so the user gets the error message at the
# right place.
Brian Granger
Created context manager for the things injected into __builtin__.
r2227 if more is None:
break
# final newline in case the input didn't have it, so that the code
# actually does get executed
if more:
self.push_line('\n')
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Complete implementation of interactive traceback support....
r3175 def run_source(self, source, filename=None,
symbol='single', post_execute=True):
Ville M. Vainio
crlf -> lf
r1032 """Compile and run some source in the interpreter.
Arguments are as for compile_command().
One several things can happen:
1) The input is incorrect; compile_command() raised an
exception (SyntaxError or OverflowError). A syntax traceback
will be printed by calling the showsyntaxerror() method.
2) The input is incomplete, and more input is required;
compile_command() returned None. Nothing happens.
3) The input is complete; compile_command() returned a code
MinRK
merge interactiveshell.py
r3122 object. The code is executed by calling self.run_code() (which
Ville M. Vainio
crlf -> lf
r1032 also handles run-time exceptions, except for SystemExit).
The return value is:
- True in case 2
- False in the other cases, unless an exception is raised, where
None is returned instead. This can be used by external callers to
know whether to continue feeding input or not.
The return value can be used to decide whether to use sys.ps1 or
sys.ps2 to prompt the next line."""
Fernando Perez
Unicode fixes, basic input/printing of unicode works.
r3038 # We need to ensure that the source is unicode from here on.
if type(source)==str:
Fernando Perez
Stop-gap fix for crash with unicode input....
r3126 usource = source.decode(self.stdin_encoding)
else:
usource = source
Thomas Kluyver
Fix up so tests pass again. input_splitter now uses ast module instead of compiler, bringing it closer to the Python 3 implementation.
r3454 if False: # dbg
Fernando Perez
Stop-gap fix for crash with unicode input....
r3126 print 'Source:', repr(source) # dbg
print 'USource:', repr(usource) # dbg
print 'type:', type(source) # dbg
print 'encoding', self.stdin_encoding # dbg
Fernando Perez
Unicode fixes, basic input/printing of unicode works.
r3038
Ville M. Vainio
crlf -> lf
r1032 try:
Fernando Perez
Complete implementation of interactive traceback support....
r3175 code = self.compile(usource, symbol, self.execution_count)
Ville M. Vainio
catch MemoryError on compile() (crash reported by Daniel Ashbrook)
r1999 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
Ville M. Vainio
crlf -> lf
r1032 # Case 1
self.showsyntaxerror(filename)
return None
if code is None:
# Case 2
return True
# Case 3
# We store the code object so that threaded shells and
# custom exception handlers can access all this info if needed.
# The source corresponding to this can be obtained from the
# buffer attribute as '\n'.join(self.buffer).
self.code_to_run = code
# now actually execute the code object
Fernando Perez
Complete implementation of interactive traceback support....
r3175 if self.run_code(code, post_execute) == 0:
Ville M. Vainio
crlf -> lf
r1032 return False
else:
return None
MinRK
merge interactiveshell.py
r3122 # For backwards compatibility
runsource = run_source
def run_code(self, code_obj, post_execute=True):
Ville M. Vainio
crlf -> lf
r1032 """Execute a code object.
When an exception occurs, self.showtraceback() is called to display a
traceback.
Return value: a flag indicating whether the code to be run completed
successfully:
- 0: successful execution.
- 1: an error occurred.
"""
# Set our own excepthook in case the user code tries to call it
# directly, so that the IPython crash handler doesn't get triggered
old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
# we save the original sys.excepthook in the instance, in case config
# code (such as magics) needs access to it.
self.sys_excepthook = old_excepthook
outflag = 1 # happens in more places, so it's easier as default
try:
try:
MinRK
merge interactiveshell.py
r3122 self.hooks.pre_run_code_hook()
Fernando Perez
Improve docs and comments of some internal tools, and of testing code
r3297 #rprint('Running code', repr(code_obj)) # dbg
Robert Kern
ENH: Allow non-dict namespaces. This involves a change in the ipapi for setting user namespaces.
r1419 exec code_obj in self.user_global_ns, self.user_ns
Ville M. Vainio
crlf -> lf
r1032 finally:
# Reset our crash handler in place
sys.excepthook = old_excepthook
except SystemExit:
MinRK
merge interactiveshell.py
r3122 self.reset_buffer()
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 self.showtraceback(exception_only=True)
warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
Ville M. Vainio
crlf -> lf
r1032 except self.custom_exceptions:
etype,value,tb = sys.exc_info()
self.CustomTB(etype,value,tb)
except:
self.showtraceback()
else:
outflag = 0
if softspace(sys.stdout, 0):
print
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987
# Execute any registered post-execution functions. Here, any errors
# are reported only minimally and just on the terminal, because the
# main exception channel may be occupied with a user traceback.
# FIXME: we need to think this mechanism a little more carefully.
Fernando Perez
Fix bug where post-execute code was being called twice.
r2992 if post_execute:
for func in self._post_execute:
try:
func()
except:
head = '[ ERROR ] Evaluating post_execute function: %s' % \
func
print >> io.Term.cout, head
print >> io.Term.cout, self._simple_error()
print >> io.Term.cout, 'Removing from post_execute'
self._post_execute.remove(func)
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987
Ville M. Vainio
crlf -> lf
r1032 # Flush out code object which has been run (and source)
self.code_to_run = None
return outflag
MinRK
merge interactiveshell.py
r3122 # For backwards compatibility
runcode = run_code
Fernando Perez
Add pending removal comments regarding the input handling methods in the kernel
r3139
# PENDING REMOVAL: this method is slated for deletion, once our new
# input logic has been 100% moved to frontends and is stable.
Brian Granger
Continuing a massive refactor of everything.
r2205 def push_line(self, line):
Ville M. Vainio
crlf -> lf
r1032 """Push a line to the interpreter.
The line should not have a trailing newline; it may have
internal newlines. The line is appended to a buffer and the
MinRK
merge interactiveshell.py
r3122 interpreter's run_source() method is called with the
Ville M. Vainio
crlf -> lf
r1032 concatenated contents of the buffer as source. If this
indicates that the command was executed or invalid, the buffer
is reset; otherwise, the command is incomplete, and the buffer
is left as it was after the line was appended. The return
value is 1 if more input is required, 0 if the line was dealt
MinRK
merge interactiveshell.py
r3122 with in some way (this is the same as run_source()).
Ville M. Vainio
crlf -> lf
r1032 """
# autoindent management should be done here, and not in the
# interactive loop, since that one is only seen by keyboard input. We
# need this done correctly even for code run via runlines (which uses
# push).
#print 'push line: <%s>' % line # dbg
self.buffer.append(line)
MinRK
merge interactiveshell.py
r3122 full_source = '\n'.join(self.buffer)
more = self.run_source(full_source, self.filename)
Ville M. Vainio
crlf -> lf
r1032 if not more:
Thomas Kluyver
Tidy up store_inputs
r3390 self.history_manager.store_inputs(self.execution_count,
'\n'.join(self.buffer_raw), full_source)
MinRK
merge interactiveshell.py
r3122 self.reset_buffer()
self.execution_count += 1
Ville M. Vainio
crlf -> lf
r1032 return more
MinRK
merge interactiveshell.py
r3122 def reset_buffer(self):
Brian Granger
Complete reorganization of InteractiveShell....
r2761 """Reset the input buffer."""
self.buffer[:] = []
MinRK
merge interactiveshell.py
r3122 self.buffer_raw[:] = []
self.input_splitter.reset()
# For backwards compatibility
resetbuffer = reset_buffer
Brian Granger
Complete reorganization of InteractiveShell....
r2761
def _is_secondary_block_start(self, s):
if not s.endswith(':'):
return False
if (s.startswith('elif') or
s.startswith('else') or
s.startswith('except') or
s.startswith('finally')):
return True
def _cleanup_ipy_script(self, script):
"""Make a script safe for self.runlines()
Currently, IPython is lines based, with blocks being detected by
empty lines. This is a problem for block based scripts that may
not have empty lines after blocks. This script adds those empty
lines to make scripts safe for running in the current line based
IPython.
"""
res = []
lines = script.splitlines()
level = 0
for l in lines:
lstripped = l.lstrip()
stripped = l.strip()
if not stripped:
continue
newlevel = len(l) - len(lstripped)
if level > 0 and newlevel == 0 and \
not self._is_secondary_block_start(stripped):
# add empty line
res.append('')
res.append(l)
level = newlevel
return '\n'.join(res) + '\n'
Brian Granger
Work on startup related things....
r2252 #-------------------------------------------------------------------------
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # Things related to GUI support and pylab
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Complete reorganization of InteractiveShell....
r2761 def enable_pylab(self, gui=None):
raise NotImplementedError('Implement enable_pylab in a subclass')
Brian Granger
More re-organization of InteractiveShell.
r2242
#-------------------------------------------------------------------------
# Utilities
#-------------------------------------------------------------------------
Brian Granger
Massive, crazy refactoring of everything....
r2202 def var_expand(self,cmd,depth=0):
"""Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is always the user's interactive
namespace.
"""
return str(ItplNS(cmd,
self.user_ns, # globals
# Skip our own frame in searching for locals:
sys._getframe(depth+1).f_locals # locals
))
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Complete implementation of interactive traceback support....
r3175 def mktempfile(self, data=None, prefix='ipython_edit_'):
Ville M. Vainio
crlf -> lf
r1032 """Make a new tempfile and return its filename.
This makes a call to tempfile.mktemp, but it registers the created
filename internally so ipython cleans it up at exit time.
Optional inputs:
- data(None): if data is given, it gets written out to the temp file
immediately, and the file is closed again."""
Fernando Perez
Complete implementation of interactive traceback support....
r3175 filename = tempfile.mktemp('.py', prefix)
Ville M. Vainio
crlf -> lf
r1032 self.tempfiles.append(filename)
if data:
tmp_file = open(filename,'w')
tmp_file.write(data)
tmp_file.close()
return filename
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # TODO: This should be removed when Term is refactored.
Ville M. Vainio
crlf -> lf
r1032 def write(self,data):
"""Write a string to the default output"""
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 io.Term.cout.write(data)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # TODO: This should be removed when Term is refactored.
Ville M. Vainio
crlf -> lf
r1032 def write_err(self,data):
"""Write a string to the default error output"""
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 io.Term.cerr.write(data)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def ask_yes_no(self,prompt,default=True):
if self.quiet:
return True
return ask_yes_no(prompt,default)
Fernando Perez
Get naked '?' to work, and in-spec with the new inputsplitter design.
r2876
def show_usage(self):
"""Show a usage message"""
page.page(IPython.core.usage.interactive_usage)
Brian Granger
More re-organization of InteractiveShell.
r2242
#-------------------------------------------------------------------------
# Things related to IPython exiting
#-------------------------------------------------------------------------
def atexit_operations(self):
"""This will be executed at the time of exit.
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Fix bug where atexit operations were only done if readline was present.
r2953 Cleanup operations and saving of persistent data that is done
unconditionally by IPython should be performed here.
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
Fix bug where atexit operations were only done if readline was present.
r2953 For things that may depend on startup flags or platform specifics (such
as having readline or not), register a separate atexit function in the
code that has the appropriate information, rather than trying to
clutter
"""
Brian Granger
More re-organization of InteractiveShell.
r2242 # Cleanup all tempfiles left around
for tfile in self.tempfiles:
try:
os.unlink(tfile)
except OSError:
pass
Thomas Kluyver
Store history sessions in table with start and end time, number of commands, and name/remark.
r3405
# Close the history session (this stores the end time and line count)
self.history_manager.end_session()
Brian Granger
More re-organization of InteractiveShell.
r2242 # Clear all user namespaces to release all references cleanly.
Thomas Kluyver
ipython-qtconsole now calls the right function.
r3397 self.reset(new_session=False)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 # Run user hooks
self.hooks.shutdown_hook()
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 def cleanup(self):
self.restore_sys_module_state()
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 class InteractiveShellABC(object):
"""An abstract base class for InteractiveShell."""
__metaclass__ = abc.ABCMeta
InteractiveShellABC.register(InteractiveShell)