##// END OF EJS Templates
Fix issue with pycat docs build
r26639:955ddb5a
Show More
interactiveshell.py
3880 lines | 152.3 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 #-----------------------------------------------------------------------------
Brian Granger
Created context manager for the things injected into __builtin__.
r2227
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 import abc
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 import ast
Fernando Perez
Fix bug where atexit operations were only done if readline was present.
r2953 import atexit
Thomas Kluyver
Remove uses of compatibility builtin_mod and builtin_mod_name
r23129 import builtins as builtin_mod
Thomas Kluyver
Declare ip.register_magic_function at class level so that it is included in docs
r12297 import functools
Matthias Bussonnier
clenup a bit
r25052 import inspect
Ville M. Vainio
crlf -> lf
r1032 import os
import re
Bradley M. Froehle
Add '-m mod : run library module as a script' option....
r6029 import runpy
Ville M. Vainio
crlf -> lf
r1032 import sys
import tempfile
Jeroen Demeyer
Print exception instead of "KeyboardInterrupt"...
r19114 import traceback
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 import types
Théophile Studer
Use default OS shell to run system commands...
r12217 import subprocess
Matthias Bussonnier
register default deprecation warning filter....
r21391 import warnings
MinRK
fix missing imports in core.interactiveshell...
r8372 from io import open as io_open
Ville M. Vainio
crlf -> lf
r1032
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014 from pathlib import Path
Min RK
remove pickleshare from external
r20844 from pickleshare import PickleShareDB
Min RK
update dependency imports...
r21253 from traitlets.config.configurable import SingletonConfigurable
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 from traitlets.utils.importstring import import_item
Matthias Bussonnier
Remove Pydb integration as Pydb is unmaintained and not ion PyPI...
r22359 from IPython.core import oinspect
Fernando Perez
Add proper initialization of magics to main shell instance....
r6923 from IPython.core import magic
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 ultratb
Thomas Kluyver
Reorder info fields to put most useful first...
r20568 from IPython.core.alias import Alias, AliasManager
Thomas Kluyver
Replace magic exit function with exit subclassing IPyAutocall. Credit to David Warde-Farley (@dwf) for tackling this issue.
r3721 from IPython.core.autocall import ExitAutocall
Brian Granger
Created context manager for the things injected into __builtin__.
r2227 from IPython.core.builtin_trap import BuiltinTrap
Thomas Kluyver
Rename callbacks -> events (mostly), fire -> trigger
r15605 from IPython.core.events import EventManager, available_events
Thomas Kluyver
Better support compiling cells with separate __future__ environments
r9140 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
Thomas Kluyver
Create separate class for debugger using prompt_toolkit
r22391 from IPython.core.debugger import Pdb
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
Scott Sanderson
MAINT: Move `InputRejected` to `IPython.core.error`.
r17799 from IPython.core.error import InputRejected, UsageError
Brian Granger
First draft of refactored Component->Configurable.
r2731 from IPython.core.extensions import ExtensionManager
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
Thomas Kluyver
Switch some imports from inputsplitter to inputtransformer2
r24176 from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2
Brian Granger
Logger.py => core/logger.py and updated imports.
r2032 from IPython.core.logger import Logger
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 from IPython.core.macro import Macro
Brian Granger
Fixing imports and syntax errors.
r2812 from IPython.core.payload import PayloadManager
MinRK
define ESC_FOO consts only in inputsplitter...
r7437 from IPython.core.prefilter import PrefilterManager
MinRK
move ipcluster create|list to `ipython profile create|list`...
r4024 from IPython.core.profiledir import ProfileDir
MinRK
move banner to base InteractiveShell class
r16581 from IPython.core.usage import default_banner
Matthias Bussonnier
Inject display into builtins...
r23711 from IPython.display import display
Paul Ivanov
remove Python2/3 specific decorators
r22960 from IPython.testing.skipdoctest import skip_doctest
Brian Granger
Massive, crazy refactoring of everything....
r2202 from IPython.utils import PyColorize
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 from IPython.utils import io
Thomas Kluyver
Start using py3compat module.
r4731 from IPython.utils import py3compat
Matthias BUSSONNIER
make pycat and loadpy aware of history and more...
r6761 from IPython.utils import openpy
Thomas Kluyver
Add way to mark classes & functions as undocumented.
r8793 from IPython.utils.decorators import undoc
Matthias BUSSONNIER
remove unused input according to pylint
r6776 from IPython.utils.io import ask_yes_no
Fernando Perez
First semi-complete support for -pylab and %pylab....
r2363 from IPython.utils.ipstruct import Struct
Min RK
update dependency imports...
r21253 from IPython.paths import get_ipython_dir
Antony Lee
On Windows, quote paths instead of escaping them.
r22418 from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
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
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
Sylvain Corlay
Use TemporaryDirectory context manager
r22461 from IPython.utils.tempdir import TemporaryDirectory
Min RK
adopt traitlets 4.2 API...
r22340 from traitlets import (
Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 observe, default, validate, Any
Min RK
adopt traitlets 4.2 API...
r22340 )
Pierre Gerold
Replace all import of IPython.utils.warn module
r22092 from warnings import warn
from logging import error
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 import IPython.core.hooks
Brian Granger
Massive, crazy refactoring of everything....
r2202
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 from typing import List as ListType, Tuple, Optional
Matthias Bussonnier
Add new interactivity mode for ast....
r23730 from ast import AST
Thomas Kluyver
Restore NoOpContext location for ipykernel to import...
r22692 # NoOpContext is deprecated, but ipykernel imports it from here.
# See https://github.com/ipython/ipykernel/issues/157
Matthias Bussonnier
Cleanup unused imports.
r25335 # (2016, let's try to remove than in IPython 8.0)
Thomas Kluyver
Restore NoOpContext location for ipykernel to import...
r22692 from IPython.utils.contexts import NoOpContext
Sylvain Corlay
Sphinxify docstrings
r22459 try:
import docrepr.sphinxify as sphx
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 def sphinxify(doc):
Sylvain Corlay
Use TemporaryDirectory context manager
r22461 with TemporaryDirectory() as dirname:
return {
'text/html': sphx.sphinxify(doc, dirname),
'text/plain': doc
}
Matthias Bussonnier
Catch only ImportError
r22467 except ImportError:
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 sphinxify = None
Sylvain Corlay
Sphinxify docstrings
r22459
Matthias Bussonnier
Add provisional warnings.
r22496
class ProvisionalWarning(DeprecationWarning):
"""
Warning class for unstable features
"""
pass
Matthias Bussonnier
Mock the new module API on <38 and ignore second argument....
r24921 if sys.version_info > (3,8):
from ast import Module
else :
# mock the new API, ignore second argument
# see https://github.com/ipython/ipython/issues/11590
from ast import Module as OriginalModule
Module = lambda nodelist, type_ignores: OriginalModule(nodelist)
Matthias Bussonnier
Add new interactivity mode for ast....
r23730 if sys.version_info > (3,6):
_assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
_single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
else:
_assign_nodes = (ast.AugAssign, ast.Assign )
_single_targets_nodes = (ast.AugAssign, )
Brian Granger
Massive, crazy refactoring of everything....
r2202 #-----------------------------------------------------------------------------
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 # Await Helpers
#-----------------------------------------------------------------------------
def removed_co_newlocals(function:types.FunctionType) -> types.FunctionType:
Matthias Bussonnier
DOC: more docstrign formatting
r25907 """Return a function that do not create a new local scope.
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463
Given a function, create a clone of this function where the co_newlocal flag
has been removed, making this function code actually run in the sourounding
Matthias Bussonnier
DOC: more docstrign formatting
r25907 scope.
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463
We need this in order to run asynchronous code in user level namespace.
"""
from types import CodeType, FunctionType
CO_NEWLOCALS = 0x0002
code = function.__code__
Daniel Hahler
Use CodeType.replace with Python 3.8...
r25067 new_co_flags = code.co_flags & ~CO_NEWLOCALS
stonebig
be more precise : >3.8.0a3
r25028 if sys.version_info > (3, 8, 0, 'alpha', 3):
Daniel Hahler
Use CodeType.replace with Python 3.8...
r25067 new_code = code.replace(co_flags=new_co_flags)
stonebig
Python-3.8 PEP570 positional only argument
r25027 else:
new_code = CodeType(
code.co_argcount,
code.co_kwonlyargcount,
Daniel Hahler
Use CodeType.replace with Python 3.8...
r25067 code.co_nlocals,
code.co_stacksize,
new_co_flags,
code.co_code,
stonebig
Python-3.8 PEP570 positional only argument
r25027 code.co_consts,
Daniel Hahler
Use CodeType.replace with Python 3.8...
r25067 code.co_names,
code.co_varnames,
code.co_filename,
code.co_name,
code.co_firstlineno,
code.co_lnotab,
code.co_freevars,
stonebig
Python-3.8 PEP570 positional only argument
r25027 code.co_cellvars
Daniel Hahler
Use CodeType.replace with Python 3.8...
r25067 )
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 return FunctionType(new_code, globals(), function.__name__, function.__defaults__)
Matthias Bussonnier
Load the asycn ext only on 3.5+
r24467 # we still need to run things using the asyncio eventloop, but there is no
# async integration
Matthias Bussonnier
Add pseudo sync mode
r24481 from .async_helpers import (_asyncio_runner, _asyncify, _pseudo_sync_runner)
kousik
Removed codepath for Python < 3.6 #11949
r25245 from .async_helpers import _curio_runner, _trio_runner, _should_be_async
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463
def _ast_asyncify(cell:str, wrapper_name:str) -> ast.Module:
"""
Parse a cell with top-level await and modify the AST to be able to run it later.
Matthias Bussonnier
Reformat some of the IPython docstrings.
r25884 Parameters
----------
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 cell: str
The code cell to asyncronify
wrapper_name: str
The name of the function to be used to wrap the passed `cell`. It is
advised to **not** use a python identifier in order to not pollute the
global namespace in which the function will be ran.
Matthias Bussonnier
Reformat some of the IPython docstrings.
r25884 Returns
-------
ModuleType:
A module object AST containing **one** function named `wrapper_name`.
The given code is wrapped in a async-def function, parsed into an AST, and
the resulting function definition AST is modified to return the last
expression.
The last expression or await node is moved into a return statement at the
end of the function, and removed from its original location. If the last
node is not Expr or Await nothing is done.
The function `__code__` will need to be later modified (by
``removed_co_newlocals``) in a subsequent step to not create new `locals()`
meaning that the local and global scope are the same, ie as if the body of
the function was at module level.
Lastly a call to `locals()` is made just before the last expression of the
function, or just after the last assignment or statement to make sure the
global dict is updated as python function work with a local fast cache which
is updated only on `local()` calls.
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 """
from ast import Expr, Await, Return
Matthias Bussonnier
draft compat 3.8
r25019 if sys.version_info >= (3,8):
return ast.parse(cell)
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 tree = ast.parse(_asyncify(cell))
function_def = tree.body[0]
function_def.name = wrapper_name
try_block = function_def.body[0]
lastexpr = try_block.body[-1]
if isinstance(lastexpr, (Expr, Await)):
try_block.body[-1] = Return(lastexpr.value)
ast.fix_missing_locations(tree)
return tree
#-----------------------------------------------------------------------------
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
#-----------------------------------------------------------------------------
Thomas Kluyver
Add way to mark classes & functions as undocumented.
r8793 @undoc
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
Thomas Kluyver
Add way to mark classes & functions as undocumented.
r8793 @undoc
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 def no_op(*a, **kw):
pass
Fernando Perez
Better handling of no-readline.
r2377
epatters
BUG: Don't use readline in the ZMQShell....
r4816
Thomas Kluyver
Clean up deprecated code: exceptions.Exception, new.instancemethod.
r3158 class SpaceInInput(Exception): pass
Ville M. Vainio
crlf -> lf
r1032
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():
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609 "DEPRECATED"
Thomas Kluyver
Tweak wording
r23448 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 DeprecationWarning, stacklevel=2)
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609 return 'Neutral'
Brian Granger
Make the default colors OS dependent.
r2319
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 class SeparateUnicode(Unicode):
Thomas Kluyver
Miscellaneous docs fixes
r13597 r"""A Unicode subclass to validate separate_in, separate_out, etc.
Brian Granger
Moved a few things back to InteractiveShell....
r2766
Thomas Kluyver
Miscellaneous docs fixes
r13597 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
Brian Granger
Moved a few things back to InteractiveShell....
r2766 """
def validate(self, obj, value):
if value == '0': value = ''
value = value.replace('\\n','\n')
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 return super(SeparateUnicode, self).validate(obj, value)
Brian Granger
Moved a few things back to InteractiveShell....
r2766
Brian Granger
Made InteractiveShell a SingletonConfigurable....
r3793
Mike McKerns
added undoc and made DummyMod doc more reflective of context
r12491 @undoc
Mike McKerns
moved DummyMod to proper namespace to enable pickling
r12470 class DummyMod(object):
Mike McKerns
added undoc and made DummyMod doc more reflective of context
r12491 """A dummy module used for IPython's interactive module when
a namespace must be assigned to the module's __dict__."""
gpotter2
Add __spec__ to DummyMod
r24388 __spec__ = None
Mike McKerns
moved DummyMod to proper namespace to enable pickling
r12470
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 class ExecutionInfo(object):
"""The arguments used for a call to :meth:`InteractiveShell.run_cell`
Fabio Niephaus
Use `backcall` and introduce `ExecutionRequest`
r23996
Stores information about what is going to happen.
"""
raw_cell = None
store_history = False
silent = False
shell_futures = True
def __init__(self, raw_cell, store_history, silent, shell_futures):
self.raw_cell = raw_cell
self.store_history = store_history
self.silent = silent
self.shell_futures = shell_futures
def __repr__(self):
name = self.__class__.__qualname__
raw_cell = ((self.raw_cell[:50] + '..')
if len(self.raw_cell) > 50 else self.raw_cell)
Ivan Gonzalez
Fix ExecutionInfo __repr__
r24083 return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\
(name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures)
Fabio Niephaus
Use `backcall` and introduce `ExecutionRequest`
r23996
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 class ExecutionResult(object):
"""The result of a call to :meth:`InteractiveShell.run_cell`
Stores information about what took place.
"""
execution_count = None
error_before_exec = None
error_in_exec = None
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 info = None
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 result = None
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 def __init__(self, info):
self.info = info
Fabio Niephaus
Use `backcall` and introduce `ExecutionRequest`
r23996
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 @property
def success(self):
return (self.error_before_exec is None) and (self.error_in_exec is None)
Tianhui Michael Li
ExecutionResult support `raise_error` method
r21413 def raise_error(self):
"""Reraises error if `success` is `False`, otherwise does nothing"""
if self.error_before_exec is not None:
raise self.error_before_exec
if self.error_in_exec is not None:
raise self.error_in_exec
Matthias Bussonnier
Keep a reference to last execution result on the shell....
r22449 def __repr__(self):
Paul Ivanov
remove sys_version for Python 3...
r22959 name = self.__class__.__qualname__
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\
(name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result))
Matthias Bussonnier
Keep a reference to last execution result on the shell....
r22449
Ville M. Vainio
crlf -> lf
r1032
Fernando Perez
First full decoupling of magics into a standalone object.
r6906 class InteractiveShell(SingletonConfigurable):
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
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Min RK
adopt traitlets 4.2 API...
r22340 ast_transformers = List([], help=
Thomas Kluyver
Add framework for AST transformations of input code.
r8220 """
A list of ast.NodeTransformer subclass instances, which will be applied
to user input before code is run.
"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Brian Granger
Started to move config docs to objects.
r3788
Min RK
adopt traitlets 4.2 API...
r22340 autocall = Enum((0,1,2), default_value=0, help=
Brian Granger
Started to move config docs to objects.
r3788 """
Make IPython automatically call any callable object even if you didn't
type explicit parentheses. For example, 'str 43' becomes 'str(43)'
automatically. The value can be '0' to disable the feature, '1' for
'smart' autocall, where it is not applied if there are no more
Brian Granger
Starting help in InteractiveShell.
r3787 arguments on the line, and '2' for 'full' autocall, where all callable
objects are automatically called (even if no arguments are present).
Brian Granger
Started to move config docs to objects.
r3788 """
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Matthias Bussonnier
Undeprecate autoindent...
r24498
Min RK
adopt traitlets 4.2 API...
r22340 autoindent = Bool(True, help=
Brian Granger
Started to move config docs to objects.
r3788 """
Brian Granger
Ongoing work on the config system....
r3789 Autoindent IPython code entered interactively.
Brian Granger
Started to move config docs to objects.
r3788 """
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Matthias Bussonnier
Add provisional warnings.
r22496
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 autoawait = Bool(True, help=
"""
Automatically run await statement in the top level repl.
"""
).tag(config=True)
loop_runner_map ={
Matthias Bussonnier
Add pseudo sync mode
r24481 'asyncio':(_asyncio_runner, True),
'curio':(_curio_runner, True),
'trio':(_trio_runner, True),
'sync': (_pseudo_sync_runner, False)
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 }
loop_runner = Any(default_value="IPython.core.interactiveshell._asyncio_runner",
allow_none=True,
help="""Select the loop runner that will be used to execute top-level asynchronous code"""
).tag(config=True)
@default('loop_runner')
def _default_loop_runner(self):
return import_item("IPython.core.interactiveshell._asyncio_runner")
@validate('loop_runner')
def _import_runner(self, proposal):
if isinstance(proposal.value, str):
if proposal.value in self.loop_runner_map:
Matthias Bussonnier
Add pseudo sync mode
r24481 runner, autoawait = self.loop_runner_map[proposal.value]
self.autoawait = autoawait
return runner
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 runner = import_item(proposal.value)
if not callable(runner):
raise ValueError('loop_runner must be callable')
return runner
if not callable(proposal.value):
raise ValueError('loop_runner must be callable')
return proposal.value
Min RK
adopt traitlets 4.2 API...
r22340 automagic = Bool(True, help=
Brian Granger
Started to move config docs to objects.
r3788 """
Enable magic commands to be called without the leading %.
"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Min RK
adopt traitlets 4.2 API...
r22340 banner1 = Unicode(default_banner,
MinRK
move banner to base InteractiveShell class
r16581 help="""The part of the banner to be printed before the profile"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
banner2 = Unicode('',
MinRK
move banner to base InteractiveShell class
r16581 help="""The part of the banner to be printed after the profile"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
MinRK
move banner to base InteractiveShell class
r16581
Min RK
adopt traitlets 4.2 API...
r22340 cache_size = Integer(1000, help=
Brian Granger
Ongoing work on the config system....
r3789 """
Set the size of the output cache. The default is 1000, you can
change it permanently in your config file. Setting it to 0 completely
Ming Zhang
fixed help message about history cache size
r23605 disables the caching system, and the minimum value accepted is 3 (if
you provide a value less than 3, it is reset to 0 and a warning is
Brian Granger
Ongoing work on the config system....
r3789 issued). This limit is defined because otherwise you'll spend more
time re-flushing a too small cache than working
"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
color_info = Bool(True, help=
Brian Granger
Ongoing work on the config system....
r3789 """
Use colors for displaying information about objects. Because this
information is passed through a pager (like 'less'), and some pagers
get confused with color codes, this capability can be turned off.
"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Matthias Bussonnier
Make everyone happy with a neutral colortheme by default.
r22609 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
default_value='Neutral',
Thomas Kluyver
Improve release notes and config details
r22611 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
debug = Bool(False).tag(config=True)
disable_failing_post_execute = Bool(False,
Takafumi Arakaki
Remove suspicious quotes in interactiveshell.py
r7363 help="Don't call post-execute functions that have failed in the past."
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Sylvain Corlay
allow_none=False by default for Type and Instance
r20940 display_formatter = Instance(DisplayFormatter, allow_none=True)
Sylvain Corlay
Remove unnecessary allow_none
r20941 displayhook_class = Type(DisplayHook)
display_pub_class = Type(DisplayPublisher)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329 compiler_class = Type(CachingCompiler)
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 sphinxify_docstring = Bool(False, help=
"""
Enables rich html representation of docstrings. (This requires the
docrepr module).
""").tag(config=True)
Matthias Bussonnier
Add provisional warnings.
r22496
@observe("sphinxify_docstring")
def _sphinxify_docstring_changed(self, change):
Matthias Bussonnier
use idiomatic Python
r22508 if change['new']:
Matthias Bussonnier
Add provisional warnings.
r22496 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 enable_html_pager = Bool(False, help=
"""
(Provisional API) enables html representation in mime bundles sent
to pagers.
""").tag(config=True)
Matthias Bussonnier
Add provisional warnings.
r22496
@observe("enable_html_pager")
def _enable_html_pager_changed(self, change):
Matthias Bussonnier
use idiomatic Python
r22508 if change['new']:
Matthias Bussonnier
Add provisional warnings.
r22496 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
MinRK
add data_pub messages...
r8102 data_pub_class = None
Brian Granger
Mostly final version of display data....
r3277
Min RK
adopt traitlets 4.2 API...
r22340 exit_now = Bool(False)
Sylvain Corlay
remove unnecessary allow_none=True
r20943 exiter = Instance(ExitAutocall)
Min RK
adopt traitlets 4.2 API...
r22340 @default('exiter')
Thomas Kluyver
Subclass exit autocallable for two process shells, with argument to keep kernel alive.
r3724 def _exiter_default(self):
return ExitAutocall(self)
Fernando Perez
Small fixes in response to code review for gh-163.
r3136 # Monotonically increasing execution counter
MinRK
add Integer traitlet...
r5344 execution_count = Integer(1)
MinRK
fix at least some command-line unicode options
r3464 filename = Unicode("<ipython console>")
Min RK
adopt traitlets 4.2 API...
r22340 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
Fernando Perez
Initialize input_splitter automatically via traitlets mechanism.
r3049
Thomas Kluyver
Start integrating new machinery for checking code completeness
r24166 # Used to transform cells before running them, and check whether code is complete
Thomas Kluyver
Start integrating new input transformation machinery into InteractiveShell
r24164 input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager',
())
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472
Thomas Kluyver
Start integrating new machinery for checking code completeness
r24166 @property
Thomas Kluyver
Simpler mechanism to extend input transformations
r24400 def input_transformers_cleanup(self):
return self.input_transformer_manager.cleanup_transforms
input_transformers_post = List([],
help="A list of string input transformers, to be applied after IPython's "
"own input transformations."
)
@property
Thomas Kluyver
Start integrating new machinery for checking code completeness
r24166 def input_splitter(self):
Matthias Bussonnier
add docstring, and emit deprecation warnings
r24406 """Make this available for backward compatibility (pre-7.0 release) with existing code.
Thomas Kluyver
Start integrating new machinery for checking code completeness
r24166
Matthias Bussonnier
add docstring, and emit deprecation warnings
r24406 For example, ipykernel ipykernel currently uses
`shell.input_splitter.check_complete`
Thomas Kluyver
Start integrating new machinery for checking code completeness
r24166 """
Matthias Bussonnier
add docstring, and emit deprecation warnings
r24406 from warnings import warn
warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.",
DeprecationWarning, stacklevel=2
)
Thomas Kluyver
Start integrating new machinery for checking code completeness
r24166 return self.input_transformer_manager
Min RK
adopt traitlets 4.2 API...
r22340 logstart = Bool(False, help=
Brian Granger
Ongoing work on the config system....
r3789 """
Matthias Bussonnier
cross reference logfile/logappend....
r20754 Start logging to the default log file in overwrite mode.
Use `logappend` to specify a log file to **append** logs to.
Brian Granger
Ongoing work on the config system....
r3789 """
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
logfile = Unicode('', help=
Brian Granger
Ongoing work on the config system....
r3789 """
The name of the logfile to use.
"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
logappend = Unicode('', help=
Brian Granger
Ongoing work on the config system....
r3789 """
Start logging to the given file in append mode.
Matthias Bussonnier
cross reference logfile/logappend....
r20754 Use `logfile` to specify a log file to **overwrite** logs to.
Brian Granger
Ongoing work on the config system....
r3789 """
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Brian Granger
More work on InteractiveShell and ipmaker. It works!
r2204 object_info_string_level = Enum((0,1,2), default_value=0,
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
pdb = Bool(False, help=
Brian Granger
Ongoing work on the config system....
r3789 """
Automatically call the pdb debugger after every exception.
"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
display_page = Bool(False,
Min RK
add InteractiveShell.display_page config...
r19387 help="""If True, anything that would be passed to the pager
will be displayed as regular output instead."""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987
MinRK
PromptManager fixes...
r5548 # deprecated prompt traits:
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Min RK
adopt traitlets 4.2 API...
r22340 prompt_in1 = Unicode('In [\\#]: ',
Min RK
undeprecate terminal.interactiveshell...
r22549 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
prompt_in2 = Unicode(' .\\D.: ',
Min RK
undeprecate terminal.interactiveshell...
r22549 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
prompt_out = Unicode('Out[\\#]: ',
Min RK
undeprecate terminal.interactiveshell...
r22549 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
prompts_pad_left = Bool(True,
Min RK
undeprecate terminal.interactiveshell...
r22549 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Min RK
adopt traitlets 4.2 API...
r22340 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
def _prompt_trait_changed(self, change):
name = change['name']
Srinivas Reddy Thatiparthy
Add stacklevel=2 to warn function
r23033 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
" and ignored since 5.0, set TerminalInteractiveShell.prompts"
" object directly.".format(name=name))
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
PromptManager fixes...
r5548 # protect against weird cases where self.config may not exist:
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472
Min RK
adopt traitlets 4.2 API...
r22340 show_rewritten_input = Bool(True,
Thomas Kluyver
Make rewrite prompt non-configurable.
r5555 help="Show rewritten input, e.g. for autocall."
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472
Min RK
adopt traitlets 4.2 API...
r22340 quiet = Bool(False).tag(config=True)
Brian Granger
Massive refactoring of of the core....
r2245
Min RK
adopt traitlets 4.2 API...
r22340 history_length = Integer(10000,
help='Total length of command history'
).tag(config=True)
Bernardo B. Marques
remove all trailling spaces
r4872
Min RK
adopt traitlets 4.2 API...
r22340 history_load_length = Integer(1000, help=
Antonio Russo
Add history_load_length configurable option
r21355 """
Antonio Russo
Simplify wording of documentation
r21357 The number of saved history entries to be loaded
Matthias Bussonnier
Remove readline related code. Pass 1
r22628 into the history buffer at startup.
Antonio Russo
Add history_load_length configurable option
r21355 """
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Antonio Russo
Add history_load_length configurable option
r21355
Matthias Bussonnier
Add new interactivity mode for ast....
r23730 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
Min RK
adopt traitlets 4.2 API...
r22340 default_value='last_expr',
Mike Hansen
Make ast_node_interactivity trait an Enum instead of Unicode
r7034 help="""
Matthias Bussonnier
Add new interactivity mode for ast....
r23730 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
which nodes should be run interactively (displaying output from expressions).
"""
Min RK
adopt traitlets 4.2 API...
r22340 ).tag(config=True)
Mike Hansen
Make default value of interactivity passed to run_ast_nodes configurable
r7033
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'
Min RK
adopt traitlets 4.2 API...
r22340 separate_in = SeparateUnicode('\n').tag(config=True)
separate_out = SeparateUnicode('').tag(config=True)
separate_out2 = SeparateUnicode('').tag(config=True)
wildcards_case_sensitive = Bool(True).tag(config=True)
Dan Allan
ENH: Add a 'Minimal' xmode option....
r24849 xmode = CaselessStrEnum(('Context', 'Plain', 'Verbose', 'Minimal'),
Matthias Bussonnier
Provide help String for `xmode`....
r23351 default_value='Context',
help="Switch modes for the IPython exception handlers."
).tag(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
Sylvain Corlay
allow_none=False by default for Type and Instance
r20940 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
MinRK
Terminal IPython working with newapp
r3963 @property
def profile(self):
if self.profile_dir is not None:
name = os.path.basename(self.profile_dir.location)
return name.replace('profile_','')
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987 # Private interface
Sylvain Corlay
remove unnecessary allow_none=True
r20943 _post_execute = Dict()
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987
Ryan May
Implement bare %pylab switching back to appropriate GUI.
r7965 # Tracks any GUI loop loaded for pylab
pylab_gui_select = None
Matthias Bussonnier
Keep a reference to last execution result on the shell....
r22449 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
Sudarshan Raghunathan
Store last execution result in the interactive shell instance so it can be seen by post execute handlers
r23803 last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True)
MinRK
use `parent=self` throughout IPython...
r11064 def __init__(self, ipython_dir=None, profile_dir=None,
Thomas Kluyver
Rename user_local_ns back to user_ns for simplicity.
r5453 user_module=None, user_ns=None,
MinRK
add manager and client as trait lets of ZMQInteractiveShell...
r10331 custom_exceptions=((), None), **kwargs):
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.
MinRK
use `parent=self` throughout IPython...
r11064 super(InteractiveShell, self).__init__(**kwargs)
Matthias Bussonnier
Remove a few usage of PromptManager in example...
r22447 if 'PromptManager' in self.config:
warn('As of IPython 5.0 `PromptManager` config will have no effect'
' and has been replaced by TerminalInteractiveShell.prompts_class')
MinRK
add %config magic for configuring IPython
r5225 self.configurables = [self]
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)
MinRK
Terminal IPython working with newapp
r3963 self.init_profile_dir(profile_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()
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 # Check if we're in a virtualenv, and set up sys.path.
self.init_virtualenv()
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.)
Thomas Kluyver
Rename user_local_ns back to user_ns for simplicity.
r5453 self.init_create_namespaces(user_module, user_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()
Bernardo B. Marques
remove all trailling spaces
r4872
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.
MinRK
Terminal IPython working with newapp
r3963 self.db = PickleShareDB(os.path.join(self.profile_dir.location, '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 self.init_syntax_highlighting()
self.init_hooks()
Thomas Kluyver
Rename callbacks -> events (mostly), fire -> trigger
r15605 self.init_events()
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.init_pushd_popd_magic()
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()
self.init_builtins()
Brian Granger
Reenabling output trapping in the kernel.
r2767
Brian Granger
More work on getting rid of ipmaker.
r2203 # The following was in post_config_initialization
self.init_inspector()
Matthias Bussonnier
Start refactoring handling of color....
r22911 self.raw_input_original = input
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 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()
MinRK
add data_pub messages...
r8102 self.init_data_pub()
Brian Granger
More work on getting rid of ipmaker.
r2203 self.init_displayhook()
self.init_magics()
Thomas Kluyver
Initial changes to make alias system use magics
r12595 self.init_alias()
Rui Pereira
Fix logging on interactive shell....
r7819 self.init_logstart()
Brian Granger
More work on getting rid of ipmaker.
r2203 self.init_pdb()
Brian Granger
First draft of refactored Component->Configurable.
r2731 self.init_extension_manager()
Brian Granger
Final attempt to fix init_io logic.
r2810 self.init_payload()
Matthias Bussonnier
register default deprecation warning filter....
r21391 self.init_deprecation_warnings()
Brian Granger
More work on getting rid of ipmaker.
r2203 self.hooks.late_startup_hook()
Thomas Kluyver
Use silly American spelling for initialised
r15612 self.events.trigger('shell_initialized', self)
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
Mark E. Haase
More work on Trio background loop...
r25432 # The trio runner is used for running Trio in the foreground thread. It
# is different from `_trio_runner(async_fn)` in `async_helpers.py`
# which calls `trio.run()` for every cell. This runner runs all cells
# inside a single Trio event loop. If used, it is set from
# `ipykernel.kernelapp`.
self.trio_runner = None
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 #-------------------------------------------------------------------------
Min RK
adopt traitlets 4.2 API...
r22340 @observe('ipython_dir')
def _ipython_dir_changed(self, change):
ensure_dir_exists(change['new'])
Brian Granger
Massive refactoring of of the core....
r2245
Brian Granger
More re-organization of InteractiveShell.
r2242 def set_autoindent(self,value=None):
Thomas Kluyver
Don't check for readline when setting autoindent...
r22170 """Set the autoindent flag.
Brian Granger
More re-organization of InteractiveShell.
r2242
If called with no arguments, it acts as a toggle."""
if value is None:
self.autoindent = not self.autoindent
else:
self.autoindent = value
Mark E. Haase
More work on Trio background loop...
r25432 def set_trio_runner(self, tr):
self.trio_runner = tr
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
Brian Granger
Minor work on how ipythondir is handled.
r2223 return
MinRK
Terminal IPython working with newapp
r3963 self.ipython_dir = get_ipython_dir()
Brian Granger
Cleaned up embedded shell and added cleanup method to InteractiveShell....
r2226
MinRK
Terminal IPython working with newapp
r3963 def init_profile_dir(self, profile_dir):
if profile_dir is not None:
self.profile_dir = profile_dir
return
Matthias Bussonnier
Mark initial frame as not hidden.
r26135 self.profile_dir = ProfileDir.create_profile_dir_by_name(
self.ipython_dir, "default"
)
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
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329 self.compile = self.compiler_class()
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 # Temporary files used for various purposes. Deleted at exit.
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 # The files here are stored with Path from Pathlib
Brian Granger
Massive, crazy refactoring of everything....
r2202 self.tempfiles = []
Matthias BUSSONNIER
avoid import of nearby temporary with %edit...
r14683 self.tempdirs = []
Brian Granger
Massive, crazy refactoring of everything....
r2202
# keep track of where we started running (mainly for crash post-mortem)
# This is not being used anywhere currently.
Srinivas Reddy Thatiparthy
rename py3compat.getcwd() -> os.getcwd()
r23045 self.starting_dir = os.getcwd()
Brian Granger
Massive, crazy refactoring of everything....
r2202
# Indentation management
self.indent_current_nsp = 0
Fernando Perez
Make post-execution happen at the cell instead of the block level....
r3732 # Dict to track post-execution functions that have been registered
self._post_execute = {}
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
Matthias Bussonnier
Start refactoring handling of color....
r22911
@observe('colors')
def init_syntax_highlighting(self, changes=None):
Brian Granger
More re-organization of InteractiveShell.
r2242 # Python source parser/formatter for syntax highlighting
Matthias Bussonnier
Pass parent to child for configuration to propagate
r22943 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
Matthias Bussonnier
Start refactoring handling of color....
r22911 self.pycolorize = lambda src: pyformat(src,'str')
Ville M. Vainio
crlf -> lf
r1032
Thomas Kluyver
Create method on parent class to get rid of warning...
r22607 def refresh_style(self):
# No-op here, used in subclass
pass
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_pushd_popd_magic(self):
# for pushd/popd management
MinRK
allow IPython to run without writable home dir...
r5384 self.home_dir = get_home_dir()
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:
Fernando Perez
First full decoupling of magics into a standalone object.
r6906 self.magic('logstart %s append' % self.logappend)
Brian Granger
Work on startup related things....
r2252 elif self.logfile:
Rui Pereira
Fix logging on interactive shell....
r7819 self.magic('logstart %s' % self.logfile)
Brian Granger
More re-organization of InteractiveShell.
r2242 elif self.logstart:
Fernando Perez
First full decoupling of magics into a standalone object.
r6906 self.magic('logstart')
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Matthias Bussonnier
use user-ns __name__
r21396 def init_deprecation_warnings(self):
Matthias Bussonnier
register default deprecation warning filter....
r21391 """
Matthias Bussonnier
do not show pending deprecation warnign
r21401 register default filter for deprecation warning.
Matthias Bussonnier
register default deprecation warning filter....
r21391
This will allow deprecation warning of function used interactively to show
warning to users, and still hide deprecation warning from libraries import.
"""
luciana
added filter warnings for older versions of python (<3.7)...
r24699 if sys.version_info < (3,7):
warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
Matthias Bussonnier
register default deprecation warning filter....
r21391
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_builtins(self):
Fernando Perez
Deprecate __IPYTHON__active for simply __IPYTHON__
r5492 # A single, static flag that we set to True. Its presence indicates
# that an IPython shell has been created, and we make no attempts at
# removing on exit or representing the existence of more than one
# IPython at a time.
builtin_mod.__dict__['__IPYTHON__'] = True
Matthias Bussonnier
Inject display into builtins...
r23711 builtin_mod.__dict__['display'] = display
Fernando Perez
Deprecate __IPYTHON__active for simply __IPYTHON__
r5492
Brian Granger
Adding support for HasTraits to take keyword arguments.
r2740 self.builtin_trap = BuiltinTrap(shell=self)
Ville M. Vainio
crlf -> lf
r1032
Antony Lee
Update object inspector colorscheme when needed.
r23820 @observe('colors')
def init_inspector(self, changes=None):
Brian Granger
More re-organization of InteractiveShell.
r2242 # Object inspector
self.inspector = oinspect.Inspector(oinspect.InspectColors,
PyColorize.ANSICodeColors,
michaelpacer
Fix help (pinfo2) view highlighting
r23425 self.colors,
Brian Granger
More re-organization of InteractiveShell.
r2242 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
Bernardo B. Marques
remove all trailling spaces
r4872 # *before* instantiating this class, because io holds onto
Fernando Perez
Fixed broken coloring on Windows....
r2974 # references to the underlying streams.
Min RK
fix some deprecations...
r22742 # io.std* are deprecated, but don't show our own deprecation warnings
# during initialization of the deprecated API.
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
io.stdout = io.IOStream(sys.stdout)
io.stderr = io.IOStream(sys.stderr)
Brian Granger
Changing how IPython.utils.io.Term is handled....
r2775
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_prompts(self):
Bradley M. Froehle
Define generic sys.ps{1,2,3}, for use by scripts....
r6749 # Set system prompts, so that scripts can decide if they are running
# interactively.
sys.ps1 = 'In : '
sys.ps2 = '...: '
sys.ps3 = 'Out: '
Brian Granger
Refactor of prompts and the displayhook....
r2781
Brian Granger
Display system is fully working now....
r3278 def init_display_formatter(self):
MinRK
use `parent=self` throughout IPython...
r11064 self.display_formatter = DisplayFormatter(parent=self)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.display_formatter)
Brian Granger
Display system is fully working now....
r3278
Brian Granger
Mostly final version of display data....
r3277 def init_display_pub(self):
Matthias Bussonnier
Provide hooks for arbitrary mimetypes handling....
r25164 self.display_pub = self.display_pub_class(parent=self, shell=self)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.display_pub)
Brian Granger
Mostly final version of display data....
r3277
MinRK
add data_pub messages...
r8102 def init_data_pub(self):
if not self.data_pub_class:
self.data_pub = None
return
MinRK
use `parent=self` throughout IPython...
r11064 self.data_pub = self.data_pub_class(parent=self)
MinRK
add data_pub messages...
r8102 self.configurables.append(self.data_pub)
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(
MinRK
use `parent=self` throughout IPython...
r11064 parent=self,
Brian Granger
Initial support in ipkernel for proper displayhook handling.
r2786 shell=self,
cache_size=self.cache_size,
)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.displayhook)
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
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 def init_virtualenv(self):
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014 """Add the current virtualenv to sys.path so the user can import modules from it.
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 This isn't perfect: it doesn't use the Python interpreter with which the
virtualenv was built, and it ignores the --no-site-packages option. A
warning will appear suggesting the user installs IPython in the
virtualenv, but for many cases, it probably works well enough.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 Adapted from code snippets online.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
"""
if 'VIRTUAL_ENV' not in os.environ:
# Not in a virtualenv
return
Matthias Bussonnier
reformat modified code
r26019 elif os.environ["VIRTUAL_ENV"] == "":
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014 warn("Virtual env path set to '', please check if this is intended.")
Thomas Kluyver
Add check for exe-in-virtualenv using os.path.samefile()...
r24106 return
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014 p = Path(sys.executable)
Matthias Bussonnier
reformat modified code
r26019 p_venv = Path(os.environ["VIRTUAL_ENV"])
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014
Thomas Kluyver
Add check for exe-in-virtualenv using os.path.samefile()...
r24106 # fallback venv detection:
MinRK
check every link when detecting virutalenv...
r13944 # stdlib venv may symlink sys.executable, so we can't use realpath.
# but others can symlink *to* the venv Python, so we can't just use sys.executable.
# So we just check every item in the symlink tree (generally <= 3)
paths = [p]
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014 while p.is_symlink():
p = Path(os.readlink(p))
paths.append(p.resolve())
Ignat Shining
Fix virtualenv warning for Cygwin...
r23579 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
Matthias Bussonnier
reformat modified code
r26019 if str(p_venv).startswith("\\cygdrive"):
Matthias Bussonnier
Update IPython/core/interactiveshell.py
r26018 p_venv = Path(str(p_venv)[11:])
Matthias Bussonnier
reformat modified code
r26019 elif len(str(p_venv)) >= 2 and str(p_venv)[1] == ":":
Matthias Bussonnier
Update IPython/core/interactiveshell.py
r26018 p_venv = Path(str(p_venv)[2:])
Ignat Shining
Fix virtualenv warning for Cygwin...
r23579
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014 if any(os.fspath(p_venv) in os.fspath(p) for p in paths):
# Our exe is inside or has access to the virtualenv, don't need to do anything.
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 return
Gabriel Simonetto
Introduce pathlib on init_virtualenv.
r26014
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 if sys.platform == "win32":
Bart Skowron
Refactor path-objets: os.path -> pathlib.Path
r26264 virtual_env = Path(os.environ["VIRTUAL_ENV"], "Lib", "site-packages")
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 else:
Bart Skowron
Refactor after darker checks
r26269 virtual_env_path = Path(
os.environ["VIRTUAL_ENV"], "lib", "python{}.{}", "site-packages"
)
Bart Skowron
Refactor virtualenv Python version prediction
r26267 p_ver = sys.version_info[:2]
Bart Skowron
Predict the Python version based on $VIRTUAL_ENV...
r26257
# Predict version from py[thon]-x.x in the $VIRTUAL_ENV
Bart Skowron
Shorten identifier name to pass darker checks
r26271 re_m = re.search(r"\bpy(?:thon)?([23])\.(\d+)\b", os.environ["VIRTUAL_ENV"])
if re_m:
predicted_path = Path(str(virtual_env_path).format(*re_m.groups()))
Bart Skowron
Refactor virtualenv Python version prediction
r26267 if predicted_path.exists():
Bart Skowron
Shorten identifier name to pass darker checks
r26271 p_ver = re_m.groups()
Bart Skowron
Predict the Python version based on $VIRTUAL_ENV...
r26257
Bart Skowron
Refactor virtualenv Python version prediction
r26268 virtual_env = str(virtual_env_path).format(*p_ver)
Bart Skowron
Predict the Python version based on $VIRTUAL_ENV...
r26257
Bart Skowron
Refactor after darker checks
r26260 warn(
"Attempting to work in a virtualenv. If you encounter problems, "
"please install IPython inside the virtualenv."
)
Thomas Kluyver
Add simple support for running inside a virtualenv.
r6085 import site
sys.path.insert(0, virtual_env)
site.addsitedir(virtual_env)
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
Thomas Kluyver
Rename user_local_ns back to user_ns for simplicity.
r5453 This has to be called after self.user_module is created.
Brian Granger
More re-organization of InteractiveShell.
r2242 """
Rémy Léone
Dict litteral
r21781 self._orig_sys_module_state = {'stdin': sys.stdin,
'stdout': sys.stdout,
'stderr': sys.stderr,
'excepthook': sys.excepthook}
Thomas Kluyver
Rename user_local_ns back to user_ns for simplicity.
r5453 self._orig_sys_modules_main_name = self.user_module.__name__
MinRK
InteractiveShell.restore_sys_module_state actually restores main...
r6829 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
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:
Srinivas Reddy Thatiparthy
Change functions,...
r23036 for k, v in self._orig_sys_module_state.items():
Brian Granger
More re-organization of InteractiveShell.
r2242 setattr(sys, k, v)
except AttributeError:
pass
# Reset what what done in self.init_sys_modules
MinRK
InteractiveShell.restore_sys_module_state actually restores main...
r6829 if self._orig_sys_modules_main_mod is not None:
sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
MinRK
move banner to base InteractiveShell class
r16581 # Things related to the banner
#-------------------------------------------------------------------------
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
make InteractiveShell.banner a property
r16595 @property
def banner(self):
banner = self.banner1
MinRK
move banner to base InteractiveShell class
r16581 if self.profile and self.profile != 'default':
MinRK
make InteractiveShell.banner a property
r16595 banner += '\nIPython profile: %s\n' % self.profile
MinRK
move banner to base InteractiveShell class
r16581 if self.banner2:
MinRK
make InteractiveShell.banner a property
r16595 banner += '\n' + self.banner2
return banner
MinRK
move banner to base InteractiveShell class
r16581
def show_banner(self, banner=None):
if banner is None:
banner = self.banner
Min RK
adopt traitlets 4.2 API...
r22340 sys.stdout.write(banner)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
move banner to base InteractiveShell class
r16581 #-------------------------------------------------------------------------
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
Thomas Kluyver
Deprecate some hooks in favour of callbacks
r15602 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Min RK
add InteractiveShell.display_page config...
r19387 if self.display_page:
self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Deprecate some hooks in favour of callbacks
r15602 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
_warn_deprecated=True):
Brian Granger
More re-organization of InteractiveShell.
r2242 """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
Bernardo B. Marques
remove all trailling spaces
r4872 adding your function to one of these hooks, you can modify IPython's
Brian Granger
More re-organization of InteractiveShell.
r2242 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.
Bernardo B. Marques
remove all trailling spaces
r4872
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
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
More re-organization of InteractiveShell.
r2242 dp = getattr(self.hooks, name, None)
if name not in IPython.core.hooks.__all__:
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print("Warning! Hook '%s' is not one of %s" % \
(name, IPython.core.hooks.__all__ ))
Thomas Kluyver
Deprecate some hooks in favour of callbacks
r15602
if _warn_deprecated and (name in IPython.core.hooks.deprecated):
alternative = IPython.core.hooks.deprecated[name]
Srinivas Reddy Thatiparthy
Add stacklevel=2 to warn function
r23033 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
Thomas Kluyver
Deprecate some hooks in favour of callbacks
r15602
Brian Granger
More re-organization of InteractiveShell.
r2242 if not dp:
dp = IPython.core.hooks.CommandChainDispatcher()
Bernardo B. Marques
remove all trailling spaces
r4872
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
Thomas Kluyver
Start of new callback system
r15597 #-------------------------------------------------------------------------
Thomas Kluyver
Update comment
r15665 # Things related to events
Thomas Kluyver
Start of new callback system
r15597 #-------------------------------------------------------------------------
Thomas Kluyver
Rename callbacks -> events (mostly), fire -> trigger
r15605 def init_events(self):
self.events = EventManager(self, available_events)
Thomas Kluyver
Start of new callback system
r15597
Nathaniel J. Smith
Reset the interactive namespace __warningregistry__ before executing code...
r18548 self.events.register("pre_execute", self._clear_warning_registry)
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987 def register_post_execute(self, func):
Thomas Kluyver
Update docstrings to refer to ip.events
r15611 """DEPRECATED: Use ip.events.register('post_run_cell', func)
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Start of new callback system
r15597 Register a function for calling after code execution.
Fernando Perez
Add support for simultaneous interactive and inline matplotlib plots....
r2987 """
Thomas Kluyver
Start of new callback system
r15597 warn("ip.register_post_execute is deprecated, use "
Srinivas Reddy Thatiparthy
Add stacklevel=2 to warn function
r23033 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
Thomas Kluyver
Rename pre/post_execute_explicit events to pre/post_run_cell
r15607 self.events.register('post_run_cell', func)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 def _clear_warning_registry(self):
Nathaniel J. Smith
Reset the interactive namespace __warningregistry__ before executing code...
r18548 # clear the warning registry, so that different code blocks with
# overlapping line number ranges don't cause spurious suppression of
# warnings (see gh-6611 for details)
if "__warningregistry__" in self.user_global_ns:
del self.user_global_ns["__warningregistry__"]
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to the "main" module
#-------------------------------------------------------------------------
Brian Granger
Massive, crazy refactoring of everything....
r2202
Thomas Kluyver
Replace FakeModule with ModuleType in InteractiveShell
r12562 def new_main_mod(self, filename, modname):
Brian Granger
More re-organization of InteractiveShell.
r2242 """Return a new 'main' module object for user code execution.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Update docstring of new_main_mod() method
r11275 ``filename`` should be the path of the script which will be run in the
module. Requests with the same filename will get the same module, with
its namespace cleared.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Replace FakeModule with ModuleType in InteractiveShell
r12562 ``modname`` should be the module name - normally either '__main__' or
the basename of the file without the extension.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Update docstring of new_main_mod() method
r11275 When scripts are executed via %run, we must keep a reference to their
Thomas Kluyver
Replace FakeModule with ModuleType in InteractiveShell
r12562 __main__ module around so that Python doesn't
Thomas Kluyver
Update docstring of new_main_mod() method
r11275 clear it, rendering references to module globals 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
Thomas Kluyver
Update docstring of new_main_mod() method
r11275 absolute path of the script. 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.
Brian Granger
More re-organization of InteractiveShell.
r2242 """
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 filename = os.path.abspath(filename)
try:
main_mod = self._main_mod_cache[filename]
except KeyError:
Thomas Kluyver
Cast module name to bytes for Py2 ModuleType constructor...
r17593 main_mod = self._main_mod_cache[filename] = types.ModuleType(
Srinivas Reddy Thatiparthy
rm cast_bytes_py2
r23666 modname,
Thomas Kluyver
Replace FakeModule with ModuleType in InteractiveShell
r12562 doc="Module created for script run in IPython")
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 else:
Thomas Kluyver
Replace FakeModule with ModuleType in InteractiveShell
r12562 main_mod.__dict__.clear()
main_mod.__name__ = modname
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Replace FakeModule with ModuleType in InteractiveShell
r12562 main_mod.__file__ = filename
# It seems pydoc (and perhaps others) needs any module instance to
# implement a __nonzero__ method
main_mod.__nonzero__ = lambda : True
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 return main_mod
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
--------
In [15]: import IPython
Ville M. Vainio
crlf -> lf
r1032
Thomas Kluyver
Replace FakeModule with ModuleType in InteractiveShell
r12562 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
Ville M. Vainio
crlf -> lf
r1032
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 In [17]: len(_ip._main_mod_cache) > 0
Brian Granger
More re-organization of InteractiveShell.
r2242 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
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 In [19]: len(_ip._main_mod_cache) == 0
Brian Granger
More re-organization of InteractiveShell.
r2242 Out[19]: True
"""
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 self._main_mod_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):
Bradley M. Froehle
Apply most 2to3 raise fixes....
r7843 raise ValueError('new call_pdb value must be boolean')
Brian Granger
More re-organization of InteractiveShell.
r2242
# 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):
Matthias Bussonnier
Remove Pydb integration as Pydb is unmaintained and not ion PyPI...
r22359 """Call the pdb debugger.
Brian Granger
More re-organization of InteractiveShell.
r2242
Keywords:
- force(False): by default, this routine checks the instance call_pdb
Thomas Kluyver
Improvements to docs formatting.
r12553 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.
Brian Granger
More re-organization of InteractiveShell.
r2242 """
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
Matthias Bussonnier
remove rest of readline, pass II
r22629 self.InteractiveTB.debugger(force=True)
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
#-------------------------------------------------------------------------
Thomas Kluyver
Simplify logic for deciding when to auto-detect local namespace and module.
r5669 default_user_namespaces = True
Brian Granger
More work on getting rid of ipmaker.
r2203
Thomas Kluyver
Rename user_local_ns back to user_ns for simplicity.
r5453 def init_create_namespaces(self, user_module=None, user_ns=None):
Brian Granger
More re-organization of InteractiveShell.
r2242 # 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:-(.
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 # These routines return a properly built module and dict as needed by
# the rest of the code, and can also be used by extension writers to
# generate properly initialized namespaces.
Thomas Kluyver
Simplify logic for deciding when to auto-detect local namespace and module.
r5669 if (user_ns is not None) or (user_module is not None):
self.default_user_namespaces = False
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
Brian Granger
More re-organization of InteractiveShell.
r2242
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 # A record of hidden variables we have added to the user namespace, so
# we can list later only variables defined in actual interactive use.
Thomas Kluyver
Implement a better check for hidden values for %who etc.
r12257 self.user_ns_hidden = {}
Brian Granger
More re-organization of InteractiveShell.
r2242
# 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
Thomas Ballinger
fix typos in comments
r21858 # so doctest and other tools work correctly), the Python module
Brian Granger
More re-organization of InteractiveShell.
r2242 # 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.
Bernardo B. Marques
remove all trailling spaces
r4872 #
Brian Granger
More re-organization of InteractiveShell.
r2242 # 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)>
Bernardo B. Marques
remove all trailling spaces
r4872 #
Brian Granger
More re-organization of InteractiveShell.
r2242 # 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
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 self._main_mod_cache = {}
Brian Granger
More re-organization of InteractiveShell.
r2242
# A table holding all the namespaces IPython deals with, so that
# introspection facilities can search easily.
Thomas Kluyver
Rename user_local_ns back to user_ns for simplicity.
r5453 self.ns_table = {'user_global':self.user_module.__dict__,
Thomas Kluyver
Fix wildcard search for new namespace model....
r5550 'user_local':self.user_ns,
Thomas Kluyver
Repair various failures in the test suite.
r4734 'builtin':builtin_mod.__dict__
Brian Granger
More re-organization of InteractiveShell.
r2242 }
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Start converting user namespace machinery to use a module.
r5452 @property
def user_global_ns(self):
return self.user_module.__dict__
Brian Granger
More work addressing review comments for Fernando's branch....
r2499
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 def prepare_user_module(self, user_module=None, user_ns=None):
"""Prepare the module and namespace in which user code will be run.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 When IPython is started normally, both parameters are None: a new module
is created automatically, and its __dict__ used as the namespace.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 If only user_module is provided, its __dict__ is used as the namespace.
If only user_ns is provided, a dummy module is created, and user_ns
becomes the global namespace. If both are provided (as they may be
when embedding), user_ns is the local namespace, and user_module
provides the global namespace.
Brian Granger
More work addressing review comments for Fernando's branch....
r2499
Parameters
----------
Thomas Kluyver
Start converting user namespace machinery to use a module.
r5452 user_module : module, optional
The current user module in which IPython is being run. If None,
a clean module will be created.
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 user_ns : dict, optional
A namespace in which to run interactive commands.
Brian Granger
More work addressing review comments for Fernando's branch....
r2499
Returns
-------
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 A tuple of user_module and user_ns, each properly initialised.
Brian Granger
More work addressing review comments for Fernando's branch....
r2499 """
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 if user_module is None and user_ns is not None:
user_ns.setdefault("__name__", "__main__")
user_module = DummyMod()
user_module.__dict__ = user_ns
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Start converting user namespace machinery to use a module.
r5452 if user_module is None:
user_module = types.ModuleType("__main__",
doc="Automatically created module for IPython interactive environment")
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Brian Granger
More work addressing review comments for Fernando's branch....
r2499 # 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
Thomas Kluyver
Clear up mistakes from rebasing.
r5460 user_module.__dict__.setdefault('__builtin__', builtin_mod)
user_module.__dict__.setdefault('__builtins__', builtin_mod)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 if user_ns is None:
user_ns = user_module.__dict__
Brian Granger
More work addressing review comments for Fernando's branch....
r2499
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 return user_module, user_ns
Brian Granger
More work addressing review comments for Fernando's branch....
r2499
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.
Thomas Kluyver
Start converting user namespace machinery to use a module.
r5452 main_name = self.user_module.__name__
sys.modules[main_name] = self.user_module
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
Craig Citro
Typo fix: `therm` -> `them`
r24222 them.
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 # 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
Thomas Ballinger
fix typos in comments
r21858 # session (probably nothing, so they really only see their own stuff)
Fernando Perez
Ensure that __builtin__ is always available and compute prompts from it....
r2485
# 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.
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Ensure that __builtin__ is always available and compute prompts from it....
r2485 # For more details:
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
Srinivas Reddy Thatiparthy
remove dict() function call and replace it with dict literal - {}
r23231 ns = {}
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
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
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
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Remove capitalised exit forms.
r3725 ns['exit'] = self.exiter
ns['quit'] = self.exiter
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.
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Clean up output of %who
r2472 # Finally, update the real user's namespace
Thomas Kluyver
Rename user_local_ns back to user_ns for simplicity.
r5453 self.user_ns.update(ns)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Minor improvements to how namespaces are handled.
r5458 @property
def all_ns_refs(self):
"""Get a list of references to all the namespace dictionaries in which
IPython might store a user-created object.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Minor improvements to how namespaces are handled.
r5458 Note that this does not include the displayhook, which also caches
objects from the output."""
Thomas Kluyver
Tweaks to interactiveshell for user_ns_hidden as dict
r12259 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
Thomas Kluyver
Simplify caching of modules from %run-ing scripts....
r11207 [m.__dict__ for m in self._main_mod_cache.values()]
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Matthias Bussonnier
Mare reset -f more agressive and cull sys.modules;...
r26229 def reset(self, new_session=True, aggressive=False):
Thomas Kluyver
Shell's reset method clears namespace from last %run command.
r3762 """Clear all internal namespaces, and attempt to release references to
user objects.
Bernardo B. Marques
remove all trailling spaces
r4872
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)
Thomas Kluyver
%reset doesn't reset prompt number.
r3703 # Reset counter used to index all histories
if new_session:
self.execution_count = 1
Bernardo B. Marques
remove all trailling spaces
r4872
Sudarshan Raghunathan
Fix reset in interactiveshell to clear execution result for both soft and hard resets and small formatting changes based on PR feedback
r23806 # Reset last execution result
self.last_execution_succeeded = True
self.last_execution_result = None
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Implement hard reset with '%reset -h' call....
r3521 # Flush cached output items
MinRK
don't flush displayhook if caching is disabled
r3810 if self.displayhook.do_full_cache:
self.displayhook.flush()
Bernardo B. Marques
remove all trailling spaces
r4872
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.
Thomas Kluyver
Use user_ns as global namespace if it is passed without user_module, and add test for pickling interactively defined objects....
r5456 if self.user_ns is not self.user_global_ns:
self.user_ns.clear()
ns = self.user_global_ns
drop_keys = set(ns.keys())
drop_keys.discard('__builtin__')
drop_keys.discard('__builtins__')
drop_keys.discard('__name__')
for k in drop_keys:
del ns[k]
Matthias Bussonnier
use explicit checking instead of tr/except
r25152
Thomas Kluyver
Minor improvements to how namespaces are handled.
r5458 self.user_ns_hidden.clear()
Matthias Bussonnier
use explicit checking instead of tr/except
r25152
Thomas Kluyver
Restore Fernando's fix for the __del__ methods on exit bug.
r3157 # Restore the user namespaces to minimal usability
Brian Granger
More re-organization of InteractiveShell.
r2242 self.init_user_ns()
Matthias Bussonnier
Mare reset -f more agressive and cull sys.modules;...
r26229 if aggressive and not hasattr(self, "_sys_modules_keys"):
print("Cannot restore sys.module, no snapshot")
elif aggressive:
print("culling sys module...")
current_keys = set(sys.modules.keys())
for k in current_keys - self._sys_modules_keys:
if k.startswith("multiprocessing"):
continue
del sys.modules[k]
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()
Bernardo B. Marques
remove all trailling spaces
r4872
Jesse Widner
Adds posix aliases after a %reset....
r24889 # Now define aliases that only make sense on the terminal, because they
# need direct access to the console in a way that we can't emulate in
# GUI or web frontend
if os.name == 'posix':
for cmd in ('clear', 'more', 'less', 'man'):
Matthias Bussonnier
use explicit checking instead of tr/except
r25152 if cmd not in self.magics_manager.magics['line']:
juanis2112
Fixing duplicated definition of magic aliases after reset
r25125 self.alias_manager.soft_define_alias(cmd, cmd)
Jesse Widner
Adds posix aliases after a %reset....
r24889
Thomas Kluyver
Implement hard reset with '%reset -h' call....
r3521 # Flush the private list of module references kept for script
# execution protection
self.clear_main_mod_cache()
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Implement deletion mechanism to remove references held by IPython behind the scenes. Exposed to the user as %xdel.
r3823 def del_var(self, varname, by_name=False):
"""Delete a variable from the various namespaces, so that, as
far as possible, we're not keeping any hidden references to it.
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Implement deletion mechanism to remove references held by IPython behind the scenes. Exposed to the user as %xdel.
r3823 Parameters
----------
varname : str
The name of the variable to delete.
by_name : bool
If True, delete variables with the given name in each
namespace. If False (default), find the variable in the user
namespace, and delete references to it.
"""
if varname in ('__builtin__', '__builtins__'):
raise ValueError("Refusing to delete %s" % varname)
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Minor improvements to how namespaces are handled.
r5458 ns_refs = self.all_ns_refs
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Implement deletion mechanism to remove references held by IPython behind the scenes. Exposed to the user as %xdel.
r3823 if by_name: # Delete by name
for ns in ns_refs:
try:
del ns[varname]
except KeyError:
pass
else: # Delete by object
try:
obj = self.user_ns[varname]
Ram Rachum
Fix exception causes in 7 modules
r25827 except KeyError as e:
raise NameError("name '%s' is not defined" % varname) from e
Thomas Kluyver
Implement deletion mechanism to remove references held by IPython behind the scenes. Exposed to the user as %xdel.
r3823 # Also check in output history
ns_refs.append(self.history_manager.output_hist)
for ns in ns_refs:
Srinivas Reddy Thatiparthy
Change functions,...
r23036 to_delete = [n for n, o in ns.items() if o is obj]
Thomas Kluyver
Implement deletion mechanism to remove references held by IPython behind the scenes. Exposed to the user as %xdel.
r3823 for name in to_delete:
del ns[name]
Bernardo B. Marques
remove all trailling spaces
r4872
Sudarshan Raghunathan
Fix del_var in interactive shell to clear the last execution result
r23805 # Ensure it is removed from the last execution result
if self.last_execution_result.result is obj:
self.last_execution_result = None
Thomas Kluyver
Implement deletion mechanism to remove references held by IPython behind the scenes. Exposed to the user as %xdel.
r3823 # displayhook keeps extra references, but not in a dictionary
for name in ('_', '__', '___'):
if getattr(self.displayhook, name) is obj:
setattr(self.displayhook, name, None)
Bernardo B. Marques
remove all trailling spaces
r4872
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)
Ram Rachum
Fix exception causes in 7 modules
r25827 except TypeError as e:
raise TypeError('regex must be a string or compiled pattern') from e
Brad Reisfeld
New magic: %reset_selective....
r2577 # Search for keys in each namespace that match the given regex
# If a match is found, delete the key/value pair.
Thomas Kluyver
Minor improvements to how namespaces are handled.
r5458 for ns in self.all_ns_refs:
Brad Reisfeld
New magic: %reset_selective....
r2577 for var in ns:
if m.search(var):
Bernardo B. Marques
remove all trailling spaces
r4872 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
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 elif isinstance(variables, (str, list, tuple)):
if isinstance(variables, str):
Brian Granger
More re-organization of InteractiveShell.
r2242 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:
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('Could not get variable %s from %s' %
Brian Granger
More re-organization of InteractiveShell.
r2242 (name,cf.f_code.co_name))
else:
raise ValueError('variables must be a dict/str/list/tuple')
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
More re-organization of InteractiveShell.
r2242 # Propagate variables to user namespace
self.user_ns.update(vdict)
# And configure interactive visibility
Thomas Kluyver
Start converting user namespace machinery to use a module.
r5452 user_ns_hidden = self.user_ns_hidden
Brian Granger
More re-organization of InteractiveShell.
r2242 if interactive:
Thomas Kluyver
Implement a better check for hidden values for %who etc.
r12257 for name in vdict:
user_ns_hidden.pop(name, None)
Brian Granger
More re-organization of InteractiveShell.
r2242 else:
Thomas Kluyver
Minor improvements to how namespaces are handled.
r5458 user_ns_hidden.update(vdict)
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472
Thomas Kluyver
Add drop_by_id method to shell, to remove variables added by extensions.
r5068 def drop_by_id(self, variables):
"""Remove a dict of variables from the user namespace, if they are the
same as the values in the dictionary.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Add drop_by_id method to shell, to remove variables added by extensions.
r5068 This is intended for use by extensions: variables that they've added can
be taken back out if they are unloaded, without removing any that the
user has overwritten.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
Thomas Kluyver
Add drop_by_id method to shell, to remove variables added by extensions.
r5068 Parameters
----------
variables : dict
Matthias Bussonnier
DOC: more docstrign formatting
r25907 A dictionary mapping object names (as strings) to the objects.
Thomas Kluyver
Add drop_by_id method to shell, to remove variables added by extensions.
r5068 """
Srinivas Reddy Thatiparthy
Change functions,...
r23036 for name, obj in variables.items():
Thomas Kluyver
Add drop_by_id method to shell, to remove variables added by extensions.
r5068 if name in self.user_ns and self.user_ns[name] is obj:
del self.user_ns[name]
Thomas Kluyver
Tweaks to interactiveshell for user_ns_hidden as dict
r12259 self.user_ns_hidden.pop(name, None)
Brian Granger
More re-organization of InteractiveShell.
r2242
#-------------------------------------------------------------------------
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.
"""
Thomas Kluyver
Start using py3compat module.
r4731 oname = oname.strip()
MinRK
oinfo finds cell magics with same name as line magics...
r7435 if not oname.startswith(ESC_MAGIC) and \
Matthias Bussonnier
Cleanup oinspect...
r23592 not oname.startswith(ESC_MAGIC2) and \
not all(a.isidentifier() for a in oname.split(".")):
Srinivas Reddy Thatiparthy
remove dict() function call and replace it with dict literal - {}
r23231 return {'found': False}
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 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),
Thomas Kluyver
Remove extraneous internal_ns and ns_refs_table variables.
r5454 ('Interactive (global)', self.user_global_ns),
Thomas Kluyver
Repair various failures in the test suite.
r4734 ('Python builtin', builtin_mod.__dict__),
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 ]
Matthias Bussonnier
Cleanup oinspect...
r23592 ismagic = False
isalias = False
found = False
ospace = None
parent = None
obj = None
Fernando Perez
Move object inspection machinery out of the magics code....
r2927
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 # 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:
immerrr
core.interactiveshell.ofind: don't evaluate property.fget (it may raise)
r17024 for idx, part in enumerate(oname_rest):
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 try:
parent = obj
immerrr
core.interactiveshell.ofind: don't evaluate property.fget (it may raise)
r17024 # The last part is looked up in a special way to avoid
# descriptor invocation as it may raise or have side
# effects.
if idx == len(oname_rest) - 1:
obj = self._getattr_property(obj, part)
else:
obj = getattr(obj, part)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 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
break # namespace loop
# Try to see if it's magic
if not found:
MinRK
oinfo finds cell magics with same name as line magics...
r7435 obj = None
MinRK
define ESC_FOO consts only in inputsplitter...
r7437 if oname.startswith(ESC_MAGIC2):
oname = oname.lstrip(ESC_MAGIC2)
Fernando Perez
Add support for finding cell magics with ?/??....
r6997 obj = self.find_cell_magic(oname)
MinRK
oinfo finds cell magics with same name as line magics...
r7435 elif oname.startswith(ESC_MAGIC):
oname = oname.lstrip(ESC_MAGIC)
obj = self.find_line_magic(oname)
else:
# search without prefix, so run? will find %run?
obj = self.find_line_magic(oname)
if obj is None:
obj = self.find_cell_magic(oname)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 if obj is not None:
found = True
ospace = 'IPython internal'
ismagic = True
Thomas Kluyver
Reorder info fields to put most useful first...
r20568 isalias = isinstance(obj, Alias)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927
Matthias Bussonnier
Cleaning of Oinspect....
r23673 # Last try: special-case some literals like '', [], {}, etc:
if not found and oname_head in ["''",'""','[]','{}','()']:
obj = eval(oname_head)
found = True
ospace = 'Interactive'
return {
'obj':obj,
'found':found,
'parent':parent,
'ismagic':ismagic,
'isalias':isalias,
'namespace':ospace
}
Fernando Perez
Move object inspection machinery out of the magics code....
r2927
immerrr
core.interactiveshell.ofind: don't evaluate property.fget (it may raise)
r17024 @staticmethod
def _getattr_property(obj, attrname):
"""Property-aware getattr to use in object finding.
If attrname represents a property, return it unevaluated (in case it has
side effects or raises an error.
"""
if not isinstance(obj, type):
try:
# `getattr(type(obj), attrname)` is not guaranteed to return
# `obj`, but does so for property:
#
# property.__get__(self, None, cls) -> self
#
# The universal alternative is to traverse the mro manually
# searching for attrname in class dicts.
attr = getattr(type(obj), attrname)
except AttributeError:
pass
else:
# This relies on the fact that data descriptors (with both
# __get__ & __set__ magic methods) take precedence over
# instance-level attributes:
#
# class A(object):
# @property
# def foobar(self): return 123
# a = A()
# a.__dict__['foobar'] = 345
# a.foobar # == 123
#
# So, a property may be returned right away.
if isinstance(attr, property):
return attr
# Nothing helped, fall back.
return getattr(obj, attrname)
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929
def _object_find(self, oname, namespaces=None):
"""Find an object and return a struct with info about it."""
immerrr
core.interactiveshell.ofind: don't evaluate property.fget (it may raise)
r17024 return Struct(self._ofind(oname, namespaces))
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 def _inspect(self, meth, oname, namespaces=None, **kw):
"""Generic interface to the inspector system.
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 This function is meant to be called by pdef, pdoc & friends.
"""
Bradley M. Froehle
Pass along namespaces, so that we can find objects when calling in ipdb.
r7905 info = self._object_find(oname, namespaces)
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 docformat = sphinxify if self.sphinxify_docstring else None
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929 if info.found:
pmethod = getattr(self.inspector, meth)
Sylvain Corlay
Add provisial config attribute to disable html display by default
r22472 # TODO: only apply format_screen to the plain/text repr of the mime
# bundle.
Sylvain Corlay
Sphinxify docstrings
r22459 formatter = format_screen if info.ismagic else docformat
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':
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329 pmethod(
info.obj,
oname,
formatter,
info,
enable_html_pager=self.enable_html_pager,
**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:
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('Object `%s` not found.' % oname)
Fernando Perez
Move object inspection machinery out of the magics code....
r2927 return 'not found' # so callers can take other action
Fernando Perez
Continue restructuring info system, move some standalone code to utils.
r2929
MinRK
add detail_level to object_info requests...
r6556 def object_inspect(self, oname, detail_level=0):
MinRK
add object_inspect_text...
r16579 """Get object info about oname"""
David Warde-Farley
fix issue 337 with incorrect calltips being generated for magics
r3685 with self.builtin_trap:
info = self._object_find(oname)
if info.found:
MinRK
add detail_level to object_info requests...
r6556 return self.inspector.info(info.obj, oname, info=info,
detail_level=detail_level
)
David Warde-Farley
fix issue 337 with incorrect calltips being generated for magics
r3685 else:
return oinspect.object_info(name=oname, found=False)
Robert Kern
BUG: mk_object_info -> object_info
r3053
MinRK
add object_inspect_text...
r16579 def object_inspect_text(self, oname, detail_level=0):
"""Get object info as formatted text"""
Min RK
InteractiveShell.object_inspect_text must return text...
r22504 return self.object_inspect_mime(oname, detail_level)['text/plain']
def object_inspect_mime(self, oname, detail_level=0):
"""Get object info as a mimebundle of formatted representations.
A mimebundle is a dictionary, keyed by mime-type.
It must always have the key `'text/plain'`.
"""
MinRK
add object_inspect_text...
r16579 with self.builtin_trap:
info = self._object_find(oname)
if info.found:
Sylvain Corlay
pinfo magic return mime bundle
r22460 return self.inspector._get_info(info.obj, oname, info=info,
MinRK
add object_inspect_text...
r16579 detail_level=detail_level
)
else:
raise KeyError(oname)
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."""
MinRK
use `parent=self` throughout IPython...
r11064 self.history_manager = HistoryManager(shell=self, parent=self)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.history_manager)
Brian Granger
More re-organization of InteractiveShell.
r2242
#-------------------------------------------------------------------------
# Things related to exception handling and tracebacks (not debugging)
#-------------------------------------------------------------------------
Ville M. Vainio
crlf -> lf
r1032
Thomas Kluyver
Create separate class for debugger using prompt_toolkit
r22391 debugger_cls = Pdb
Brian Granger
More re-organization of InteractiveShell.
r2242 def init_traceback_handlers(self, custom_exceptions):
# Syntax error handler.
Matthias Bussonnier
Pass parent to child for configuration to propagate
r22943 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
Bernardo B. Marques
remove all trailling spaces
r4872
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
Dan Allan
ENH: Add a 'Minimal' xmode option....
r24849 # internal code. Valid modes: ['Plain','Context','Verbose','Minimal']
Brian Granger
More re-organization of InteractiveShell.
r2242 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
color_scheme='NoColor',
Fernando Perez
Complete implementation of interactive traceback support....
r3175 tb_offset = 1,
Thomas Kluyver
Create separate class for debugger using prompt_toolkit
r22391 check_cache=check_linecache_ipython,
Matthias Bussonnier
Pass parent to child for configuration to propagate
r22943 debugger_cls=self.debugger_cls, parent=self)
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):
Matthias Bussonnier
Use generic showtraceback() instead of showsyntaxerror()...
r22431 """set_custom_exc(exc_tuple, handler)
Ville M. Vainio
crlf -> lf
r1032
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
update set_custom_exc docstring with new-style Parameters section
r5000 run_code() method).
Ville M. Vainio
crlf -> lf
r1032
MinRK
update set_custom_exc docstring with new-style Parameters section
r5000 Parameters
----------
exc_tuple : tuple of exception classes
A *tuple* of exception classes, for which to call the defined
handler. 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::
Ville M. Vainio
crlf -> lf
r1032
MinRK
update set_custom_exc docstring with new-style Parameters section
r5000 exc_tuple == (MyCustomException,)
Ville M. Vainio
crlf -> lf
r1032
MinRK
update set_custom_exc docstring with new-style Parameters section
r5000 handler : callable
handler must have the following signature::
Ville M. Vainio
crlf -> lf
r1032
MinRK
update set_custom_exc docstring with new-style Parameters section
r5000 def my_handler(self, etype, value, tb, tb_offset=None):
...
return structured_traceback
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838
MinRK
update set_custom_exc docstring with new-style Parameters section
r5000 Your handler must return a structured traceback (a list of strings),
or None.
Ville M. Vainio
crlf -> lf
r1032
MinRK
update set_custom_exc docstring with new-style Parameters section
r5000 This will be made into an instance method (via types.MethodType)
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.
Brian Granger
Added compatibility layer for Shell/ipapi/iplib....
r2061
MinRK
update set_custom_exc docstring with new-style Parameters section
r5000 To protect IPython from crashes, if your handler ever raises an
exception or returns an invalid result, it will be immediately
disabled.
Ville M. Vainio
crlf -> lf
r1032
Matthias Bussonnier
Fix docstring syntax to be properly parsed by numpydoc.
r26478 Notes
-----
Ville M. Vainio
crlf -> lf
r1032 WARNING: by putting in your own exception handler into IPython's main
execution loop, you run a very good chance of nasty crashes. This
Matthias Bussonnier
Fix docstring syntax to be properly parsed by numpydoc.
r26478 facility should only be used if you really know what you are doing.
"""
Matthias Bussonnier
Do not rely on assert to catch errors....
r23593 if not isinstance(exc_tuple, tuple):
raise TypeError("The custom exceptions must be given as a tuple.")
Ville M. Vainio
crlf -> lf
r1032
Matthias Bussonnier
Use generic showtraceback() instead of showsyntaxerror()...
r22431 def dummy_handler(self, etype, value, tb, tb_offset=None):
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print('*** Simple custom exception handler ***')
Matthias Bussonnier
Do not rely on assert to catch errors....
r23593 print('Exception type :', etype)
print('Exception value:', value)
print('Traceback :', tb)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
protect against bad return type of CustomTB...
r4999 def validate_stb(stb):
"""validate structured traceback return type
Matthias Bussonnier
DOC: more docstrign formatting
r25907
MinRK
protect against bad return type of CustomTB...
r4999 return type of CustomTB *should* be a list of strings, but allow
single strings or None, which are harmless.
Matthias Bussonnier
DOC: more docstrign formatting
r25907
MinRK
protect against bad return type of CustomTB...
r4999 This function will *always* return a list of strings,
and will raise a TypeError if stb is inappropriate.
"""
msg = "CustomTB must return list of strings, not %r" % stb
if stb is None:
return []
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 elif isinstance(stb, str):
MinRK
protect against bad return type of CustomTB...
r4999 return [stb]
elif not isinstance(stb, list):
raise TypeError(msg)
# it's a list
for line in stb:
# check every element
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 if not isinstance(line, str):
MinRK
protect against bad return type of CustomTB...
r4999 raise TypeError(msg)
return stb
Brian Granger
Added compatibility layer for Shell/ipapi/iplib....
r2061
MinRK
protect IPython from bad custom exception handlers...
r4991 if handler is None:
wrapped = dummy_handler
else:
def wrapped(self,etype,value,tb,tb_offset=None):
MinRK
protect against bad return type of CustomTB...
r4999 """wrap CustomTB handler, to protect IPython from user code
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
protect against bad return type of CustomTB...
r4999 This makes it harder (but not impossible) for custom exception
handlers to crash IPython.
"""
MinRK
protect IPython from bad custom exception handlers...
r4991 try:
MinRK
protect against bad return type of CustomTB...
r4999 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
return validate_stb(stb)
MinRK
protect IPython from bad custom exception handlers...
r4991 except:
# clear custom handler immediately
self.set_custom_exc((), None)
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 print("Custom TB Handler failed, unregistering", file=sys.stderr)
MinRK
protect IPython from bad custom exception handlers...
r4991 # show the exception in handler first
stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 print(self.InteractiveTB.stb2text(stb))
print("The original exception:")
MinRK
protect against bad return type of CustomTB...
r4999 stb = self.InteractiveTB.structured_traceback(
(etype,value,tb), tb_offset=tb_offset
)
return stb
MinRK
protect IPython from bad custom exception handlers...
r4991
self.CustomTB = types.MethodType(wrapped,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):
Matthias Bussonnier
Fix indentation not multiple of 4 and double import
r23454 """One more defense for GUI apps that call sys.excepthook.
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
Rodolfo Carvalho
Fix typo in excepthook docstring
r26610 which expects to catch all of the program exceptions with a try:
Matthias Bussonnier
Fix indentation not multiple of 4 and double import
r23454 except: statement.
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.
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
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 def _get_exc_info(self, exc_tuple=None):
"""get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 Ensures sys.last_type,value,traceback hold the exc_info we found,
from whichever source.
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 raises ValueError if none of these contain any information
"""
if exc_tuple is None:
etype, value, tb = sys.exc_info()
else:
etype, value, tb = exc_tuple
if etype is None:
if hasattr(sys, 'last_type'):
etype, value, tb = sys.last_type, sys.last_value, \
sys.last_traceback
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 if etype is None:
raise ValueError("No exception to find")
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 # Now store the exception info in sys.last_type etc.
# 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
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 return etype, value, tb
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add InteractiveShell.show_usage_error...
r11466 def show_usage_error(self, exc):
"""Show a short message for UsageErrors
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add InteractiveShell.show_usage_error...
r11466 These are special exceptions that shouldn't show a traceback.
"""
Thomas Kluyver
Show UsageError exception immediately...
r22189 print("UsageError: %s" % exc, file=sys.stderr)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Jeroen Demeyer
Print exception instead of "KeyboardInterrupt"...
r19114 def get_exception_only(self, exc_tuple=None):
"""
Return as a string (ending with a newline) the exception that
just occurred, without any traceback.
"""
etype, value, tb = self._get_exc_info(exc_tuple)
msg = traceback.format_exception_only(etype, value)
return ''.join(msg)
Justyna Ilczuk
i1673 implementation of py3 proper error handling...
r17157 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611 exception_only=False, running_compiled_code=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."""
Bernardo B. Marques
remove all trailling spaces
r4872
Ville M. Vainio
crlf -> lf
r1032 try:
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 try:
etype, value, tb = self._get_exc_info(exc_tuple)
except ValueError:
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 print('No traceback available to show.', file=sys.stderr)
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 return
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611
Thomas Kluyver
Make IndentationErrors display like other SyntaxErrors...
r8417 if issubclass(etype, 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
Thomas Kluyver
Fix for looking up print function in Python 3.
r4741 # line, there may be SyntaxError cases with imported code.
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611 self.showsyntaxerror(filename, running_compiled_code)
Brian Granger
More re-organization of InteractiveShell.
r2242 elif etype is UsageError:
MinRK
add InteractiveShell.show_usage_error...
r11466 self.show_usage_error(value)
Brian Granger
More re-organization of InteractiveShell.
r2242 else:
Thomas Kluyver
Remove check for custom_exceptions from showtraceback; it's checked in run_code.
r7109 if exception_only:
stb = ['An exception has occurred, use %tb to see '
'the full traceback.\n']
stb.extend(self.InteractiveTB.get_exception_only(etype,
value))
Brian Granger
More re-organization of InteractiveShell.
r2242 else:
Thomas Kluyver
Allow custom tracebacks for exception types with a _render_traceback_() method.
r8082 try:
# Exception classes can customise their traceback - we
# use this in IPython.parallel for exceptions occurring
# in the engines. This should return a list of strings.
stb = value._render_traceback_()
except Exception:
stb = self.InteractiveTB.structured_traceback(etype,
Thomas Kluyver
Remove check for custom_exceptions from showtraceback; it's checked in run_code.
r7109 value, tb, tb_offset=tb_offset)
self._showtraceback(etype, value, stb)
if self.call_pdb:
# drop into debugger
self.debugger(force=True)
return
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838
# Actually show the traceback
self._showtraceback(etype, value, stb)
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
More re-organization of InteractiveShell.
r2242 except KeyboardInterrupt:
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 print('\n' + self.get_exception_only(), file=sys.stderr)
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838
takuya fujiwara
Fix issue #11615
r26272 def _showtraceback(self, etype, evalue, stb: str):
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 """Actually show a traceback.
Subclasses may override this method to put the traceback on a different
place, like a side channel.
"""
takuya fujiwara
Fix issue #11615
r26272 val = self.InteractiveTB.stb2text(stb)
try:
takuya fujiwara
Fix lint warnings
r26276 print(val)
takuya fujiwara
Fix issue #11615
r26272 except UnicodeEncodeError:
takuya fujiwara
Fix lint warnings
r26277 print(val.encode("utf-8", "backslashreplace").decode())
Brian Granger
Continuing a massive refactor of everything.
r2205
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611 def showsyntaxerror(self, filename=None, running_compiled_code=False):
Brian Granger
More re-organization of InteractiveShell.
r2242 """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).
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611
If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
longer stack trace will be displayed.
"""
MinRK
move exc_info extraction to Shell._get_exc_info...
r6109 etype, value, last_traceback = self._get_exc_info()
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Make IndentationErrors display like other SyntaxErrors...
r8417 if filename and issubclass(etype, SyntaxError):
Brian Granger
More re-organization of InteractiveShell.
r2242 try:
Thomas Kluyver
Fix display of SyntaxError in Python 3....
r5827 value.filename = filename
Brian Granger
More re-organization of InteractiveShell.
r2242 except:
# Not the format we expect; leave it alone
pass
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611
luzpaz
Misc. typo fixes...
r24084 # If the error occurred when executing compiled code, we should provide full stacktrace.
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
stb = self.SyntaxTB.structured_traceback(etype, value, elist)
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 self._showtraceback(etype, value, stb)
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Only tell the user about %paste in the terminal shell.
r4226 # This is overridden in TerminalInteractiveShell to show a message about
# the %paste magic.
Thomas Kluyver
Make showindentationerror a separate function, so it can have its own docstring.
r4227 def showindentationerror(self):
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 """Called by _run_cell when there's an IndentationError in code entered
Thomas Kluyver
Make showindentationerror a separate function, so it can have its own docstring.
r4227 at the prompt.
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Make showindentationerror a separate function, so it can have its own docstring.
r4227 This is overridden in TerminalInteractiveShell to show a message about
the %paste magic."""
self.showsyntaxerror()
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
# Things related to readline
#-------------------------------------------------------------------------
def init_readline(self):
Matthias Bussonnier
Remove readline mention, add Deprecation Warning
r22643 """DEPRECATED
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Matthias Bussonnier
Remove readline mention, add Deprecation Warning
r22643 Moved to terminal subclass, here only to simplify the init logic."""
Thomas Kluyver
Move most readline code from InteractiveShell to terminal subclass...
r21846 # Set a number of methods that depend on readline to be no-op
Matthias Bussonnier
Remove readline mention, add Deprecation Warning
r22643 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
DeprecationWarning, stacklevel=2)
Thomas Kluyver
Move most readline code from InteractiveShell to terminal subclass...
r21846 self.set_custom_completer = no_op
Brian Granger
Continuing a massive refactor of everything.
r2205
Thomas Kluyver
Skip doctest that can't possibly work.
r9246 @skip_doctest
Thomas Kluyver
Machinery to replace the current cell instead of adding a new one
r19250 def set_next_input(self, s, replace=False):
Brian Granger
Continuing a massive refactor of everything.
r2205 """ Sets the 'default' input string for the next command line.
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Miscellaneous docs fixes
r9244 Example::
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Miscellaneous docs fixes
r9244 In [1]: _ip.set_next_input("Hello Word")
In [2]: Hello Word_ # cursor is here
Brian Granger
Continuing a massive refactor of everything.
r2205 """
Srinivas Reddy Thatiparthy
rm cast_bytes_py2
r23666 self.rl_next_input = s
Brian Granger
Continuing a massive refactor of everything.
r2205
Brian Granger
More re-organization of InteractiveShell.
r2242 def _indent_current_str(self):
"""return the current level of indentation as a string"""
Thomas Kluyver
Avoid unnecessary calculation of indent on every line
r24048 return self.input_splitter.get_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
Thomas Ballinger
fix typos in docstrings
r21859 library), programmatically (such as in test suites) or out-of-process
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 (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,
Paul Ivanov
%reset now takes optional in/out/dhist/array args...
r5965 magic_run_completer, cd_completer, reset_completer)
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
make Completer.greedy configurable
r4825 self.Completer = IPCompleter(shell=self,
namespace=self.user_ns,
global_namespace=self.user_global_ns,
MinRK
use `parent=self` throughout IPython...
r11064 parent=self,
MinRK
make Completer.greedy configurable
r4825 )
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.Completer)
Bernardo B. Marques
remove all trailling spaces
r4872
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')
Min RK
use module completion on %aimport
r21717 self.set_hook('complete_command', module_completer, str_key = '%aimport')
Fernando Perez
Restored major default completer functionality (cd, import, run)....
r2959 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
self.set_hook('complete_command', cd_completer, str_key = '%cd')
Paul Ivanov
%reset now takes optional in/out/dhist/array args...
r5965 self.set_hook('complete_command', reset_completer, str_key = '%reset')
Fernando Perez
Restored major default completer functionality (cd, import, run)....
r2959
Thomas Kluyver
Fix tests of IPython completion machinery
r24128 @skip_doctest
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 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
-------
Matthias Bussonnier
Fix docstring syntax to be properly parsed by numpydoc.
r26478 text : string
The actual text that was completed.
Fernando Perez
Reorganization of readline and completion dependent code....
r2956
Matthias Bussonnier
Fix docstring syntax to be properly parsed by numpydoc.
r26478 matches : list
A sorted list with all possible completions.
Fernando Perez
Reorganization of readline and completion dependent code....
r2956
Matthias Bussonnier
Fix docstring syntax to be properly parsed by numpydoc.
r26478
Notes
-----
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 The optional arguments allow the completion to take more context into
account, and are part of the low-level completion API.
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 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.
Matthias Bussonnier
Fix docstring syntax to be properly parsed by numpydoc.
r26478 Examples
--------
Fernando Perez
Reorganization of readline and completion dependent code....
r2956
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)
Matthias Bussonnier
Implement understanding on __tracebackhide__...
r25839 def set_custom_completer(self, completer, pos=0) -> None:
Fernando Perez
Reorganization of readline and completion dependent code....
r2956 """Adds a new custom completer function.
The position argument (defaults to 0) is the index in the completers
Matthias Bussonnier
Implement understanding on __tracebackhide__...
r25839 list where you want the completer to be inserted.
`completer` should have the following signature::
def completion(self: Completer, text: string) -> List[str]:
raise NotImplementedError
It will be bound to the current Completer instance and pass some text
and return a list with current completions to suggest to the user.
"""
Fernando Perez
Reorganization of readline and completion dependent code....
r2956
Matthias Bussonnier
Try to elide long completion based on user input....
r25689 newcomp = types.MethodType(completer, self.Completer)
Nathan Goldbaum
Ensure set_custom_completer is working. Fixes #11272
r25490 self.Completer.custom_matchers.insert(pos,newcomp)
Fernando Perez
Reorganization of readline and completion dependent code....
r2956
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):
Fernando Perez
Create new core.magics package and start populating with history.
r6956 from IPython.core import magics as m
Fernando Perez
Add proper initialization of magics to main shell instance....
r6923 self.magics_manager = magic.MagicsManager(shell=self,
MinRK
use `parent=self` throughout IPython...
r11064 parent=self,
Fernando Perez
Move UserMagics to core.magics
r6957 user_magics=m.UserMagics(self))
Fernando Perez
Add proper initialization of magics to main shell instance....
r6923 self.configurables.append(self.magics_manager)
Fernando Perez
Settle on cleaner API for magic registration....
r6936 # Expose as public API from the magics manager
Fernando Perez
Clean up magic registration api and make it public.
r6933 self.register_magics = self.magics_manager.register
Fernando Perez
Create core.magics.auto according to new API.
r6964 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
Matthias Bussonnier
Don't register deprecated magics that have been removed.
r22410 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
Fernando Perez
Create core.magics.extension according to new API.
r6967 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
Jake VanderPlas
ENH: add pip and conda magics
r24880 m.NamespaceMagics, m.OSMagics, m.PackagingMagics,
m.PylabMagics, m.ScriptMagics,
MinRK
add script magics...
r7299 )
kousik
Removed codepath for Python < 3.6 #11949
r25245 self.register_magics(m.AsyncMagics)
Fernando Perez
Add proper initialization of magics to main shell instance....
r6923
Bradley M. Froehle
Use magic alias api to register magic aliases.
r7933 # Register Magic Aliases
mman = self.magics_manager
MinRK
clarify FIXME comment for magics aliases
r10655 # FIXME: magic aliases should be defined by the Magics classes
# or in MagicsManager, not here
Bradley M. Froehle
Use magic alias api to register magic aliases.
r7933 mman.register_alias('ed', 'edit')
mman.register_alias('hist', 'history')
mman.register_alias('rep', 'recall')
MinRK
add uppercase aliases to html, svg cell magics...
r10000 mman.register_alias('SVG', 'svg', 'cell')
mman.register_alias('HTML', 'html', 'cell')
MinRK
make that writefile
r10634 mman.register_alias('file', 'writefile', 'cell')
Bradley M. Froehle
Use magic alias api to register magic aliases.
r7933
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.
adityausathe
fix for #10327: _stack_depth added and {u} string literals removed from core/tests
r23764 self.run_line_magic('colors', self.colors)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Declare ip.register_magic_function at class level so that it is included in docs
r12297 # Defined here so that it's included in the documentation
@functools.wraps(magic.MagicsManager.register_function)
def register_magic_function(self, func, magic_kind='line', magic_name=None):
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329 self.magics_manager.register_function(
func, magic_kind=magic_kind, magic_name=magic_name
)
Ville M. Vainio
crlf -> lf
r1032
adityausathe
fix for #10327: _stack_depth added and {u} string literals removed from core/tests
r23764 def run_line_magic(self, magic_name, line, _stack_depth=1):
Fernando Perez
First working version of cell magic support.
r6953 """Execute the given line magic.
Fernando Perez
Fix https://bugs.launchpad.net/ipython/+bug/239054...
r1859
Fernando Perez
First working version of cell magic support.
r6953 Parameters
----------
magic_name : str
Matthias Bussonnier
DOC: more docstrign formatting
r25907 Name of the desired magic function, without '%' prefix.
Fernando Perez
First working version of cell magic support.
r6953 line : str
Matthias Bussonnier
DOC: more docstrign formatting
r25907 The rest of the input line as a single string.
adityausathe
fix for #10327: _stack_depth added and {u} string literals removed from core/tests
r23764 _stack_depth : int
Matthias Bussonnier
DOC: more docstrign formatting
r25907 If run_line_magic() is called from magic() then _stack_depth=2.
This is added to ensure backward compatibility for use of 'get_ipython().magic()'
Brian Granger
More re-organization of InteractiveShell.
r2242 """
Fernando Perez
First working version of cell magic support.
r6953 fn = self.find_line_magic(magic_name)
Brian Granger
More re-organization of InteractiveShell.
r2242 if fn is None:
Fernando Perez
First working version of cell magics in inputsplitter in line mode....
r6978 cm = self.find_cell_magic(magic_name)
Fernando Perez
Improve error messages for line/cell magics.
r6983 etpl = "Line magic function `%%%s` not found%s."
extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
'did you mean that instead?)' % magic_name )
Min RK
raise UsageError on magic not found...
r23833 raise UsageError(etpl % (magic_name, extra))
Brian Granger
More re-organization of InteractiveShell.
r2242 else:
Fernando Perez
First working version of cell magic support.
r6953 # Note: this is the distance in the stack to the user's frame.
# This will need to be updated if the internal calling logic gets
# refactored, or else we'll be expanding the wrong variables.
Min RK
Don't expand user variables in execution magics...
r24859
adityausathe
Fix #10327: Test fails handled and magic() backward compatibilty added
r23756 # Determine stack_depth depending on where run_line_magic() has been called
adityausathe
fix for #10327: _stack_depth added and {u} string literals removed from core/tests
r23764 stack_depth = _stack_depth
Min RK
Don't expand user variables in execution magics...
r24859 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
# magic has opted out of var_expand
magic_arg_s = line
else:
magic_arg_s = self.var_expand(line, stack_depth)
Fernando Perez
Simplify logic of passing local scope to magics that need it....
r6907 # Put magic args in a list so we can call with f(*a) syntax
args = [magic_arg_s]
Guy Haskin Fernald
Added functionality to %R and %octave magics so that -i first looks in local...
r8262 kwargs = {}
Thomas Kluyver
Refine implementation, so that local scope is only used if a function needs it.
r3479 # Grab local namespace if we need it:
if getattr(fn, "needs_local_scope", False):
Quentin Peter
Move Extraction of local scope to a method...
r25886 kwargs['local_ns'] = self.get_local_scope(stack_depth)
Fernando Perez
Make post-execution happen at the cell instead of the block level....
r3732 with self.builtin_trap:
Min RK
Don't expand user variables in execution magics...
r24859 result = fn(*args, **kwargs)
Thomas Kluyver
Refine implementation, so that local scope is only used if a function needs it.
r3479 return result
Ville M. Vainio
crlf -> lf
r1032
Quentin Peter
Move Extraction of local scope to a method...
r25886 def get_local_scope(self, stack_depth):
"""Get local scope at given stack depth.
Parameters
----------
stack_depth : int
Matthias Bussonnier
DOC: more docstrign formatting
r25907 Depth relative to calling frame
Quentin Peter
Move Extraction of local scope to a method...
r25886 """
return sys._getframe(stack_depth + 1).f_locals
Fernando Perez
Rename a few methods as per review, also complete some docstrings.
r7003 def run_cell_magic(self, magic_name, line, cell):
Fernando Perez
First working version of cell magic support.
r6953 """Execute the given cell magic.
Min RK
Don't expand user variables in execution magics...
r24859
Fernando Perez
Rename a few methods as per review, also complete some docstrings.
r7003 Parameters
----------
magic_name : str
Matthias Bussonnier
DOC: more docstrign formatting
r25907 Name of the desired magic function, without '%' prefix.
Fernando Perez
Rename a few methods as per review, also complete some docstrings.
r7003 line : str
Matthias Bussonnier
DOC: more docstrign formatting
r25907 The rest of the first input line as a single string.
Fernando Perez
Rename a few methods as per review, also complete some docstrings.
r7003 cell : str
Matthias Bussonnier
DOC: more docstrign formatting
r25907 The body of the cell as a (possibly multiline) string.
Fernando Perez
First working version of cell magic support.
r6953 """
fn = self.find_cell_magic(magic_name)
if fn is None:
Fernando Perez
Improve error messages for line/cell magics.
r6983 lm = self.find_line_magic(magic_name)
MinRK
better UsageError for cell magic with no body...
r10227 etpl = "Cell magic `%%{0}` not found{1}."
Robert Marchman
new style formatting for magic-not-found warning
r9469 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
'did you mean that instead?)'.format(magic_name))
Min RK
raise UsageError on magic not found...
r23833 raise UsageError(etpl.format(magic_name, extra))
Robert Marchman
general empty cell warning
r9466 elif cell == '':
MinRK
better UsageError for cell magic with no body...
r10227 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
if self.find_line_magic(magic_name) is not None:
message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
raise UsageError(message)
Fernando Perez
First working version of cell magic support.
r6953 else:
# Note: this is the distance in the stack to the user's frame.
# This will need to be updated if the internal calling logic gets
# refactored, or else we'll be expanding the wrong variables.
stack_depth = 2
Min RK
Don't expand user variables in execution magics...
r24859 if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
# magic has opted out of var_expand
magic_arg_s = line
else:
magic_arg_s = self.var_expand(line, stack_depth)
Matthias Bussonnier
Apply @needs_local_scope to cell magics....
r24895 kwargs = {}
if getattr(fn, "needs_local_scope", False):
Matthias Bussonnier
Fix applying @needs_global_scope to cell magics....
r25007 kwargs['local_ns'] = self.user_ns
Matthias Bussonnier
Apply @needs_local_scope to cell magics....
r24895
Fernando Perez
First working version of cell magic support.
r6953 with self.builtin_trap:
Matthias Bussonnier
Apply @needs_local_scope to cell magics....
r24895 args = (magic_arg_s, cell)
result = fn(*args, **kwargs)
Fernando Perez
First working version of cell magic support.
r6953 return result
Fernando Perez
Add proper initialization of magics to main shell instance....
r6923 def find_line_magic(self, magic_name):
Fernando Perez
First working version of cell magic support.
r6953 """Find and return a line magic by name.
Returns None if the magic isn't found."""
Fernando Perez
Add proper initialization of magics to main shell instance....
r6923 return self.magics_manager.magics['line'].get(magic_name)
def find_cell_magic(self, magic_name):
Fernando Perez
First working version of cell magic support.
r6953 """Find and return a cell magic by name.
Returns None if the magic isn't found."""
Fernando Perez
Add proper initialization of magics to main shell instance....
r6923 return self.magics_manager.magics['cell'].get(magic_name)
Fernando Perez
Remove next_input nonsense in magic calls (but keep functionality).
r6974 def find_magic(self, magic_name, magic_kind='line'):
Fernando Perez
First working version of cell magic support.
r6953 """Find and return a magic of the given type by name.
Returns None if the magic isn't found."""
Fernando Perez
Remove next_input nonsense in magic calls (but keep functionality).
r6974 return self.magics_manager.magics[magic_kind].get(magic_name)
Fernando Perez
First full decoupling of magics into a standalone object.
r6906
Fernando Perez
Remove next_input nonsense in magic calls (but keep functionality).
r6974 def magic(self, arg_s):
Fernando Perez
Rename a few methods as per review, also complete some docstrings.
r7003 """DEPRECATED. Use run_line_magic() instead.
Fernando Perez
First working version of cell magic support.
r6953
Call a magic function by name.
Input: a string containing the name of the magic function to call and
any additional arguments to be passed to the magic.
magic('name -opt foo bar') is equivalent to typing at the ipython
prompt:
In[1]: %name -opt foo bar
To call a magic without arguments, simply use magic('name').
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.
"""
# TODO: should we issue a loud deprecation warning here?
magic_name, _, magic_arg_s = arg_s.partition(' ')
magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
adityausathe
fix for #10327: _stack_depth added and {u} string literals removed from core/tests
r23764 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
Fernando Perez
First working version of cell magic support.
r6953
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
Bernardo B. Marques
remove all trailling spaces
r4872 The action to do upon invoking the macro. If a string, a new
Brian Granger
More re-organization of InteractiveShell.
r2242 Macro object is created by passing the string to it.
Fernando Perez
Work again on bug 269966....
r1916 """
Bernardo B. Marques
remove all trailling spaces
r4872
Brian Granger
More re-organization of InteractiveShell.
r2242 from IPython.core import macro
Fernando Perez
Work again on bug 269966....
r1916
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 if isinstance(themacro, str):
Brian Granger
More re-organization of InteractiveShell.
r2242 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
MinRK
split shell.system into shell.system_raw/system_piped...
r3909 def system_piped(self, cmd):
"""Call the given cmd in a subprocess, piping stdout/err
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002
Parameters
----------
cmd : str
MinRK
split shell.system into shell.system_raw/system_piped...
r3909 Command to execute (can not end in '&', as background processes are
not supported. Should not be a command that expects input
other than simple text.
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 """
MinRK
split shell.system into shell.system_raw/system_piped...
r3909 if cmd.rstrip().endswith('&'):
# this is *far* from a rigorous test
# We do not support backgrounding processes because we either use
# pexpect or pipes to read from. Users can always just call
# os.system() or use ip.system=ip.system_raw
# if they really want a background process.
Fernando Perez
Remove shell hook and system_verbose magic....
r2905 raise OSError("Background processes not supported.")
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
store exit code in user_ns['_exit_code']...
r3910 # we explicitly do NOT return the subprocess status code, because
# a non-None value would trigger :func:`sys.displayhook` calls.
# Instead, we store the exit_code in user_ns.
Thomas Kluyver
Correct stack depth for !system calls...
r7332 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
split shell.system into shell.system_raw/system_piped...
r3909 def system_raw(self, cmd):
Théophile Studer
Use default OS shell to run system commands...
r12366 """Call the given cmd in a subprocess using os.system on Windows or
subprocess.call using the system shell on other platforms.
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
split shell.system into shell.system_raw/system_piped...
r3909 Parameters
----------
cmd : str
Command to execute.
"""
Thomas Kluyver
Correct stack depth for !system calls...
r7332 cmd = self.var_expand(cmd, depth=1)
Ashwin Vishnu
Warn if user executes !pip or !conda...
r26526 # warn if there is an IPython magic alternative.
main_cmd = cmd.split()[0]
Sammy Al Hashemi
Adding !cd and !ls warnings
r26527 has_magic_alternatives = ("pip", "conda", "cd", "ls")
# had to check if the command was an alias expanded because of `ls`
Sammy Al Hashemi
Fixed linter error
r26528 is_alias_expanded = self.alias_manager.is_alias(main_cmd) and (
self.alias_manager.retrieve_alias(main_cmd).strip() == cmd.strip()
)
Sammy Al Hashemi
Adding !cd and !ls warnings
r26527
if main_cmd in has_magic_alternatives and not is_alias_expanded:
Ashwin Vishnu
Warn if user executes !pip or !conda...
r26526 warnings.warn(
(
"You executed the system command !{0} which may not work "
"as expected. Try the IPython magic %{0} instead."
).format(main_cmd)
)
MinRK
protect system_raw from UNC paths on windows
r5277 # protect os.system from UNC paths on Windows, which it can't handle:
if sys.platform == 'win32':
from IPython.utils._process_win32 import AvoidUNCPath
with AvoidUNCPath() as path:
if path is not None:
cmd = '"pushd %s &&"%s' % (path, cmd)
Thomas Kluyver
Catch KeyboardInterrupt for !commands on Windows...
r18765 try:
ec = os.system(cmd)
except KeyboardInterrupt:
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 print('\n' + self.get_exception_only(), file=sys.stderr)
Thomas Kluyver
Catch KeyboardInterrupt for !commands on Windows...
r18765 ec = -2
MinRK
protect system_raw from UNC paths on windows
r5277 else:
mvr
[issue6883] catch keyboardinterrupt if generated during shell.system() calls
r18732 # For posix the result of the subprocess.call() below is an exit
# code, which by convention is zero for success, positive for
# program failure. Exit codes above 128 are reserved for signals,
# and the formula for converting a signal to an exit code is usually
# signal_number+128. To more easily differentiate between exit
# codes and signals, ipython uses negative numbers. For instance
# since control-c is signal 2 but exit code 130, ipython's
# _exit_code variable will read -2. Note that some shells like
# csh and fish don't follow sh/bash conventions for exit codes.
executable = os.environ.get('SHELL', None)
try:
# Use env shell instead of default /bin/sh
ec = subprocess.call(cmd, shell=True, executable=executable)
except KeyboardInterrupt:
# intercept control-C; a long traceback is not useful here
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 print('\n' + self.get_exception_only(), file=sys.stderr)
mvr
[issue6883] catch keyboardinterrupt if generated during shell.system() calls
r18732 ec = 130
MinRK
handle error code > 128 in system_raw like system_piped...
r17015 if ec > 128:
ec = -(ec - 128)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
store exit code in user_ns['_exit_code']...
r3910 # We explicitly do NOT return the subprocess status code, because
# a non-None value would trigger :func:`sys.displayhook` calls.
mvr
[issue6883] catch keyboardinterrupt if generated during shell.system() calls
r18732 # Instead, we store the exit_code in user_ns. Note the semantics
# of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
# but raising SystemExit(_exit_code) will give status 254!
MinRK
protect system_raw from UNC paths on windows
r5277 self.user_ns['_exit_code'] = ec
Bernardo B. Marques
remove all trailling spaces
r4872
MinRK
split shell.system into shell.system_raw/system_piped...
r3909 # use piped system by default, because it is better behaved
system = system_piped
Fernando Perez
Remove shell hook and system_verbose magic....
r2905
Thomas Kluyver
Expose & document depth parameter to ip.getoutput()
r7400 def getoutput(self, cmd, split=True, depth=0):
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 """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.
Thomas Kluyver
Expose & document depth parameter to ip.getoutput()
r7400 depth : int, optional
How many frames above the caller are the local variables which should
be expanded in the command string? The default (0) assumes that the
expansion variables are in the stack frame calling this function.
"""
MinRK
split shell.system into shell.system_raw/system_piped...
r3909 if cmd.rstrip().endswith('&'):
# this is *far* from a rigorous test
Fernando Perez
Remove shell hook and system_verbose magic....
r2905 raise OSError("Background processes not supported.")
Thomas Kluyver
Expose & document depth parameter to ip.getoutput()
r7400 out = getoutput(self.var_expand(cmd, depth=depth+1))
Fernando Perez
Fix bugs in x=!cmd; we can't use pexpect at all....
r3002 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):
MinRK
use `parent=self` throughout IPython...
r11064 self.alias_manager = AliasManager(shell=self, parent=self)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.alias_manager)
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
More re-organization of InteractiveShell.
r2242 #-------------------------------------------------------------------------
Brian Granger
Cleaning up extensions that used plugins.
r8197 # Things related to extensions
Brian Granger
First draft of refactored Component->Configurable.
r2731 #-------------------------------------------------------------------------
def init_extension_manager(self):
MinRK
use `parent=self` throughout IPython...
r11064 self.extension_manager = ExtensionManager(shell=self, parent=self)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.extension_manager)
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):
MinRK
use `parent=self` throughout IPython...
r11064 self.payload_manager = PayloadManager(parent=self)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.payload_manager)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Brian Granger
Final attempt to fix init_io logic.
r2810 #-------------------------------------------------------------------------
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # Things related to the prefilter
#-------------------------------------------------------------------------
def init_prefilter(self):
MinRK
use `parent=self` throughout IPython...
r11064 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
MinRK
add %config magic for configuring IPython
r5225 self.configurables.append(self.prefilter_manager)
Brian Granger
Complete reorganization of InteractiveShell....
r2761 # 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)
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Change wording of example so
r2954 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 """
Thomas Kluyver
Make rewrite prompt non-configurable.
r5555 if not self.show_rewritten_input:
return
Fernando Perez
Put auto_rewrite functionality into a method so subclasses can do the...
r2951
Thomas Kluyver
New prompts class for terminal interface
r22421 # This is overridden in TerminalInteractiveShell to use fancy prompts
print("------> " + cmd)
Bernardo B. Marques
remove all trailling spaces
r4872
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
#-------------------------------------------------------------------------
MinRK
user_variables and user_expressions use rich repr API...
r10636 def _user_obj_error(self):
"""return simple exception dict
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
remove user_variables...
r16570 for use in user_expressions
MinRK
user_variables and user_expressions use rich repr API...
r10636 """
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
user_variables and user_expressions use rich repr API...
r10636 etype, evalue, tb = self._get_exc_info()
stb = self.InteractiveTB.get_exception_only(etype, evalue)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
user_variables and user_expressions use rich repr API...
r10636 exc_info = {
Matthias Bussonnier
Python3 compat layer cleanup
r26209 "status": "error",
"traceback": stb,
"ename": etype.__name__,
"evalue": py3compat.safe_unicode(evalue),
MinRK
user_variables and user_expressions use rich repr API...
r10636 }
Fernando Perez
Rework messaging to better conform to our spec....
r2926
MinRK
user_variables and user_expressions use rich repr API...
r10636 return exc_info
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
user_variables and user_expressions use rich repr API...
r10636 def _format_user_obj(self, obj):
"""format a user object to display dict
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
remove user_variables...
r16570 for use in user_expressions
MinRK
user_variables and user_expressions use rich repr API...
r10636 """
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
user_variables and user_expressions use rich repr API...
r10636 data, md = self.display_formatter.format(obj)
value = {
'status' : 'ok',
'data' : data,
'metadata' : md,
}
return value
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
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.
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Document the code execution semantics much more carefully....
r3050 Returns
-------
MinRK
user_variables and user_expressions use rich repr API...
r10636 A dict, keyed like the input expressions dict, with the rich mime-typed
display_data 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
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Srinivas Reddy Thatiparthy
Change functions,...
r23036 for key, expr in expressions.items():
Fernando Perez
Rework messaging to better conform to our spec....
r2926 try:
MinRK
user_variables and user_expressions use rich repr API...
r10636 value = self._format_user_obj(eval(expr, global_ns, user_ns))
Fernando Perez
Rework messaging to better conform to our spec....
r2926 except:
MinRK
user_variables and user_expressions use rich repr API...
r10636 value = self._user_obj_error()
Fernando Perez
Rework messaging to better conform to our spec....
r2926 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."""
Fernando Perez
Make post-execution happen at the cell instead of the block level....
r3732 with self.builtin_trap:
Thomas Kluyver
Fix exec statements for Py 3...
r13350 exec(cmd, 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
"""
Fernando Perez
Make post-execution happen at the cell instead of the block level....
r3732 with 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
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
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).
Jörgen Stenarson
Adding test for safe_execfile call with non-ascii path
r5094 raise_exceptions : bool (False)
If True raise exceptions everywhere. Meant for testing.
Thomas Ballinger
save future compile directives from ipython -i module.py
r18526 shell_futures : bool (False)
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
Jörgen Stenarson
Adding test for safe_execfile call with non-ascii path
r5094
Brian Granger
Work on startup related things....
r2252 """
Ashwin Vishnu
Use pathlib in interactiveshell.py
r26035 fname = Path(fname).expanduser().resolve()
Ville M. Vainio
crlf -> lf
r1032
Brian Granger
Work on startup related things....
r2252 # Make sure we can open the file
try:
Ashwin Vishnu
Use pathlib in interactiveshell.py
r26035 with fname.open():
Brian Granger
Work on startup related things....
r2252 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
Ashwin Vishnu
Use pathlib in interactiveshell.py
r26035 dname = str(fname.parent)
Brian Granger
More re-organization of InteractiveShell.
r2242
Thomas Kluyver
Use builtin_trap in safe_execfile...
r22737 with prepended_to_syspath(dname), self.builtin_trap:
Brian Granger
More re-organization of InteractiveShell.
r2242 try:
Thomas Ballinger
save future compile directives from ipython -i module.py
r18526 glob, loc = (where + (None, ))[:2]
py3compat.execfile(
fname, glob, loc,
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 self.compile if shell_futures else None)
Matthias BUSSONNIER
conform to pep 3110...
r7787 except SystemExit as 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.
Fairly
Set exit code on script errors....
r21758 if status.code:
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 if raise_exceptions:
Fairly
Set exit code on script errors....
r21758 raise
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 if not exit_ignore:
Fairly
Set exit code on script errors....
r21758 self.showtraceback(exception_only=True)
Brian Granger
More re-organization of InteractiveShell.
r2242 except:
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 if raise_exceptions:
Jörgen Stenarson
Adding test for safe_execfile call with non-ascii path
r5094 raise
MinRK
fix tb_offset when running a file...
r14730 # tb offset is 2 because we wrap execfile
self.showtraceback(tb_offset=2)
Brian Granger
More re-organization of InteractiveShell.
r2242
Tianhui Michael Li
flipping order of charges in safe_exefile_ipy
r21412 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
MinRK
support notebooks in %run...
r13644 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
Brian Granger
Work on startup related things....
r2252
Parameters
----------
fname : str
The name of the file to execute. The filename must have a
MinRK
support notebooks in %run...
r13644 .ipy or .ipynb extension.
Thomas Ballinger
save future compile directives from ipython -i module.py
r18526 shell_futures : bool (False)
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
Tianhui Michael Li
flipping order of charges in safe_exefile_ipy
r21412 raise_exceptions : bool (False)
If True raise exceptions everywhere. Meant for testing.
Brian Granger
Work on startup related things....
r2252 """
Ashwin Vishnu
Use pathlib in interactiveshell.py
r26035 fname = Path(fname).expanduser().resolve()
Brian Granger
Work on startup related things....
r2252
# Make sure we can open the file
try:
Ashwin Vishnu
Use pathlib in interactiveshell.py
r26035 with fname.open():
Brian Granger
Work on startup related things....
r2252 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
Ashwin Vishnu
Use pathlib in interactiveshell.py
r26035 dname = str(fname.parent)
MinRK
support notebooks in %run...
r13644 def get_cells():
"""generator for sequence of code blocks to run"""
Ashwin Vishnu
Run darker
r26037 if fname.suffix == ".ipynb":
Min RK
jupyter_nbformat is now nbformat
r21345 from nbformat import read
Thomas Kluyver
Let nbformat take care of opening the file...
r23649 nb = read(fname, as_version=4)
if not nb.cells:
return
for cell in nb.cells:
if cell.cell_type == 'code':
yield cell.source
MinRK
support notebooks in %run...
r13644 else:
Ashwin Vishnu
Use pathlib in interactiveshell.py
r26035 yield fname.read_text()
Brian Granger
Work on startup related things....
r2252
with prepended_to_syspath(dname):
try:
MinRK
support notebooks in %run...
r13644 for cell in get_cells():
Min RK
stop %run foo.ipynb on exception...
r19937 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
Tianhui Michael Li
ExecutionResult support `raise_error` method
r21413 if raise_exceptions:
result.raise_error()
Tianhui Michael Li
safe_execfile_ipy optionally raises exception in user code
r21409 elif not result.success:
Min RK
stop %run foo.ipynb on exception...
r19937 break
Brian Granger
Work on startup related things....
r2252 except:
Tianhui Michael Li
Reprising caught error
r21411 if raise_exceptions:
raise
Brian Granger
Work on startup related things....
r2252 self.showtraceback()
warn('Unknown failure executing file: <%s>' % fname)
Bernardo B. Marques
remove all trailling spaces
r4872
Bradley M. Froehle
Add '-m mod : run library module as a script' option....
r6029 def safe_run_module(self, mod_name, where):
"""A safe version of runpy.run_module().
This version will never throw an exception, but instead print
helpful error messages to the screen.
Bradley M. Froehle
safe_run_module: Ignore SystemExit codes 0 and None.
r9679 `SystemExit` exceptions with status code 0 or None are ignored.
Bradley M. Froehle
Add '-m mod : run library module as a script' option....
r6029 Parameters
----------
mod_name : string
The name of the module to be executed.
where : dict
The globals namespace.
"""
try:
Bradley M. Froehle
safe_run_module: Ignore SystemExit codes 0 and None.
r9679 try:
where.update(
runpy.run_module(str(mod_name), run_name="__main__",
alter_sys=True)
Matthias Bussonnier
Cleaning of Oinspect....
r23673 )
Bradley M. Froehle
safe_run_module: Ignore SystemExit codes 0 and None.
r9679 except SystemExit as status:
if status.code:
raise
Bradley M. Froehle
Add '-m mod : run library module as a script' option....
r6029 except:
self.showtraceback()
warn('Unknown failure executing module: <%s>' % mod_name)
Thomas Kluyver
Add shell_futures parameter to run_cell to allow running code without sharing __future__ imports.
r9081 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 """Run a complete IPython cell.
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 Parameters
----------
Thomas Kluyver
Fix bug with magic names in multi-line strings. run_cell now uses inputsplitter for static transformations.
r3709 raw_cell : str
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell will be stored in IPython's
history. For user code calling back into IPython's machinery, this
should be set to False.
MinRK
add silent kwarg to run_cell...
r6802 silent : bool
Jason Grout
Fix docs to clearly indicate relationship between store_history and silent execute message parameters.
r7999 If True, avoid side-effects, such as implicit displayhooks and
MinRK
add silent kwarg to run_cell...
r6802 and logging. silent=True forces store_history=False.
Thomas Kluyver
Add shell_futures parameter to run_cell to allow running code without sharing __future__ imports.
r9081 shell_futures : bool
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630
Returns
-------
result : :class:`ExecutionResult`
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 """
Thomas Kluyver
Ensure that result is defined in run_cell()...
r24169 result = None
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 try:
result = self._run_cell(
raw_cell, store_history, silent, shell_futures)
finally:
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 self.events.trigger('post_execute')
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 if not silent:
Fabio Niephaus
Ensure post event callbacks are always called....
r23982 self.events.trigger('post_run_cell', result)
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 return result
Brendan Gerrity
[interactiveshell] add type annotation to run cell
r25841 def _run_cell(self, raw_cell:str, store_history:bool, silent:bool, shell_futures:bool) -> ExecutionResult:
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 """Internal method to run a complete IPython cell."""
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891
# we need to avoid calling self.transform_cell multiple time on the same thing
# so we need to store some results:
preprocessing_exc_tuple = None
try:
transformed_cell = self.transform_cell(raw_cell)
except Exception:
transformed_cell = raw_cell
preprocessing_exc_tuple = sys.exc_info()
assert transformed_cell is not None
Dale Jung
Only trigger async loop runner when needed. Allows running files that...
r24483 coro = self.run_cell_async(
raw_cell,
store_history=store_history,
silent=silent,
shell_futures=shell_futures,
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 transformed_cell=transformed_cell,
preprocessing_exc_tuple=preprocessing_exc_tuple,
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 )
Min RK
make `run_cell_async` a regular coroutine...
r24537 # run_cell_async is async, but may not actually need an eventloop.
Matthias Bussonnier
docs cleanup, reformat code, remove dead code.
r24490 # when this is the case, we want to run it using the pseudo_sync_runner
# so that code can invoke eventloops (for example via the %run , and
# `%paste` magic.
Mark E. Haase
More work on Trio background loop...
r25432 if self.trio_runner:
runner = self.trio_runner
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 elif self.should_run_async(
raw_cell,
transformed_cell=transformed_cell,
preprocessing_exc_tuple=preprocessing_exc_tuple,
):
Min RK
make `run_cell_async` a regular coroutine...
r24537 runner = self.loop_runner
else:
runner = _pseudo_sync_runner
Dale Jung
Only trigger async loop runner when needed. Allows running files that...
r24483 try:
Min RK
make `run_cell_async` a regular coroutine...
r24537 return runner(coro)
Min RK
catch BaseException in coroutine runner...
r24543 except BaseException as e:
Min RK
make `run_cell_async` a regular coroutine...
r24537 info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
result = ExecutionResult(info)
result.error_in_exec = e
self.showtraceback(running_compiled_code=True)
return result
Dale Jung
Only trigger async loop runner when needed. Allows running files that...
r24483
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 def should_run_async(
self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None
) -> bool:
Min RK
make `run_cell_async` a regular coroutine...
r24537 """Return whether a cell should be run asynchronously via a coroutine runner
Dale Jung
Only trigger async loop runner when needed. Allows running files that...
r24483
Min RK
make `run_cell_async` a regular coroutine...
r24537 Parameters
----------
raw_cell: str
The code to be executed
Returns
-------
result: bool
Whether the code needs to be run with a coroutine runner or not
.. versionadded: 7.0
"""
if not self.autoawait:
return False
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 if preprocessing_exc_tuple is not None:
Min RK
make `run_cell_async` a regular coroutine...
r24537 return False
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 assert preprocessing_exc_tuple is None
if transformed_cell is None:
warnings.warn(
"`should_run_async` will not call `transform_cell`"
" automatically in the future. Please pass the result to"
" `transformed_cell` argument and any exception that happen"
" during the"
"transform in `preprocessing_exc_tuple` in"
" IPython 7.17 and above.",
DeprecationWarning,
stacklevel=2,
)
try:
cell = self.transform_cell(raw_cell)
except Exception:
# any exception during transform will be raised
# prior to execution
return False
else:
cell = transformed_cell
Min RK
make `run_cell_async` a regular coroutine...
r24537 return _should_be_async(cell)
Dale Jung
Only trigger async loop runner when needed. Allows running files that...
r24483
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 async def run_cell_async(
self,
raw_cell: str,
store_history=False,
silent=False,
shell_futures=True,
*,
transformed_cell: Optional[str] = None,
preprocessing_exc_tuple: Optional[Any] = None
) -> ExecutionResult:
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 """Run a complete IPython cell asynchronously.
Fabio Niephaus
Add support for "finally" event callbacks....
r23909
Parameters
----------
raw_cell : str
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 The code (including IPython code such as %magic functions) to run.
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 store_history : bool
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 If True, the raw and translated cell will be stored in IPython's
history. For user code calling back into IPython's machinery, this
should be set to False.
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 silent : bool
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 If True, avoid side-effects, such as implicit displayhooks and
and logging. silent=True forces store_history=False.
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 shell_futures : bool
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 transformed_cell: str
cell that was passed through transformers
preprocessing_exc_tuple:
trace if the transformation failed.
Fabio Niephaus
Add support for "finally" event callbacks....
r23909
Returns
-------
result : :class:`ExecutionResult`
Min RK
make `run_cell_async` a regular coroutine...
r24537
.. versionadded: 7.0
Fabio Niephaus
Add support for "finally" event callbacks....
r23909 """
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 info = ExecutionInfo(
Fabio Niephaus
Use `backcall` and introduce `ExecutionRequest`
r23996 raw_cell, store_history, silent, shell_futures)
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 result = ExecutionResult(info)
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630
Thomas Kluyver
Tweak empty cell test.
r3710 if (not raw_cell) or raw_cell.isspace():
Sudarshan Raghunathan
Fix reset in interactiveshell to clear execution result for both soft and hard resets and small formatting changes based on PR feedback
r23806 self.last_execution_succeeded = True
self.last_execution_result = result
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 return result
Fabio Niephaus
Use `backcall` and introduce `ExecutionRequest`
r23996
MinRK
add silent kwarg to run_cell...
r6802 if silent:
store_history = False
MinRK
rollback UsageError for cell magic mid-cell...
r11467
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 if store_history:
result.execution_count = self.execution_count
def error_before_exec(value):
Min RK
move execution_count bump to error_before_exec...
r24139 if store_history:
self.execution_count += 1
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 result.error_before_exec = value
Sudarshan Raghunathan
Fix reset in interactiveshell to clear execution result for both soft and hard resets and small formatting changes based on PR feedback
r23806 self.last_execution_succeeded = False
self.last_execution_result = result
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 return result
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 self.events.trigger('pre_execute')
Thomas Kluyver
Start of new callback system
r15597 if not silent:
Fabio Niephaus
Rename ExecutionRequest to ExecutionInfo; refactor
r23997 self.events.trigger('pre_run_cell', info)
Thomas Kluyver
Start of new callback system
r15597
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 if transformed_cell is None:
warnings.warn(
"`run_cell_async` will not call `transform_cell`"
" automatically in the future. Please pass the result to"
" `transformed_cell` argument and any exception that happen"
" during the"
"transform in `preprocessing_exc_tuple` in"
" IPython 7.17 and above.",
DeprecationWarning,
stacklevel=2,
)
# If any of our input transformation (input_transformer_manager or
# prefilter_manager) raises an exception, we store it in this variable
# so that we can display the error after logging the input and storing
# it in the history.
try:
cell = self.transform_cell(raw_cell)
except Exception:
preprocessing_exc_tuple = sys.exc_info()
cell = raw_cell # cell has to exist so it can be stored/logged
else:
preprocessing_exc_tuple = None
Min RK
make `run_cell_async` a regular coroutine...
r24537 else:
Matthias Bussonnier
Avoid calling the input transformer twice in the execution stack....
r25891 if preprocessing_exc_tuple is None:
cell = transformed_cell
else:
cell = raw_cell
Thomas Kluyver
Refactor run_cell for clarity.
r13526
# Store raw and processed history
if store_history:
self.history_manager.store_inputs(self.execution_count,
cell, raw_cell)
if not silent:
self.logger.log(cell, raw_cell)
# Display the exception if input processing failed.
if preprocessing_exc_tuple is not None:
self.showtraceback(preprocessing_exc_tuple)
if store_history:
self.execution_count += 1
lllf
Sets error_before_exec to be the value of the exception instead of the stack trace
r25150 return error_before_exec(preprocessing_exc_tuple[1])
MinRK
rollback UsageError for cell magic mid-cell...
r11467
Thomas Kluyver
Add shell_futures parameter to run_cell to allow running code without sharing __future__ imports.
r9081 # Our own compiler remembers the __future__ environment. If we want to
# run code with a separate __future__ environment, use the default
# compiler
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329 compiler = self.compile if shell_futures else self.compiler_class()
Bernardo B. Marques
remove all trailling spaces
r4872
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 _run_async = False
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 with self.builtin_trap:
Sammy Al Hashemi
Fixing linter error
r26532 cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Refactor run_cell for clarity.
r13526 with self.display_trap:
# Compile to bytecode
try:
Matthias Bussonnier
clenup a bit
r25052 if sys.version_info < (3,8) and self.autoawait:
if _should_be_async(cell):
# the code AST below will not be user code: we wrap it
# in an `async def`. This will likely make some AST
# transformer below miss some transform opportunity and
# introduce a small coupling to run_code (in which we
# bake some assumptions of what _ast_asyncify returns.
# they are ways around (like grafting part of the ast
# later:
# - Here, return code_ast.body[0].body[1:-1], as well
# as last expression in return statement which is
# the user code part.
# - Let it go through the AST transformers, and graft
# - it back after the AST transform
# But that seem unreasonable, at least while we
# do not need it.
code_ast = _ast_asyncify(cell, 'async-def-wrapper')
_run_async = True
else:
code_ast = compiler.ast_parse(cell, filename=cell_name)
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 else:
code_ast = compiler.ast_parse(cell, filename=cell_name)
Matthias Bussonnier
Use generic showtraceback() instead of showsyntaxerror()...
r22431 except self.custom_exceptions as e:
etype, value, tb = sys.exc_info()
self.CustomTB(etype, value, tb)
Min RK
move execution_count bump to error_before_exec...
r24139 return error_before_exec(e)
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 except IndentationError as e:
Thomas Kluyver
Refactor run_cell for clarity.
r13526 self.showindentationerror()
Min RK
move execution_count bump to error_before_exec...
r24139 return error_before_exec(e)
Thomas Kluyver
Refactor run_cell for clarity.
r13526 except (OverflowError, SyntaxError, ValueError, TypeError,
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 MemoryError) as e:
Thomas Kluyver
Refactor run_cell for clarity.
r13526 self.showsyntaxerror()
Min RK
move execution_count bump to error_before_exec...
r24139 return error_before_exec(e)
Thomas Kluyver
Refactor run_cell for clarity.
r13526
# Apply AST transformations
Scott Sanderson
DEV: AST transformers supplied to `InteractiveShell` can reject input....
r17798 try:
code_ast = self.transform_ast(code_ast)
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 except InputRejected as e:
Scott Sanderson
DEV: AST transformers supplied to `InteractiveShell` can reject input....
r17798 self.showtraceback()
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 return error_before_exec(e)
# Give the displayhook a reference to our ExecutionResult so it
# can fill in the output value.
self.displayhook.exec_result = result
Thomas Kluyver
Refactor run_cell for clarity.
r13526
# Execute the user code
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 interactivity = "none" if silent else self.ast_node_interactivity
if _run_async:
interactivity = 'async'
Min RK
make `run_cell_async` a regular coroutine...
r24537
Matthias Bussonnier
cleanup 3.8 compat
r25053 has_raised = await self.run_ast_nodes(code_ast.body, cell_name,
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 interactivity=interactivity, compiler=compiler, result=result)
Min RK
make `run_cell_async` a regular coroutine...
r24537
Sudarshan Raghunathan
Fix reset in interactiveshell to clear execution result for both soft and hard resets and small formatting changes based on PR feedback
r23806 self.last_execution_succeeded = not has_raised
self.last_execution_result = result
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630
# Reset this so later displayed values do not modify the
# ExecutionResult
self.displayhook.exec_result = None
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 if store_history:
# Write output to the database. Does nothing unless
# history output logging is enabled.
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
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630
return result
Thomas Kluyver
Simpler mechanism to extend input transformations
r24400
def transform_cell(self, raw_cell):
Thomas Kluyver
Add & improve docstrings following @willingc's review
r24407 """Transform an input cell before parsing it.
Static transformations, implemented in IPython.core.inputtransformer2,
deal with things like ``%magic`` and ``!system`` commands.
These run on all input.
Dynamic transformations, for things like unescaped magics and the exit
autocall, depend on the state of the interpreter.
These only apply to single line inputs.
These string-based transformations are followed by AST transformations;
see :meth:`transform_ast`.
"""
Thomas Kluyver
Simpler mechanism to extend input transformations
r24400 # Static input transformations
cell = self.input_transformer_manager.transform_cell(raw_cell)
if len(cell.splitlines()) == 1:
# Dynamic transformations - only applied for single line commands
with self.builtin_trap:
# use prefilter_lines to handle trailing newlines
# restore trailing newline for ast.parse
cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
lines = cell.splitlines(keepends=True)
for transform in self.input_transformers_post:
lines = transform(lines)
cell = ''.join(lines)
return cell
Min RK
make `run_cell_async` a regular coroutine...
r24537
Thomas Kluyver
Add framework for AST transformations of input code.
r8220 def transform_ast(self, node):
"""Apply the AST transformations from self.ast_transformers
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Add framework for AST transformations of input code.
r8220 Parameters
----------
node : ast.Node
The root node to be transformed. Typically called with the ast.Module
produced by parsing user input.
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Thomas Kluyver
Add framework for AST transformations of input code.
r8220 Returns
-------
An ast.Node corresponding to the node it was called with. Note that it
may also modify the passed object, so don't rely on references to the
original AST.
"""
for transformer in self.ast_transformers:
try:
node = transformer.visit(node)
Scott Sanderson
DEV: AST transformers supplied to `InteractiveShell` can reject input....
r17798 except InputRejected:
# User-supplied AST transformers can reject an input by raising
# an InputRejected. Short-circuit in this case so that we
# don't unregister the transform.
raise
Thomas Kluyver
Add framework for AST transformations of input code.
r8220 except Exception:
Thomas Kluyver
Fix warning message for unregistering AST transformers.
r8222 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
Thomas Kluyver
Add framework for AST transformations of input code.
r8220 self.ast_transformers.remove(transformer)
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463
Thomas Kluyver
Don't call ast.fix_missing_locations unless the AST could have been modified....
r9482 if self.ast_transformers:
ast.fix_missing_locations(node)
return node
Bernardo B. Marques
remove all trailling spaces
r4872
Matthias Bussonnier
cleanup 3.8 compat
r25053 async def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 compiler=compile, result=None):
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 """Run a sequence of AST nodes. The execution mode depends on the
interactivity parameter.
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 Parameters
----------
nodelist : list
A sequence of AST nodes to run.
Thomas Kluyver
Change integer options to string options for interactivity.
r3533 cell_name : str
Will be passed to the compiler as the filename of the cell. Typically
the value returned by ip.compile.cache(cell).
interactivity : str
Matthias Bussonnier
Add new interactivity mode for ast....
r23730 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
specifying which nodes should be run interactively (displaying output
from expressions). 'last_expr' will run the last node interactively
only if it is an expression (i.e. expressions in loops or other blocks
are not displayed) 'last_expr_or_assign' will run the last expression
or the last assignment. Other values for this parameter will raise a
ValueError.
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463
Experimental value: 'async' Will try to run top level interactive
async/await code in default runner, this will not respect the
Min ho Kim
Fixed typos
r25167 interactivity setting and will only run the last node if it is an
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329 expression.
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463
Thomas Kluyver
Add shell_futures parameter to run_cell to allow running code without sharing __future__ imports.
r9081 compiler : callable
A function with the same interface as the built-in compile(), to turn
the AST nodes into code objects. Default is the built-in compile().
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 result : ExecutionResult, optional
An object to store exceptions that occur during execution.
Returns
-------
True if an exception occurred while running code, False if it finished
running.
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 """
if not nodelist:
return
Matthias Bussonnier
more work
r25024
Matthias Bussonnier
Add new interactivity mode for ast....
r23730 if interactivity == 'last_expr_or_assign':
if isinstance(nodelist[-1], _assign_nodes):
asg = nodelist[-1]
if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
target = asg.targets[0]
elif isinstance(asg, _single_targets_nodes):
target = asg.target
else:
target = None
if isinstance(target, ast.Name):
nnode = ast.Expr(ast.Name(target.id, ast.Load()))
ast.fix_missing_locations(nnode)
nodelist.append(nnode)
interactivity = 'last_expr'
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 _async = False
Thomas Kluyver
Make default evaluation run the last AST node only if it is an expression.
r3740 if interactivity == 'last_expr':
if isinstance(nodelist[-1], ast.Expr):
interactivity = "last"
else:
interactivity = "none"
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Change integer options to string options for interactivity.
r3533 if interactivity == 'none':
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 to_run_exec, to_run_interactive = nodelist, []
Thomas Kluyver
Change integer options to string options for interactivity.
r3533 elif interactivity == 'last':
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
Thomas Kluyver
Change integer options to string options for interactivity.
r3533 elif interactivity == 'all':
Thomas Kluyver
Add methods to run an IPython cell based on AST nodes. Have done basic testing manually.
r3527 to_run_exec, to_run_interactive = [], nodelist
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 elif interactivity == 'async':
Matthias Bussonnier
draft compat 3.8
r25019 to_run_exec, to_run_interactive = [], nodelist
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 _async = True
Thomas Kluyver
Change integer options to string options for interactivity.
r3533 else:
raise ValueError("Interactivity was %r" % interactivity)
Matthias Bussonnier
more work
r25024
Fernando Perez
Prevent crash from invalid code such as a bare 'return'....
r4566 try:
Matthias Bussonnier
clenup a bit
r25052 if _async and sys.version_info > (3,8):
raise ValueError("This branch should never happen on Python 3.8 and above, "
"please try to upgrade IPython and open a bug report with your case.")
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 if _async:
# If interactivity is async the semantics of run_code are
# completely different Skip usual machinery.
Matthias Bussonnier
Mock the new module API on <38 and ignore second argument....
r24921 mod = Module(nodelist, [])
async_wrapper_code = compiler(mod, cell_name, 'exec')
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 exec(async_wrapper_code, self.user_global_ns, self.user_ns)
async_code = removed_co_newlocals(self.user_ns.pop('async-def-wrapper')).__code__
Matthias Bussonnier
cleanup 3.8 compat
r25053 if (await self.run_code(async_code, result, async_=True)):
Fernando Perez
Prevent crash from invalid code such as a bare 'return'....
r4566 return True
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 else:
Matthias Bussonnier
clenup a bit
r25052 if sys.version_info > (3, 8):
def compare(code):
is_async = (inspect.CO_COROUTINE & code.co_flags == inspect.CO_COROUTINE)
return is_async
else:
def compare(code):
return _async
Matthias Bussonnier
more work
r25024
# refactor that to just change the mod constructor.
Matthias Bussonnier
clenup a bit
r25052 to_run = []
for node in to_run_exec:
to_run.append((node, 'exec'))
for node in to_run_interactive:
to_run.append((node, 'single'))
for node,mode in to_run:
if mode == 'exec':
mod = Module([node], [])
elif mode == 'single':
mod = ast.Interactive([node])
Matthias Bussonnier
more work
r25024 with compiler.extra_flags(getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0x0) if self.autoawait else 0x0):
Matthias Bussonnier
clenup a bit
r25052 code = compiler(mod, cell_name, mode)
Matthias Bussonnier
more work
r25024 asy = compare(code)
Matthias Bussonnier
cleanup 3.8 compat
r25053 if (await self.run_code(code, result, async_=asy)):
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 return True
Bradley M. Froehle
Delay flushing softspace until after an entire cell is run....
r6642
# Flush softspace
if softspace(sys.stdout, 0):
Matthias BUSSONNIER
use print function in module with `print >>`
r7817 print()
Bradley M. Froehle
Delay flushing softspace until after an entire cell is run....
r6642
Fernando Perez
Prevent crash from invalid code such as a bare 'return'....
r4566 except:
# It's possible to have exceptions raised here, typically by
# compilation of odd code (such as a naked 'return' outside a
# function) that did parse but isn't valid. Typically the exception
# is a SyntaxError, but it's safest just to catch anything and show
# the user a traceback.
# We do only one try/except outside the loop to minimize the impact
# on runtime, and also because if any node in the node list is
# broken, we should stop execution completely.
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 if result:
result.error_before_exec = sys.exc_info()[1]
Fernando Perez
Prevent crash from invalid code such as a bare 'return'....
r4566 self.showtraceback()
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 return True
MinRK
remove code_to_run attribute, updates per review....
r3737
return False
Bernardo B. Marques
remove all trailling spaces
r4872
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 def _async_exec(self, code_obj: types.CodeType, user_ns: dict):
"""
Evaluate an asynchronous code object using a code runner
Fake asynchronous execution of code_object in a namespace via a proxy namespace.
Returns coroutine object, which can be executed via async loop runner
WARNING: The semantics of `async_exec` are quite different from `exec`,
in particular you can only pass a single namespace. It also return a
handle to the value of the last things returned by code_object.
"""
return eval(code_obj, user_ns)
Matthias Bussonnier
cleanup 3.8 compat
r25053 async def run_code(self, code_obj, result=None, *, async_=False):
Ville M. Vainio
crlf -> lf
r1032 """Execute a code object.
When an exception occurs, self.showtraceback() is called to display a
traceback.
MinRK
fix %autopx in scripts by calling run_code for each ast node...
r3735 Parameters
----------
code_obj : code object
A compiled code object, to be executed
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 result : ExecutionResult, optional
An object to store exceptions that occur during execution.
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 async_ : Bool (Experimental)
Attempt to run top-level asynchronous code in a default loop.
Ville M. Vainio
crlf -> lf
r1032
MinRK
fix %autopx in scripts by calling run_code for each ast node...
r3735 Returns
-------
MinRK
remove code_to_run attribute, updates per review....
r3737 False : successful execution.
True : an error occurred.
Ville M. Vainio
crlf -> lf
r1032 """
Matthias Bussonnier
Implement understanding on __tracebackhide__...
r25839 # special value to say that anything above is IPython and should be
# hidden.
__tracebackhide__ = "__ipython_bottom__"
Ville M. Vainio
crlf -> lf
r1032 # Set our own excepthook in case the user code tries to call it
# directly, so that the IPython crash handler doesn't get triggered
Justyna Ilczuk
i1673 implementation of py3 proper error handling...
r17157 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
Ville M. Vainio
crlf -> lf
r1032
# 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
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 outflag = True # happens in more places, so it's easier as default
Ville M. Vainio
crlf -> lf
r1032 try:
try:
MinRK
merge interactiveshell.py
r3122 self.hooks.pre_run_code_hook()
Matthias Bussonnier
draft compat 3.8
r25019 if async_ and sys.version_info < (3,8):
Matthias Bussonnier
cleanup 3.8 compat
r25053 last_expr = (await self._async_exec(code_obj, self.user_ns))
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 code = compile('last_expr', 'fake', "single")
exec(code, {'last_expr': last_expr})
Matthias Bussonnier
draft compat 3.8
r25019 elif async_ :
Matthias Bussonnier
cleanup 3.8 compat
r25053 await eval(code_obj, self.user_global_ns, self.user_ns)
Matthias Bussonnier
Prototype async REPL using IPython, take III...
r24463 else:
exec(code_obj, self.user_global_ns, self.user_ns)
Ville M. Vainio
crlf -> lf
r1032 finally:
# Reset our crash handler in place
sys.excepthook = old_excepthook
Thomas Kluyver
run_cell returns an ExecutionResult instance...
r19630 except SystemExit as e:
Thomas Kluyver
Restore support for Python < 2.7.9...
r19689 if result is not None:
result.error_in_exec = e
Fernando Perez
Lots of work on exception handling, including tests for traceback printing....
r2440 self.showtraceback(exception_only=True)
Thomas Kluyver
Fix keyword argument to warn()...
r22691 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
Ville M. Vainio
crlf -> lf
r1032 except self.custom_exceptions:
Justyna Ilczuk
i1673 implementation of py3 proper error handling...
r17157 etype, value, tb = sys.exc_info()
Thomas Kluyver
Restore support for Python < 2.7.9...
r19689 if result is not None:
result.error_in_exec = value
Justyna Ilczuk
i1673 implementation of py3 proper error handling...
r17157 self.CustomTB(etype, value, tb)
Ville M. Vainio
crlf -> lf
r1032 except:
Thomas Kluyver
Restore support for Python < 2.7.9...
r19689 if result is not None:
result.error_in_exec = sys.exc_info()[1]
Piotr Zielinski
Verbose error message for syntax error occuring at runtime
r23611 self.showtraceback(running_compiled_code=True)
Ville M. Vainio
crlf -> lf
r1032 else:
Matthias Bussonnier
Cleanup some idioms in safe-exec
r23445 outflag = False
Ville M. Vainio
crlf -> lf
r1032 return outflag
Bernardo B. Marques
remove all trailling spaces
r4872
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
Matthias Bussonnier
Fix the sphinx_ipython directive....
r24591 def check_complete(self, code: str) -> Tuple[str, str]:
Thomas Kluyver
Add shell.check_complete() method...
r24180 """Return whether a block of code is ready to execute, or should be continued
Parameters
----------
source : string
Python input code, which can be multiline.
Returns
-------
status : str
One of 'complete', 'incomplete', or 'invalid' if source is not a
prefix of valid code.
indent : str
When status is 'incomplete', this is some whitespace to insert on
the next line of the prompt.
"""
status, nspaces = self.input_transformer_manager.check_complete(code)
return status, ' ' * (nspaces or 0)
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
Thomas Kluyver
Let IPython.lib.guisupport detect terminal-integrated event loops...
r22913 active_eventloop = None
Fernando Perez
Refactor gui/pylab integration to eliminate code duplication....
r5469 def enable_gui(self, gui=None):
raise NotImplementedError('Implement enable_gui in a subclass')
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 def enable_matplotlib(self, gui=None):
"""Enable interactive matplotlib and inline figure support.
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 This takes the following steps:
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 1. select the appropriate eventloop and matplotlib backend
2. set up matplotlib for interactive use with that backend
3. configure formatters for inline figure display
4. enable the selected gui eventloop
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 Parameters
----------
gui : optional, string
If given, dictates the choice of matplotlib GUI backend to use
(should be one of IPython's supported backends, 'qt', 'osx', 'tk',
'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
matplotlib (as dictated by the matplotlib build-time options plus the
user's matplotlibrc configuration file). Note that not all backends
make sense in all contexts, for example a terminal ipython can't
display figures inline.
"""
from IPython.core import pylabtools as pt
martinRenou
Use matplotlib-inline instead of ipykernel.pylab
r26464 from matplotlib_inline.backend_inline import configure_inline_support
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 if gui != 'inline':
# If we have our first gui selection, store it
if self.pylab_gui_select is None:
self.pylab_gui_select = gui
# Otherwise if they are different
elif gui != self.pylab_gui_select:
Matthias Bussonnier
Add new interactivity mode for ast....
r23730 print('Warning: Cannot change to a different GUI toolkit: %s.'
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 ' Using %s instead.' % (gui, self.pylab_gui_select))
gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 pt.activate_matplotlib(backend)
martinRenou
Use matplotlib-inline instead of ipykernel.pylab
r26464 configure_inline_support(self, backend)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 # Now we must activate the gui pylab wants to use, and fix %run to take
# plot updates into account
self.enable_gui(gui)
self.magics_manager.registry['ExecutionMagics'].default_runner = \
pt.mpl_runner(self.safe_execfile)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 return gui, backend
Fernando Perez
Refactor gui/pylab integration to eliminate code duplication....
r5469
Aaron Meurer
Add welcome_message option to enable_pylab...
r8229 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
Fernando Perez
Refactor gui/pylab integration to eliminate code duplication....
r5469 """Activate pylab support at runtime.
This turns on support for matplotlib, preloads into the interactive
namespace all of numpy and pylab, and configures IPython to correctly
interact with the GUI event loop. The GUI backend to be used can be
Thomas Kluyver
Miscellaneous docs fixes
r9244 optionally selected with the optional ``gui`` argument.
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
Fernando Perez
Refactor gui/pylab integration to eliminate code duplication....
r5469
Parameters
----------
gui : optional, string
If given, dictates the choice of matplotlib GUI backend to use
(should be one of IPython's supported backends, 'qt', 'osx', 'tk',
'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
matplotlib (as dictated by the matplotlib build-time options plus the
user's matplotlibrc configuration file). Note that not all backends
make sense in all contexts, for example a terminal ipython can't
display figures inline.
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 import_all : optional, bool, default: True
Whether to do `from numpy import *` and `from pylab import *`
in addition to module imports.
welcome_message : deprecated
This argument is ignored, no welcome message will be displayed.
Fernando Perez
Refactor gui/pylab integration to eliminate code duplication....
r5469 """
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 from IPython.core.pylabtools import import_pylab
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 gui, backend = self.enable_matplotlib(gui)
martinRenou
Allow passing a custom CachingCompiler to the interactive shell...
r26329
Fernando Perez
Refactor gui/pylab integration to eliminate code duplication....
r5469 # We want to prevent the loading of pylab to pollute the user's
# namespace as shown by the %who* magics, so we execute the activation
# code in an empty namespace, and we update *both* user_ns and
# user_ns_hidden with this information.
ns = {}
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 import_pylab(ns, import_all)
MinRK
warn about names clobbered by `%pylab`
r11325 # warn about clobbered names
Rémy Léone
Set litteral
r21804 ignored = {"__builtins__"}
MinRK
warn about names clobbered by `%pylab`
r11325 both = set(ns).intersection(self.user_ns).difference(ignored)
clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
Fernando Perez
Refactor gui/pylab integration to eliminate code duplication....
r5469 self.user_ns.update(ns)
self.user_ns_hidden.update(ns)
MinRK
add `%matplotlib` and `shell.enable_matplotlib`...
r11328 return gui, backend, clobbered
Brian Granger
More re-organization of InteractiveShell.
r2242
#-------------------------------------------------------------------------
# Utilities
#-------------------------------------------------------------------------
Thomas Kluyver
Use DollarFormatter to fill in names in ! shell calls....
r5355 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
Brian Granger
Massive, crazy refactoring of everything....
r2202 """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.
"""
Thomas Kluyver
Use DollarFormatter to fill in names in ! shell calls....
r5355 ns = self.user_ns.copy()
Thomas Kluyver
Allow run_line_magic to be called from scripts...
r18937 try:
frame = sys._getframe(depth+1)
except ValueError:
# This is thrown if there aren't that many frames on the stack,
# e.g. if a script called run_line_magic() directly.
pass
else:
ns.update(frame.f_locals)
MinRK
ignore errors in shell.var_expand...
r6124 try:
Thomas Kluyver
Fix variable expansion on 'self'...
r8225 # We have to use .vformat() here, because 'self' is a valid and common
# name, and expanding **ns for .format() would make it collide with
# the 'self' argument of the method.
cmd = formatter.vformat(cmd, args=[], kwargs=ns)
MinRK
ignore errors in shell.var_expand...
r6124 except Exception:
# if formatter couldn't format, just let it go untransformed
pass
return cmd
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.
Matthias BUSSONNIER
avoid import of nearby temporary with %edit...
r14683 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
but it registers the created filename internally so ipython cleans it up
at exit time.
Ville M. Vainio
crlf -> lf
r1032
Optional inputs:
- data(None): if data is given, it gets written out to the temp file
Thomas Kluyver
Improvements to docs formatting.
r12553 immediately, and the file is closed again."""
Ville M. Vainio
crlf -> lf
r1032
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 dir_path = Path(tempfile.mkdtemp(prefix=prefix))
self.tempdirs.append(dir_path)
Matthias BUSSONNIER
avoid import of nearby temporary with %edit...
r14683
bar-hen
Run darker to fix formatting problems
r26062 handle, filename = tempfile.mkstemp(".py", prefix, dir=str(dir_path))
Thomas Kluyver
Close handle on new temporary files before returning filename...
r17337 os.close(handle) # On Windows, there can only be one open handle on a file
bar-hen
Run darker to fix formatting problems
r26062
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 file_path = Path(filename)
self.tempfiles.append(file_path)
Bernardo B. Marques
remove all trailling spaces
r4872
Ville M. Vainio
crlf -> lf
r1032 if data:
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 file_path.write_text(data)
Ville M. Vainio
crlf -> lf
r1032 return filename
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 @undoc
Ville M. Vainio
crlf -> lf
r1032 def write(self,data):
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 """DEPRECATED: Write a string to the default output"""
warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
DeprecationWarning, stacklevel=2)
sys.stdout.write(data)
Ville M. Vainio
crlf -> lf
r1032
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 @undoc
Ville M. Vainio
crlf -> lf
r1032 def write_err(self,data):
Thomas Kluyver
Deprecate io.{stdout,stderr} and shell.{write,write_err}...
r22192 """DEPRECATED: Write a string to the default error output"""
warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
DeprecationWarning, stacklevel=2)
sys.stderr.write(data)
Ville M. Vainio
crlf -> lf
r1032
Yuri Numerov
fixed exit confirmation glitch
r21622 def ask_yes_no(self, prompt, default=None, interrupt=None):
Brian Granger
More re-organization of InteractiveShell.
r2242 if self.quiet:
return True
Yuri Numerov
fixed exit confirmation glitch
r21622 return ask_yes_no(prompt,default,interrupt)
Bernardo B. Marques
remove all trailling spaces
r4872
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)
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Move extract_input_lines to main shell object, where it belongs.
r6914 def extract_input_lines(self, range_str, raw=False):
"""Return as a string a set of input history slices.
Parameters
----------
Blazej Michalik
Docs: fix wrong arg type in `extract_input_lines`
r26634 range_str : str
Fernando Perez
Move extract_input_lines to main shell object, where it belongs.
r6914 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
since this function is for use by magic functions which get their
arguments as strings. The number before the / is the session
number: ~n goes n back from the current session.
Blazej Michalik
Don't return the last line in `find_user_code`...
r26631 If empty string is given, returns history of current session
without the last input.
Thomas Kluyver
Clean up numpydoc section headers
r13587 raw : bool, optional
By default, the processed input is used. If this is true, the raw
input history is used instead.
Fernando Perez
Move extract_input_lines to main shell object, where it belongs.
r6914
Thomas Kluyver
Clean up numpydoc section headers
r13587 Notes
-----
Fernando Perez
Move extract_input_lines to main shell object, where it belongs.
r6914
Thomas Kluyver
Clean up numpydoc section headers
r13587 Slices can be described with two notations:
Fernando Perez
Move extract_input_lines to main shell object, where it belongs.
r6914
Thomas Kluyver
Clean up numpydoc section headers
r13587 * ``N:M`` -> standard python form, means including items N...(M-1).
* ``N-M`` -> include items N..M (closed endpoint).
Thomas Kluyver
Improvements to docs formatting.
r12553 """
Fernando Perez
Move extract_input_lines to main shell object, where it belongs.
r6914 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
Blazej Michalik
Don't return the last line in `find_user_code`...
r26631 text = "\n".join(x for _, _, x in lines)
# Skip the last line, as it's probably the magic that called this
if not range_str:
if '\n' not in text:
text = ''
else:
text = text[:text.rfind('\n')]
return text
Fernando Perez
Move extract_input_lines to main shell object, where it belongs.
r6914
George Titsworth
Added new capability to the `%load` magic to search the user's namespace for modules, classes, or functions and inspects those to load source....
r16318 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
Matthias BUSSONNIER
find_user_code improvement for not py-files...
r6774 """Get a code string from history, file, url, or a string or macro.
Bernardo B. Marques
remove all trailling spaces
r4872
This is mainly used by magic functions.
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 Parameters
----------
target : str
A string specifying code to retrieve. This will be tried respectively
Matthias BUSSONNIER
make pycat and loadpy aware of history and more...
r6761 as: ranges of input history (see %history for syntax), url,
Thomas Ballinger
fix typos in docstrings
r21859 corresponding .py file, filename, or an expression evaluating to a
Matthias BUSSONNIER
make pycat and loadpy aware of history and more...
r6761 string or Macro in the user namespace.
Blazej Michalik
Don't return the last line in `find_user_code`...
r26631 If empty string is given, returns complete history of current
session, without the last line.
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 raw : bool
If true (default), retrieve raw history. Has no effect on the other
retrieval mechanisms.
Bernardo B. Marques
remove all trailling spaces
r4872
Matthias BUSSONNIER
find_user_code binary fallback
r6775 py_only : bool (default False)
Matthias BUSSONNIER
find_user_code improvement for not py-files...
r6774 Only try to fetch python code, do not try alternative methods to decode file
if unicode fails.
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 Returns
-------
A string of code.
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 ValueError is raised if nothing is found, and TypeError if it evaluates
to an object of another type. In each case, .args[0] is a printable
message.
"""
Bernardo B. Marques
remove all trailling spaces
r4872 code = self.extract_input_lines(target, raw=raw) # Grab history
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 if code:
return code
Matthias BUSSONNIER
use openpy, and catch non-responding URL
r6763 try:
Antony Lee
On Windows, quote paths instead of escaping them.
r22418 if target.startswith(('http://', 'https://')):
return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
Ram Rachum
Fix exception causes in 7 modules
r25827 except UnicodeDecodeError as e:
Matthias BUSSONNIER
find_user_code improvement for not py-files...
r6774 if not py_only :
Sean Vig
Fix Python 3 handling of urllib...
r13640 # Deferred import
Srinivas Reddy Thatiparthy
remove python 2.x specific urllib2's functions
r23075 from urllib.request import urlopen
Thomas Kluyver
Defer import of urllib
r9389 response = urlopen(target)
Matthias BUSSONNIER
remove TextIOWrapper, use strig mode for load options
r6895 return response.read().decode('latin1')
Ram Rachum
Fix exception causes in 7 modules
r25827 raise ValueError(("'%s' seem to be unreadable.") % target) from e
Matthias BUSSONNIER
make pycat and loadpy aware of history and more...
r6761
Matthias BUSSONNIER
share code for file and py_file
r6778 potential_target = [target]
Matthias BUSSONNIER
make pycat and loadpy aware of history and more...
r6761 try :
Matthias BUSSONNIER
share code for file and py_file
r6778 potential_target.insert(0,get_py_filename(target))
Matthias BUSSONNIER
make pycat and loadpy aware of history and more...
r6761 except IOError:
pass
Matthias BUSSONNIER
share code for file and py_file
r6778
for tgt in potential_target :
if os.path.isfile(tgt): # Read file
try :
Jörgen Stenarson
Make magic pycat print encoding_cookie
r8334 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
Ram Rachum
Fix exception causes in 7 modules
r25827 except UnicodeDecodeError as e:
Matthias BUSSONNIER
share code for file and py_file
r6778 if not py_only :
with io_open(tgt,'r', encoding='latin1') as f :
return f.read()
Ram Rachum
Fix exception causes in 7 modules
r25827 raise ValueError(("'%s' seem to be unreadable.") % target) from e
Paul Ivanov
informative error when trying to load directories...
r10348 elif os.path.isdir(os.path.expanduser(tgt)):
raise ValueError("'%s' is a directory, not a regular file." % target)
Bernardo B. Marques
remove all trailling spaces
r4872
George Titsworth
Added new capability to the `%load` magic to search the user's namespace for modules, classes, or functions and inspects those to load source....
r16318 if search_ns:
George Titsworth
Reworking object look up code to use existing inspect functionality.
r16353 # Inspect namespace to load object source
object_info = self.object_inspect(target, detail_level=1)
if object_info['found'] and object_info['source']:
return object_info['source']
George Titsworth
Added new capability to the `%load` magic to search the user's namespace for modules, classes, or functions and inspects those to load source....
r16318
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 try: # User namespace
codeobj = eval(target, self.user_ns)
Ram Rachum
Fix exception causes in 7 modules
r25827 except Exception as e:
Matthias BUSSONNIER
share code for file and py_file
r6778 raise ValueError(("'%s' was not found in history, as a file, url, "
Ram Rachum
Fix exception causes in 7 modules
r25827 "nor in the user namespace.") % target) from e
George Titsworth
Added new capability to the `%load` magic to search the user's namespace for modules, classes, or functions and inspects those to load source....
r16318
Srinivas Reddy Thatiparthy
convert string_types to str
r23037 if isinstance(codeobj, str):
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 return codeobj
elif isinstance(codeobj, Macro):
return codeobj.value
Bernardo B. Marques
remove all trailling spaces
r4872
Thomas Kluyver
Move _get_some_code method to InteractiveShell object; improve docstring.
r3509 raise TypeError("%s is neither a string nor a macro." % target,
codeobj)
Brian Granger
More re-organization of InteractiveShell.
r2242
Matthias Bussonnier
Finish fixing the at-exit spurious failures....
r26428 def _atexit_once(self):
"""
At exist operation that need to be called at most once.
Second call to this function per instance will do nothing.
"""
if not getattr(self, "_atexit_once_called", False):
self._atexit_once_called = True
# Clear all user namespaces to release all references cleanly.
self.reset(new_session=False)
# Close the history session (this stores the end time and line count)
# this must be *before* the tempfile cleanup, in case of temporary
# history db
self.history_manager.end_session()
self.history_manager = None
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
Bernardo B. Marques
remove all trailling spaces
r4872 clutter
Fernando Perez
Fix bug where atexit operations were only done if readline was present.
r2953 """
Matthias Bussonnier
Finish fixing the at-exit spurious failures....
r26428 self._atexit_once()
Bernardo B. Marques
remove all trailling spaces
r4872
Matthias BUSSONNIER
avoid import of nearby temporary with %edit...
r14683 # Cleanup all tempfiles and folders left around
Brian Granger
More re-organization of InteractiveShell.
r2242 for tfile in self.tempfiles:
try:
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 tfile.unlink()
Matthias Bussonnier
Cleaner shutdown...
r26427 self.tempfiles.remove(tfile)
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 except FileNotFoundError:
Brian Granger
More re-organization of InteractiveShell.
r2242 pass
Matthias Bussonnier
Cleaner shutdown...
r26427 del self.tempfiles
Matthias BUSSONNIER
avoid import of nearby temporary with %edit...
r14683 for tdir in self.tempdirs:
try:
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 tdir.rmdir()
Matthias Bussonnier
Cleaner shutdown...
r26427 self.tempdirs.remove(tdir)
bar-hen
Chaged tempfiles and tempdire to be Path from Pathlib
r26061 except FileNotFoundError:
Matthias BUSSONNIER
avoid import of nearby temporary with %edit...
r14683 pass
Matthias Bussonnier
Cleaner shutdown...
r26427 del self.tempdirs
Matthias BUSSONNIER
avoid import of nearby temporary with %edit...
r14683
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
Thomas Kluyver
Switch prompts for doctest_mode
r22429 # Overridden in terminal subclass to change prompts
def switch_doctest_mode(self, mode):
pass
Thomas Kluyver
Remove uses of with_metaclass compatibility hack
r23071 class InteractiveShellABC(metaclass=abc.ABCMeta):
Brian Granger
Finishing work on configurables, plugins and extensions.
r2738 """An abstract base class for InteractiveShell."""
InteractiveShellABC.register(InteractiveShell)