aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/ipython/py2/IPython
diff options
context:
space:
mode:
authorNikita Slyusarev <nslus@yandex-team.com>2022-02-10 16:46:52 +0300
committerDaniil Cherednik <dcherednik@yandex-team.ru>2022-02-10 16:46:52 +0300
commitcd77cecfc03a3eaf87816af28a33067c4f0cdb59 (patch)
tree1308e0bae862d52e0020d881fe758080437fe389 /contrib/python/ipython/py2/IPython
parentcdae02d225fb5b3afbb28990e79a7ac6c9125327 (diff)
downloadydb-cd77cecfc03a3eaf87816af28a33067c4f0cdb59.tar.gz
Restoring authorship annotation for Nikita Slyusarev <nslus@yandex-team.com>. Commit 1 of 2.
Diffstat (limited to 'contrib/python/ipython/py2/IPython')
-rw-r--r--contrib/python/ipython/py2/IPython/core/alias.py6
-rw-r--r--contrib/python/ipython/py2/IPython/core/application.py162
-rw-r--r--contrib/python/ipython/py2/IPython/core/builtin_trap.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/completer.py208
-rw-r--r--contrib/python/ipython/py2/IPython/core/completerlib.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/debugger.py120
-rw-r--r--contrib/python/ipython/py2/IPython/core/display.py118
-rw-r--r--contrib/python/ipython/py2/IPython/core/displayhook.py28
-rw-r--r--contrib/python/ipython/py2/IPython/core/displaypub.py16
-rw-r--r--contrib/python/ipython/py2/IPython/core/events.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/excolors.py60
-rw-r--r--contrib/python/ipython/py2/IPython/core/extensions.py18
-rw-r--r--contrib/python/ipython/py2/IPython/core/formatters.py68
-rw-r--r--contrib/python/ipython/py2/IPython/core/history.py132
-rw-r--r--contrib/python/ipython/py2/IPython/core/historyapp.py26
-rw-r--r--contrib/python/ipython/py2/IPython/core/hooks.py26
-rw-r--r--contrib/python/ipython/py2/IPython/core/interactiveshell.py636
-rw-r--r--contrib/python/ipython/py2/IPython/core/magic.py16
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/auto.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/basic.py28
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/code.py74
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/config.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/display.py32
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/execution.py122
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/history.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/logging.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/osm.py8
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/pylab.py2
-rw-r--r--contrib/python/ipython/py2/IPython/core/magics/script.py16
-rw-r--r--contrib/python/ipython/py2/IPython/core/oinspect.py356
-rw-r--r--contrib/python/ipython/py2/IPython/core/page.py34
-rw-r--r--contrib/python/ipython/py2/IPython/core/prefilter.py44
-rw-r--r--contrib/python/ipython/py2/IPython/core/profileapp.py22
-rw-r--r--contrib/python/ipython/py2/IPython/core/profiledir.py34
-rw-r--r--contrib/python/ipython/py2/IPython/core/prompts.py4
-rw-r--r--contrib/python/ipython/py2/IPython/core/pylabtools.py8
-rw-r--r--contrib/python/ipython/py2/IPython/core/release.py6
-rw-r--r--contrib/python/ipython/py2/IPython/core/shellapp.py108
-rw-r--r--contrib/python/ipython/py2/IPython/core/ultratb.py108
-rw-r--r--contrib/python/ipython/py2/IPython/core/usage.py12
-rw-r--r--contrib/python/ipython/py2/IPython/extensions/storemagic.py8
-rw-r--r--contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py6
-rw-r--r--contrib/python/ipython/py2/IPython/lib/backgroundjobs.py2
-rw-r--r--contrib/python/ipython/py2/IPython/lib/deepreload.py8
-rw-r--r--contrib/python/ipython/py2/IPython/lib/demo.py28
-rw-r--r--contrib/python/ipython/py2/IPython/lib/display.py2
-rw-r--r--contrib/python/ipython/py2/IPython/lib/inputhook.py230
-rw-r--r--contrib/python/ipython/py2/IPython/lib/latextools.py34
-rw-r--r--contrib/python/ipython/py2/IPython/lib/lexers.py20
-rw-r--r--contrib/python/ipython/py2/IPython/lib/pretty.py38
-rw-r--r--contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py2
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/debugger.py148
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/embed.py66
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/interactiveshell.py706
-rwxr-xr-xcontrib/python/ipython/py2/IPython/terminal/ipapp.py54
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/magics.py410
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/prompts.py140
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py84
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py282
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py118
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py24
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py274
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py136
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py54
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py190
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py296
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/ptshell.py16
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/ptutils.py206
-rw-r--r--contrib/python/ipython/py2/IPython/terminal/shortcuts.py374
-rw-r--r--contrib/python/ipython/py2/IPython/testing/decorators.py4
-rw-r--r--contrib/python/ipython/py2/IPython/testing/globalipapp.py18
-rw-r--r--contrib/python/ipython/py2/IPython/testing/iptest.py10
-rw-r--r--contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py16
-rw-r--r--contrib/python/ipython/py2/IPython/testing/skipdoctest.py10
-rw-r--r--contrib/python/ipython/py2/IPython/testing/tools.py16
-rw-r--r--contrib/python/ipython/py2/IPython/utils/PyColorize.py86
-rw-r--r--contrib/python/ipython/py2/IPython/utils/_process_common.py18
-rw-r--r--contrib/python/ipython/py2/IPython/utils/colorable.py52
-rw-r--r--contrib/python/ipython/py2/IPython/utils/contexts.py22
-rw-r--r--contrib/python/ipython/py2/IPython/utils/dir2.py72
-rw-r--r--contrib/python/ipython/py2/IPython/utils/io.py40
-rw-r--r--contrib/python/ipython/py2/IPython/utils/path.py18
-rw-r--r--contrib/python/ipython/py2/IPython/utils/py3compat.py4
-rw-r--r--contrib/python/ipython/py2/IPython/utils/terminal.py16
-rw-r--r--contrib/python/ipython/py2/IPython/utils/text.py14
-rw-r--r--contrib/python/ipython/py2/IPython/utils/tokenutil.py2
-rw-r--r--contrib/python/ipython/py2/IPython/utils/warn.py38
87 files changed, 3546 insertions, 3546 deletions
diff --git a/contrib/python/ipython/py2/IPython/core/alias.py b/contrib/python/ipython/py2/IPython/core/alias.py
index 28a9ccb00d..be4e7eebed 100644
--- a/contrib/python/ipython/py2/IPython/core/alias.py
+++ b/contrib/python/ipython/py2/IPython/core/alias.py
@@ -29,7 +29,7 @@ from IPython.core.error import UsageError
from IPython.utils.py3compat import string_types
from traitlets import List, Instance
-from logging import error
+from logging import error
#-----------------------------------------------------------------------------
# Utilities
@@ -192,8 +192,8 @@ class Alias(object):
class AliasManager(Configurable):
- default_aliases = List(default_aliases()).tag(config=True)
- user_aliases = List(default_value=[]).tag(config=True)
+ default_aliases = List(default_aliases()).tag(config=True)
+ user_aliases = List(default_value=[]).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None, **kwargs):
diff --git a/contrib/python/ipython/py2/IPython/core/application.py b/contrib/python/ipython/py2/IPython/core/application.py
index af28133945..32983540e7 100644
--- a/contrib/python/ipython/py2/IPython/core/application.py
+++ b/contrib/python/ipython/py2/IPython/core/application.py
@@ -13,7 +13,7 @@ object and then create the configurable objects, passing the config to them.
# Distributed under the terms of the Modified BSD License.
import atexit
-from copy import deepcopy
+from copy import deepcopy
import glob
import logging
import os
@@ -27,10 +27,10 @@ from IPython.core.profiledir import ProfileDir, ProfileDirError
from IPython.paths import get_ipython_dir, get_ipython_package_dir
from IPython.utils.path import ensure_dir_exists
from IPython.utils import py3compat
-from traitlets import (
- List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
- default, observe,
-)
+from traitlets import (
+ List, Unicode, Type, Bool, Dict, Set, Instance, Undefined,
+ default, observe,
+)
if os.name == 'nt':
programdata = os.environ.get('PROGRAMDATA', None)
@@ -52,16 +52,16 @@ if _env_config_dir not in SYSTEM_CONFIG_DIRS:
ENV_CONFIG_DIRS.append(_env_config_dir)
-_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
-if _envvar in {None, ''}:
- IPYTHON_SUPPRESS_CONFIG_ERRORS = None
-else:
- if _envvar.lower() in {'1','true'}:
- IPYTHON_SUPPRESS_CONFIG_ERRORS = True
- elif _envvar.lower() in {'0','false'} :
- IPYTHON_SUPPRESS_CONFIG_ERRORS = False
- else:
- sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
+_envvar = os.environ.get('IPYTHON_SUPPRESS_CONFIG_ERRORS')
+if _envvar in {None, ''}:
+ IPYTHON_SUPPRESS_CONFIG_ERRORS = None
+else:
+ if _envvar.lower() in {'1','true'}:
+ IPYTHON_SUPPRESS_CONFIG_ERRORS = True
+ elif _envvar.lower() in {'0','false'} :
+ IPYTHON_SUPPRESS_CONFIG_ERRORS = False
+ else:
+ sys.exit("Unsupported value for environment variable: 'IPYTHON_SUPPRESS_CONFIG_ERRORS' is set to '%s' which is none of {'0', '1', 'false', 'true', ''}."% _envvar )
# aliases and flags
@@ -118,13 +118,13 @@ class BaseIPythonApplication(Application):
config_file_specified = Set()
config_file_name = Unicode()
- @default('config_file_name')
+ @default('config_file_name')
def _config_file_name_default(self):
return self.name.replace('-','_') + u'_config.py'
- @observe('config_file_name')
- def _config_file_name_changed(self, change):
- if change['new'] != change['old']:
- self.config_file_specified.add(change['new'])
+ @observe('config_file_name')
+ def _config_file_name_changed(self, change):
+ if change['new'] != change['old']:
+ self.config_file_specified.add(change['new'])
# The directory that contains IPython's builtin profiles.
builtin_profile_dir = Unicode(
@@ -132,19 +132,19 @@ class BaseIPythonApplication(Application):
)
config_file_paths = List(Unicode())
- @default('config_file_paths')
+ @default('config_file_paths')
def _config_file_paths_default(self):
return [py3compat.getcwd()]
- extra_config_file = Unicode(
+ extra_config_file = Unicode(
help="""Path to an extra config file to load.
If specified, load this config file in addition to any other IPython config.
- """).tag(config=True)
- @observe('extra_config_file')
- def _extra_config_file_changed(self, change):
- old = change['old']
- new = change['new']
+ """).tag(config=True)
+ @observe('extra_config_file')
+ def _extra_config_file_changed(self, change):
+ old = change['old']
+ new = change['new']
try:
self.config_files.remove(old)
except ValueError:
@@ -152,37 +152,37 @@ class BaseIPythonApplication(Application):
self.config_file_specified.add(new)
self.config_files.append(new)
- profile = Unicode(u'default',
+ profile = Unicode(u'default',
help="""The IPython profile to use."""
- ).tag(config=True)
-
- @observe('profile')
- def _profile_changed(self, change):
+ ).tag(config=True)
+
+ @observe('profile')
+ def _profile_changed(self, change):
self.builtin_profile_dir = os.path.join(
- get_ipython_package_dir(), u'config', u'profile', change['new']
+ get_ipython_package_dir(), u'config', u'profile', change['new']
)
- ipython_dir = Unicode(
+ ipython_dir = Unicode(
help="""
The name of the IPython directory. This directory is used for logging
configuration (through profiles), history storage, etc. The default
is usually $HOME/.ipython. This option can also be specified through
the environment variable IPYTHONDIR.
"""
- ).tag(config=True)
- @default('ipython_dir')
+ ).tag(config=True)
+ @default('ipython_dir')
def _ipython_dir_default(self):
d = get_ipython_dir()
- self._ipython_dir_changed({
- 'name': 'ipython_dir',
- 'old': d,
- 'new': d,
- })
+ self._ipython_dir_changed({
+ 'name': 'ipython_dir',
+ 'old': d,
+ 'new': d,
+ })
return d
_in_init_profile_dir = False
profile_dir = Instance(ProfileDir, allow_none=True)
- @default('profile_dir')
+ @default('profile_dir')
def _profile_dir_default(self):
# avoid recursion
if self._in_init_profile_dir:
@@ -191,29 +191,29 @@ class BaseIPythonApplication(Application):
self.init_profile_dir()
return self.profile_dir
- overwrite = Bool(False,
- help="""Whether to overwrite existing config files when copying"""
- ).tag(config=True)
- auto_create = Bool(False,
- help="""Whether to create profile dir if it doesn't exist"""
- ).tag(config=True)
+ overwrite = Bool(False,
+ help="""Whether to overwrite existing config files when copying"""
+ ).tag(config=True)
+ auto_create = Bool(False,
+ help="""Whether to create profile dir if it doesn't exist"""
+ ).tag(config=True)
config_files = List(Unicode())
- @default('config_files')
+ @default('config_files')
def _config_files_default(self):
return [self.config_file_name]
- copy_config_files = Bool(False,
+ copy_config_files = Bool(False,
help="""Whether to install the default config files into the profile dir.
If a new profile is being created, and IPython contains config files for that
profile, then they will be staged into the new directory. Otherwise,
default config files will be automatically generated.
- """).tag(config=True)
+ """).tag(config=True)
- verbose_crash = Bool(False,
+ verbose_crash = Bool(False,
help="""Create a massive crash report when IPython encounters what may be an
internal error. The default is to append a short message to the
- usual traceback""").tag(config=True)
+ usual traceback""").tag(config=True)
# The class to use as the crash handler.
crash_handler_class = Type(crashhandler.CrashHandler)
@@ -239,8 +239,8 @@ class BaseIPythonApplication(Application):
if subc in self.deprecated_subcommands:
self.log.warning("Subcommand `ipython {sub}` is deprecated and will be removed "
"in future versions.".format(sub=subc))
- self.log.warning("You likely want to use `jupyter {sub}` in the "
- "future".format(sub=subc))
+ self.log.warning("You likely want to use `jupyter {sub}` in the "
+ "future".format(sub=subc))
return super(BaseIPythonApplication, self).initialize_subcommand(subc, argv)
def init_crash_handler(self):
@@ -262,11 +262,11 @@ class BaseIPythonApplication(Application):
return self.crash_handler(etype, evalue, tb)
else:
return crashhandler.crash_handler_lite(etype, evalue, tb)
-
- @observe('ipython_dir')
- def _ipython_dir_changed(self, change):
- old = change['old']
- new = change['new']
+
+ @observe('ipython_dir')
+ def _ipython_dir_changed(self, change):
+ old = change['old']
+ new = change['new']
if old is not Undefined:
str_old = py3compat.cast_bytes_py2(os.path.abspath(old),
sys.getfilesystemencoding()
@@ -291,33 +291,33 @@ class BaseIPythonApplication(Application):
self.log.error("couldn't create path %s: %s", path, e)
self.log.debug("IPYTHONDIR set to: %s" % new)
- def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
+ def load_config_file(self, suppress_errors=IPYTHON_SUPPRESS_CONFIG_ERRORS):
"""Load the config file.
By default, errors in loading config are handled, and a warning
printed on screen. For testing, the suppress_errors option is set
to False, so errors will make tests fail.
-
- `supress_errors` default value is to be `None` in which case the
- behavior default to the one of `traitlets.Application`.
-
- The default value can be set :
- - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
- - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
- - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
-
- Any other value are invalid, and will make IPython exit with a non-zero return code.
+
+ `supress_errors` default value is to be `None` in which case the
+ behavior default to the one of `traitlets.Application`.
+
+ The default value can be set :
+ - to `False` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '0', or 'false' (case insensitive).
+ - to `True` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '1' or 'true' (case insensitive).
+ - to `None` by setting 'IPYTHON_SUPPRESS_CONFIG_ERRORS' environment variable to '' (empty string) or leaving it unset.
+
+ Any other value are invalid, and will make IPython exit with a non-zero return code.
"""
-
-
+
+
self.log.debug("Searching path %s for config files", self.config_file_paths)
base_config = 'ipython_config.py'
self.log.debug("Attempting to load config file: %s" %
base_config)
try:
- if suppress_errors is not None:
- old_value = Application.raise_config_file_errors
- Application.raise_config_file_errors = not suppress_errors;
+ if suppress_errors is not None:
+ old_value = Application.raise_config_file_errors
+ Application.raise_config_file_errors = not suppress_errors;
Application.load_config_file(
self,
base_config,
@@ -327,8 +327,8 @@ class BaseIPythonApplication(Application):
# ignore errors loading parent
self.log.debug("Config file %s not found", base_config)
pass
- if suppress_errors is not None:
- Application.raise_config_file_errors = old_value
+ if suppress_errors is not None:
+ Application.raise_config_file_errors = old_value
for config_file_name in self.config_files:
if not config_file_name or config_file_name == base_config:
@@ -457,9 +457,9 @@ class BaseIPythonApplication(Application):
if self.subapp is not None:
# stop here if subapp is taking over
return
- # save a copy of CLI config to re-load after config files
- # so that it has highest priority
- cl_config = deepcopy(self.config)
+ # save a copy of CLI config to re-load after config files
+ # so that it has highest priority
+ cl_config = deepcopy(self.config)
self.init_profile_dir()
self.init_config_files()
self.load_config_file()
diff --git a/contrib/python/ipython/py2/IPython/core/builtin_trap.py b/contrib/python/ipython/py2/IPython/core/builtin_trap.py
index 909a555c73..ff857be949 100644
--- a/contrib/python/ipython/py2/IPython/core/builtin_trap.py
+++ b/contrib/python/ipython/py2/IPython/core/builtin_trap.py
@@ -57,7 +57,7 @@ class BuiltinTrap(Configurable):
from IPython.lib import deepreload
if self.shell.deep_reload:
from warnings import warn
- warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated since IPython 4.0, please import `reload` explicitly from `IPython.lib.deepreload", DeprecationWarning)
+ warn("Automatically replacing builtin `reload` by `deepreload.reload` is deprecated since IPython 4.0, please import `reload` explicitly from `IPython.lib.deepreload", DeprecationWarning)
self.auto_builtins['reload'] = deepreload._dreload
else:
self.auto_builtins['dreload']= deepreload._dreload
diff --git a/contrib/python/ipython/py2/IPython/core/completer.py b/contrib/python/ipython/py2/IPython/core/completer.py
index b386945e54..70bdee80ed 100644
--- a/contrib/python/ipython/py2/IPython/core/completer.py
+++ b/contrib/python/ipython/py2/IPython/core/completer.py
@@ -1,9 +1,9 @@
# encoding: utf-8
"""Word completion for IPython.
-This module started as fork of the rlcompleter module in the Python standard
+This module started as fork of the rlcompleter module in the Python standard
library. The original enhancements made to rlcompleter have been sent
-upstream and were accepted as of Python 2.3,
+upstream and were accepted as of Python 2.3,
"""
@@ -13,8 +13,8 @@ upstream and were accepted as of Python 2.3,
# Some of this code originated from rlcompleter in the Python standard library
# Copyright (C) 2001 Python Software Foundation, www.python.org
-from __future__ import print_function
-
+from __future__ import print_function
+
import __main__
import glob
import inspect
@@ -27,18 +27,18 @@ import unicodedata
import string
import warnings
-from traitlets.config.configurable import Configurable
+from traitlets.config.configurable import Configurable
from IPython.core.error import TryNext
from IPython.core.inputsplitter import ESC_MAGIC
from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
from IPython.utils import generics
from IPython.utils.decorators import undoc
-from IPython.utils.dir2 import dir2, get_real_method
+from IPython.utils.dir2 import dir2, get_real_method
from IPython.utils.process import arg_split
-from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
-from traitlets import Bool, Enum, observe
-
+from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
+from traitlets import Bool, Enum, observe
+
# Public API
__all__ = ['Completer','IPCompleter']
@@ -74,13 +74,13 @@ def has_open_quotes(s):
def protect_filename(s):
"""Escape a string to protect certain characters."""
- if set(s) & set(PROTECTABLES):
- if sys.platform == "win32":
- return '"' + s + '"'
- else:
- return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
- else:
- return s
+ if set(s) & set(PROTECTABLES):
+ if sys.platform == "win32":
+ return '"' + s + '"'
+ else:
+ return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
+ else:
+ return s
def expand_user(path):
@@ -132,52 +132,52 @@ def compress_user(path, tilde_expand, tilde_val):
return path
-def completions_sorting_key(word):
- """key for sorting completions
+def completions_sorting_key(word):
+ """key for sorting completions
- This does several things:
+ This does several things:
- - Lowercase all completions, so they are sorted alphabetically with
- upper and lower case words mingled
- - Demote any completions starting with underscores to the end
- - Insert any %magic and %%cellmagic completions in the alphabetical order
- by their name
- """
- # Case insensitive sort
- word = word.lower()
+ - Lowercase all completions, so they are sorted alphabetically with
+ upper and lower case words mingled
+ - Demote any completions starting with underscores to the end
+ - Insert any %magic and %%cellmagic completions in the alphabetical order
+ by their name
+ """
+ # Case insensitive sort
+ word = word.lower()
- prio1, prio2 = 0, 0
+ prio1, prio2 = 0, 0
- if word.startswith('__'):
- prio1 = 2
- elif word.startswith('_'):
- prio1 = 1
+ if word.startswith('__'):
+ prio1 = 2
+ elif word.startswith('_'):
+ prio1 = 1
- if word.endswith('='):
- prio1 = -1
+ if word.endswith('='):
+ prio1 = -1
- if word.startswith('%%'):
- # If there's another % in there, this is something else, so leave it alone
+ if word.startswith('%%'):
+ # If there's another % in there, this is something else, so leave it alone
if not "%" in word[2:]:
- word = word[2:]
- prio2 = 2
- elif word.startswith('%'):
+ word = word[2:]
+ prio2 = 2
+ elif word.startswith('%'):
if not "%" in word[1:]:
- word = word[1:]
- prio2 = 1
-
- return prio1, word, prio2
+ word = word[1:]
+ prio2 = 1
+ return prio1, word, prio2
+
@undoc
class Bunch(object): pass
-if sys.platform == 'win32':
- DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
-else:
- DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
-
+if sys.platform == 'win32':
+ DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
+else:
+ DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
+
GREEDY_DELIMS = ' =\r\n'
@@ -234,14 +234,14 @@ class CompletionSplitter(object):
class Completer(Configurable):
- greedy = Bool(False,
+ greedy = Bool(False,
help="""Activate greedy completion
- PENDING DEPRECTION. this is now mostly taken care of with Jedi.
+ PENDING DEPRECTION. this is now mostly taken care of with Jedi.
This will enable completion on elements of lists, results of function calls, etc.,
but can be unsafe because the code is actually evaluated on TAB.
"""
- ).tag(config=True)
+ ).tag(config=True)
backslash_combining_completions = Bool(True,
help="Enable unicode completions, e.g. \\alpha<tab> . "
@@ -251,7 +251,7 @@ class Completer(Configurable):
def __init__(self, namespace=None, global_namespace=None, **kwargs):
"""Create a new completer for the command line.
- Completer(namespace=ns, global_namespace=ns2) -> completer instance.
+ Completer(namespace=ns, global_namespace=ns2) -> completer instance.
If unspecified, the default namespace where completions are performed
is __main__ (technically, __main__.__dict__). Namespaces should be
@@ -321,7 +321,7 @@ class Completer(Configurable):
for word in lst:
if word[:n] == text and word != "__builtins__":
match_append(word)
- return [cast_unicode_py2(m) for m in matches]
+ return [cast_unicode_py2(m) for m in matches]
def attr_matches(self, text):
"""Compute matches when text contains a dot.
@@ -373,7 +373,7 @@ class Completer(Configurable):
pass
# Build match list to return
n = len(attr)
- return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
+ return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
def get__all__entries(obj):
@@ -383,7 +383,7 @@ def get__all__entries(obj):
except:
return []
- return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
+ return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
def match_dict_keys(keys, prefix, delims):
@@ -470,7 +470,7 @@ def back_unicode_name_matches(text):
try :
unic = unicodedata.name(char)
return '\\'+char,['\\'+unic]
- except KeyError:
+ except KeyError:
pass
return u'', ()
@@ -497,18 +497,18 @@ def back_latex_name_matches(text):
latex = reverse_latex_symbol[char]
# '\\' replace the \ as well
return '\\'+char,[latex]
- except KeyError:
+ except KeyError:
pass
return u'', ()
class IPCompleter(Completer):
"""Extension of the completer class with IPython-specific features"""
-
- @observe('greedy')
- def _greedy_changed(self, change):
+
+ @observe('greedy')
+ def _greedy_changed(self, change):
"""update the splitter and readline delims when greedy is changed"""
- if change['new']:
+ if change['new']:
self.splitter.delims = GREEDY_DELIMS
else:
self.splitter.delims = DELIMS
@@ -516,14 +516,14 @@ class IPCompleter(Completer):
if self.readline:
self.readline.set_completer_delims(self.splitter.delims)
- merge_completions = Bool(True,
+ merge_completions = Bool(True,
help="""Whether to merge completion results into a single list
If False, only the completion results from the first non-empty
completer will be returned.
"""
- ).tag(config=True)
- omit__names = Enum((0,1,2), default_value=2,
+ ).tag(config=True)
+ omit__names = Enum((0,1,2), default_value=2,
help="""Instruct the completer to omit private method names
Specifically, when completing on ``object.<tab>``.
@@ -534,20 +534,20 @@ class IPCompleter(Completer):
When 0: nothing will be excluded.
"""
- ).tag(config=True)
- limit_to__all__ = Bool(False,
- help="""
- DEPRECATED as of version 5.0.
-
- Instruct the completer to use __all__ for the completion
+ ).tag(config=True)
+ limit_to__all__ = Bool(False,
+ help="""
+ DEPRECATED as of version 5.0.
+ Instruct the completer to use __all__ for the completion
+
Specifically, when completing on ``object.<tab>``.
When True: only those names in obj.__all__ will be included.
When False [default]: the __all__ attribute is ignored
- """,
- ).tag(config=True)
+ """,
+ ).tag(config=True)
@observe('limit_to__all__')
def _limit_to_all_changed(self, change):
@@ -621,24 +621,24 @@ class IPCompleter(Completer):
#= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
# All active matcher routines for completion
- self.matchers = [
- self.python_matches,
+ self.matchers = [
+ self.python_matches,
self.file_matches,
self.magic_matches,
self.python_func_kw_matches,
self.dict_key_matches,
]
- # This is set externally by InteractiveShell
- self.custom_completers = None
-
+ # This is set externally by InteractiveShell
+ self.custom_completers = None
+
def all_completions(self, text):
"""
- Wrapper around the complete method for the benefit of emacs.
+ Wrapper around the complete method for the benefit of emacs.
"""
return self.complete(text)[1]
- def _clean_glob(self, text):
+ def _clean_glob(self, text):
return self.glob("%s*" % text)
def _clean_glob_win32(self,text):
@@ -665,9 +665,9 @@ class IPCompleter(Completer):
# when escaped with backslash
if text.startswith('!'):
text = text[1:]
- text_prefix = u'!'
+ text_prefix = u'!'
else:
- text_prefix = u''
+ text_prefix = u''
text_until_cursor = self.text_until_cursor
# track strings with open quotes
@@ -698,13 +698,13 @@ class IPCompleter(Completer):
text = os.path.expanduser(text)
if text == "":
- return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
+ return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
# Compute the matches from the filesystem
- if sys.platform == 'win32':
- m0 = self.clean_glob(text)
- else:
- m0 = self.clean_glob(text.replace('\\', ''))
+ if sys.platform == 'win32':
+ m0 = self.clean_glob(text)
+ else:
+ m0 = self.clean_glob(text.replace('\\', ''))
if has_protectables:
# If we had protectables, we need to revert our changes to the
@@ -724,7 +724,7 @@ class IPCompleter(Completer):
protect_filename(f) for f in m0]
# Mark directories in input list by appending '/' to their names.
- return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
+ return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
def magic_matches(self, text):
"""Match magics"""
@@ -745,10 +745,10 @@ class IPCompleter(Completer):
comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
if not text.startswith(pre2):
comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
- return [cast_unicode_py2(c) for c in comp]
-
+ return [cast_unicode_py2(c) for c in comp]
- def python_matches(self, text):
+
+ def python_matches(self, text):
"""Match attributes or global python names"""
if "." in text:
try:
@@ -896,19 +896,19 @@ class IPCompleter(Completer):
for namedArg in namedArgs:
if namedArg.startswith(text):
- argMatches.append(u"%s=" %namedArg)
+ argMatches.append(u"%s=" %namedArg)
return argMatches
def dict_key_matches(self, text):
"Match string keys in a dictionary, after e.g. 'foo[' "
def get_keys(obj):
- # Objects can define their own completions by defining an
- # _ipy_key_completions_() method.
- method = get_real_method(obj, '_ipython_key_completions_')
- if method is not None:
- return method()
-
- # Special case some common in-memory dict-like types
+ # Objects can define their own completions by defining an
+ # _ipy_key_completions_() method.
+ method = get_real_method(obj, '_ipython_key_completions_')
+ if method is not None:
+ return method()
+
+ # Special case some common in-memory dict-like types
if isinstance(obj, dict) or\
_safe_isinstance(obj, 'pandas', 'DataFrame'):
try:
@@ -1026,7 +1026,7 @@ class IPCompleter(Completer):
# allow combining chars
if ('a'+unic).isidentifier():
return '\\'+s,[unic]
- except KeyError:
+ except KeyError:
pass
return u'', []
@@ -1055,9 +1055,9 @@ class IPCompleter(Completer):
return u'', []
def dispatch_custom_completer(self, text):
- if not self.custom_completers:
- return
-
+ if not self.custom_completers:
+ return
+
line = self.line_buffer
if not line.strip():
return None
@@ -1085,12 +1085,12 @@ class IPCompleter(Completer):
res = c(event)
if res:
# first, try case sensitive match
- withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
+ withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
if withcase:
return withcase
# if none, then case insensitive ones are ok too
text_low = text.lower()
- return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
+ return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
except TryNext:
pass
except KeyboardInterrupt:
diff --git a/contrib/python/ipython/py2/IPython/core/completerlib.py b/contrib/python/ipython/py2/IPython/core/completerlib.py
index e736ca73d1..5d51991725 100644
--- a/contrib/python/ipython/py2/IPython/core/completerlib.py
+++ b/contrib/python/ipython/py2/IPython/core/completerlib.py
@@ -227,8 +227,8 @@ def try_import(mod, only_modules=False):
completions.extend(getattr(m, '__all__', []))
if m_is_init:
completions.extend(arcadia_module_list(mod))
- completions = {c for c in completions if isinstance(c, string_types)}
- completions.discard('__init__')
+ completions = {c for c in completions if isinstance(c, string_types)}
+ completions.discard('__init__')
return sorted(completions)
diff --git a/contrib/python/ipython/py2/IPython/core/debugger.py b/contrib/python/ipython/py2/IPython/core/debugger.py
index f08cfb1a78..4980c3551b 100644
--- a/contrib/python/ipython/py2/IPython/core/debugger.py
+++ b/contrib/python/ipython/py2/IPython/core/debugger.py
@@ -31,40 +31,40 @@ import bdb
import functools
import inspect
import sys
-import warnings
+import warnings
from IPython import get_ipython
from IPython.utils import PyColorize, ulinecache
-from IPython.utils import coloransi, py3compat
+from IPython.utils import coloransi, py3compat
from IPython.core.excolors import exception_colors
from IPython.testing.skipdoctest import skip_doctest
-
+
prompt = 'ipdb> '
-
+
#We have to check this directly from sys.argv, config struct not yet available
-from pdb import Pdb as OldPdb
+from pdb import Pdb as OldPdb
# Allow the set_trace code to operate outside of an ipython instance, even if
# it does so with some limitations. The rest of this support is implemented in
# the Tracer constructor.
-
-def make_arrow(pad):
- """generate the leading arrow in front of traceback or debugger"""
- if pad >= 2:
- return '-'*(pad-2) + '> '
- elif pad == 1:
- return '>'
- return ''
-
-
+
+def make_arrow(pad):
+ """generate the leading arrow in front of traceback or debugger"""
+ if pad >= 2:
+ return '-'*(pad-2) + '> '
+ elif pad == 1:
+ return '>'
+ return ''
+
+
def BdbQuit_excepthook(et, ev, tb, excepthook=None):
"""Exception hook which handles `BdbQuit` exceptions.
All other exceptions are processed using the `excepthook`
parameter.
"""
- warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
+ warnings.warn("`BdbQuit_excepthook` is deprecated since version 5.1",
DeprecationWarning, stacklevel=2)
if et==bdb.BdbQuit:
print('Exiting Debugger.')
@@ -74,20 +74,20 @@ def BdbQuit_excepthook(et, ev, tb, excepthook=None):
# Backwards compatibility. Raise deprecation warning?
BdbQuit_excepthook.excepthook_ori(et,ev,tb)
-
+
def BdbQuit_IPython_excepthook(self,et,ev,tb,tb_offset=None):
- warnings.warn(
- "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
+ warnings.warn(
+ "`BdbQuit_IPython_excepthook` is deprecated since version 5.1",
DeprecationWarning, stacklevel=2)
print('Exiting Debugger.')
class Tracer(object):
- """
- DEPRECATED
-
- Class for local debugging, similar to pdb.set_trace.
+ """
+ DEPRECATED
+ Class for local debugging, similar to pdb.set_trace.
+
Instances of this class, when called, behave like pdb.set_trace, but
providing IPython's enhanced capabilities.
@@ -100,11 +100,11 @@ class Tracer(object):
@skip_doctest
def __init__(self, colors=None):
- """
- DEPRECATED
-
- Create a local debugger instance.
+ """
+ DEPRECATED
+ Create a local debugger instance.
+
Parameters
----------
@@ -128,8 +128,8 @@ class Tracer(object):
step through code, set breakpoints, etc. See the pdb documentation
from the Python standard library for usage details.
"""
- warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
- "`IPython.core.debugger.Pdb.set_trace()`",
+ warnings.warn("`Tracer` is deprecated since version 5.1, directly use "
+ "`IPython.core.debugger.Pdb.set_trace()`",
DeprecationWarning, stacklevel=2)
ip = get_ipython()
@@ -204,25 +204,25 @@ def _file_lines(fname):
class Pdb(OldPdb):
- """Modified Pdb class, does not load readline.
-
- for a standalone version that uses prompt_toolkit, see
- `IPython.terminal.debugger.TerminalPdb` and
- `IPython.terminal.debugger.set_trace()`
- """
-
- def __init__(self, color_scheme=None, completekey=None,
+ """Modified Pdb class, does not load readline.
+
+ for a standalone version that uses prompt_toolkit, see
+ `IPython.terminal.debugger.TerminalPdb` and
+ `IPython.terminal.debugger.set_trace()`
+ """
+
+ def __init__(self, color_scheme=None, completekey=None,
stdin=None, stdout=None, context=5):
# Parent constructor:
try:
- self.context = int(context)
+ self.context = int(context)
if self.context <= 0:
raise ValueError("Context must be a positive integer")
except (TypeError, ValueError):
raise ValueError("Context must be a positive integer")
- OldPdb.__init__(self, completekey, stdin, stdout)
+ OldPdb.__init__(self, completekey, stdin, stdout)
# IPython changes...
self.shell = get_ipython()
@@ -237,12 +237,12 @@ class Pdb(OldPdb):
# the debugger was entered. See also #9941.
sys.modules['__main__'] = save_main
- if color_scheme is not None:
- warnings.warn(
- "The `color_scheme` argument is deprecated since version 5.1",
- DeprecationWarning)
- else:
- color_scheme = self.shell.colors
+ if color_scheme is not None:
+ warnings.warn(
+ "The `color_scheme` argument is deprecated since version 5.1",
+ DeprecationWarning)
+ else:
+ color_scheme = self.shell.colors
self.aliases = {}
@@ -266,28 +266,28 @@ class Pdb(OldPdb):
cst['LightBG'].colors.breakpoint_enabled = C.LightRed
cst['LightBG'].colors.breakpoint_disabled = C.Red
- cst['Neutral'].colors.prompt = C.Blue
- cst['Neutral'].colors.breakpoint_enabled = C.LightRed
- cst['Neutral'].colors.breakpoint_disabled = C.Red
-
+ cst['Neutral'].colors.prompt = C.Blue
+ cst['Neutral'].colors.breakpoint_enabled = C.LightRed
+ cst['Neutral'].colors.breakpoint_disabled = C.Red
+
self.set_colors(color_scheme)
# Add a python parser so we can syntax highlight source while
# debugging.
self.parser = PyColorize.Parser()
- # Set the prompt - the default prompt is '(Pdb)'
- self.prompt = prompt
+ # Set the prompt - the default prompt is '(Pdb)'
+ self.prompt = prompt
def set_colors(self, scheme):
"""Shorthand access to the color table scheme selector method."""
self.color_scheme_table.set_active_scheme(scheme)
def interaction(self, frame, traceback):
- try:
- OldPdb.interaction(self, frame, traceback)
- except KeyboardInterrupt:
- sys.stdout.write('\n' + self.shell.get_exception_only())
+ try:
+ OldPdb.interaction(self, frame, traceback)
+ except KeyboardInterrupt:
+ sys.stdout.write('\n' + self.shell.get_exception_only())
def new_do_up(self, arg):
OldPdb.do_up(self, arg)
@@ -331,7 +331,7 @@ class Pdb(OldPdb):
except KeyboardInterrupt:
pass
- def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
+ def print_stack_entry(self,frame_lineno, prompt_prefix='\n-> ',
context=None):
if context is None:
context = self.context
@@ -341,7 +341,7 @@ class Pdb(OldPdb):
raise ValueError("Context must be a positive integer")
except (TypeError, ValueError):
raise ValueError("Context must be a positive integer")
- print(self.format_stack_entry(frame_lineno, '', context))
+ print(self.format_stack_entry(frame_lineno, '', context))
# vds: >>
frame, lineno = frame_lineno
@@ -447,11 +447,11 @@ class Pdb(OldPdb):
if arrow:
# This is the line with the error
pad = numbers_width - len(str(lineno)) - len(bp_mark)
- num = '%s%s' % (make_arrow(pad), str(lineno))
+ num = '%s%s' % (make_arrow(pad), str(lineno))
else:
num = '%*s' % (numbers_width - len(bp_mark), str(lineno))
- return tpl_line % (bp_mark_color + bp_mark, num, line)
+ return tpl_line % (bp_mark_color + bp_mark, num, line)
def print_list_lines(self, filename, first, last):
@@ -479,7 +479,7 @@ class Pdb(OldPdb):
src.append(line)
self.lineno = lineno
- print(''.join(src))
+ print(''.join(src))
except KeyboardInterrupt:
pass
diff --git a/contrib/python/ipython/py2/IPython/core/display.py b/contrib/python/ipython/py2/IPython/core/display.py
index 5c82a57b31..a099031953 100644
--- a/contrib/python/ipython/py2/IPython/core/display.py
+++ b/contrib/python/ipython/py2/IPython/core/display.py
@@ -6,17 +6,17 @@
from __future__ import print_function
-try:
- from base64 import encodebytes as base64_encode
-except ImportError:
- from base64 import encodestring as base64_encode
-
+try:
+ from base64 import encodebytes as base64_encode
+except ImportError:
+ from base64 import encodestring as base64_encode
+
from binascii import b2a_hex, hexlify
import json
import mimetypes
import os
import struct
-import sys
+import sys
import warnings
from IPython.utils.py3compat import (string_types, cast_bytes_py2, cast_unicode,
@@ -964,9 +964,9 @@ class Image(DisplayObject):
Note that QtConsole is not able to display images if `embed` is set to `False`
width : int
- Width in pixels to which to constrain the image in html
+ Width in pixels to which to constrain the image in html
height : int
- Height in pixels to which to constrain the image in html
+ Height in pixels to which to constrain the image in html
retina : bool
Automatically set the width and height to half of the measured
width and height.
@@ -1111,7 +1111,7 @@ class Image(DisplayObject):
class Video(DisplayObject):
- def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
+ def __init__(self, data=None, url=None, filename=None, embed=False, mimetype=None):
"""Create a video object given raw data or an URL.
When this object is returned by an input cell or passed to the
@@ -1121,54 +1121,54 @@ class Video(DisplayObject):
Parameters
----------
data : unicode, str or bytes
- The raw video data or a URL or filename to load the data from.
- Raw data will require passing `embed=True`.
+ The raw video data or a URL or filename to load the data from.
+ Raw data will require passing `embed=True`.
url : unicode
- A URL for the video. If you specify `url=`,
- the image data will not be embedded.
+ A URL for the video. If you specify `url=`,
+ the image data will not be embedded.
filename : unicode
- Path to a local file containing the video.
- Will be interpreted as a local URL unless `embed=True`.
+ Path to a local file containing the video.
+ Will be interpreted as a local URL unless `embed=True`.
embed : bool
- Should the video be embedded using a data URI (True) or be
- loaded using a <video> tag (False).
-
- Since videos are large, embedding them should be avoided, if possible.
- You must confirm embedding as your intention by passing `embed=True`.
-
- Local files can be displayed with URLs without embedding the content, via::
+ Should the video be embedded using a data URI (True) or be
+ loaded using a <video> tag (False).
- Video('./video.mp4')
+ Since videos are large, embedding them should be avoided, if possible.
+ You must confirm embedding as your intention by passing `embed=True`.
+ Local files can be displayed with URLs without embedding the content, via::
+
+ Video('./video.mp4')
+
mimetype: unicode
- Specify the mimetype for embedded videos.
- Default will be guessed from file extension, if available.
-
+ Specify the mimetype for embedded videos.
+ Default will be guessed from file extension, if available.
+
Examples
--------
-
+
Video('https://archive.org/download/Sita_Sings_the_Blues/Sita_Sings_the_Blues_small.mp4')
Video('path/to/video.mp4')
- Video('path/to/video.mp4', embed=True)
- Video(b'raw-videodata', embed=True)
+ Video('path/to/video.mp4', embed=True)
+ Video(b'raw-videodata', embed=True)
"""
- if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
+ if url is None and isinstance(data, string_types) and data.startswith(('http:', 'https:')):
url = data
data = None
elif os.path.exists(data):
filename = data
data = None
-
- if data and not embed:
- msg = ''.join([
- "To embed videos, you must pass embed=True ",
- "(this may make your notebook files huge)\n",
- "Consider passing Video(url='...')",
- ])
- raise ValueError(msg)
+
+ if data and not embed:
+ msg = ''.join([
+ "To embed videos, you must pass embed=True ",
+ "(this may make your notebook files huge)\n",
+ "Consider passing Video(url='...')",
+ ])
+ raise ValueError(msg)
self.mimetype = mimetype
- self.embed = embed
+ self.embed = embed
super(Video, self).__init__(data=data, url=url, filename=filename)
def _repr_html_(self):
@@ -1180,27 +1180,27 @@ class Video(DisplayObject):
Your browser does not support the <code>video</code> element.
</video>""".format(url)
return output
-
- # Embedded videos are base64-encoded.
- mimetype = self.mimetype
+
+ # Embedded videos are base64-encoded.
+ mimetype = self.mimetype
if self.filename is not None:
- if not mimetype:
- mimetype, _ = mimetypes.guess_type(self.filename)
-
- with open(self.filename, 'rb') as f:
- video = f.read()
+ if not mimetype:
+ mimetype, _ = mimetypes.guess_type(self.filename)
+
+ with open(self.filename, 'rb') as f:
+ video = f.read()
else:
- video = self.data
- if isinstance(video, unicode_type):
- # unicode input is already b64-encoded
- b64_video = video
- else:
- b64_video = base64_encode(video).decode('ascii').rstrip()
-
+ video = self.data
+ if isinstance(video, unicode_type):
+ # unicode input is already b64-encoded
+ b64_video = video
+ else:
+ b64_video = base64_encode(video).decode('ascii').rstrip()
+
output = """<video controls>
<source src="data:{0};base64,{1}" type="{0}">
Your browser does not support the video tag.
- </video>""".format(mimetype, b64_video)
+ </video>""".format(mimetype, b64_video)
return output
def reload(self):
@@ -1225,10 +1225,10 @@ def clear_output(wait=False):
if InteractiveShell.initialized():
InteractiveShell.instance().display_pub.clear_output(wait)
else:
- print('\033[2K\r', end='')
- sys.stdout.flush()
- print('\033[2K\r', end='')
- sys.stderr.flush()
+ print('\033[2K\r', end='')
+ sys.stdout.flush()
+ print('\033[2K\r', end='')
+ sys.stderr.flush()
@skip_doctest
diff --git a/contrib/python/ipython/py2/IPython/core/displayhook.py b/contrib/python/ipython/py2/IPython/core/displayhook.py
index cce7c83d16..e07b577680 100644
--- a/contrib/python/ipython/py2/IPython/core/displayhook.py
+++ b/contrib/python/ipython/py2/IPython/core/displayhook.py
@@ -16,7 +16,7 @@ import tokenize
from traitlets.config.configurable import Configurable
from IPython.utils.py3compat import builtin_mod, cast_unicode_py2
from traitlets import Instance, Float
-from warnings import warn
+from warnings import warn
# TODO: Move the various attributes (cache_size, [others now moved]). Some
# of these are also attributes of InteractiveShell. They should be on ONE object
@@ -94,7 +94,7 @@ class DisplayHook(Configurable):
tokens = list(tokenize.generate_tokens(sio.readline))
for token in reversed(tokens):
- if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
+ if token[0] in (tokenize.ENDMARKER, tokenize.NL, tokenize.NEWLINE, tokenize.COMMENT):
continue
if (token[0] == tokenize.OP) and (token[1] == ';'):
return True
@@ -109,13 +109,13 @@ class DisplayHook(Configurable):
"""Write the output prompt.
The default implementation simply writes the prompt to
- ``sys.stdout``.
+ ``sys.stdout``.
"""
# Use write, not print which adds an extra space.
- sys.stdout.write(self.shell.separate_out)
- outprompt = 'Out[{}]: '.format(self.shell.execution_count)
+ sys.stdout.write(self.shell.separate_out)
+ outprompt = 'Out[{}]: '.format(self.shell.execution_count)
if self.do_full_cache:
- sys.stdout.write(outprompt)
+ sys.stdout.write(outprompt)
def compute_format_data(self, result):
"""Compute format data of the object to be displayed.
@@ -149,14 +149,14 @@ class DisplayHook(Configurable):
"""
return self.shell.display_formatter.format(result)
- # This can be set to True by the write_output_prompt method in a subclass
- prompt_end_newline = False
-
+ # This can be set to True by the write_output_prompt method in a subclass
+ prompt_end_newline = False
+
def write_format_data(self, format_dict, md_dict=None):
"""Write the format data dict to the frontend.
This default version of this method simply writes the plain text
- representation of the object to ``sys.stdout``. Subclasses should
+ representation of the object to ``sys.stdout``. Subclasses should
override this method to send the entire `format_dict` to the
frontends.
@@ -182,11 +182,11 @@ class DisplayHook(Configurable):
# because the expansion may add ANSI escapes that will interfere
# with our ability to determine whether or not we should add
# a newline.
- if not self.prompt_end_newline:
+ if not self.prompt_end_newline:
# But avoid extraneous empty lines.
result_repr = '\n' + result_repr
- print(result_repr)
+ print(result_repr)
def update_user_ns(self, result):
"""Update user_ns with various things like _, __, _1, etc."""
@@ -230,8 +230,8 @@ class DisplayHook(Configurable):
def finish_displayhook(self):
"""Finish up all displayhook activities."""
- sys.stdout.write(self.shell.separate_out2)
- sys.stdout.flush()
+ sys.stdout.write(self.shell.separate_out2)
+ sys.stdout.flush()
def __call__(self, result=None):
"""Printing with history cache management.
diff --git a/contrib/python/ipython/py2/IPython/core/displaypub.py b/contrib/python/ipython/py2/IPython/core/displaypub.py
index 82a859ae15..cd7be5797e 100644
--- a/contrib/python/ipython/py2/IPython/core/displaypub.py
+++ b/contrib/python/ipython/py2/IPython/core/displaypub.py
@@ -17,8 +17,8 @@ spec.
from __future__ import print_function
-import sys
-
+import sys
+
from traitlets.config.configurable import Configurable
from traitlets import List
@@ -105,16 +105,16 @@ class DisplayPublisher(Configurable):
transient = kwargs.pop('transient', None)
update = kwargs.pop('update', False)
- # The default is to simply write the plain text data using sys.stdout.
+ # The default is to simply write the plain text data using sys.stdout.
if 'text/plain' in data:
- print(data['text/plain'])
+ print(data['text/plain'])
def clear_output(self, wait=False):
"""Clear the output of the cell receiving output."""
- print('\033[2K\r', end='')
- sys.stdout.flush()
- print('\033[2K\r', end='')
- sys.stderr.flush()
+ print('\033[2K\r', end='')
+ sys.stdout.flush()
+ print('\033[2K\r', end='')
+ sys.stderr.flush()
class CapturingDisplayPublisher(DisplayPublisher):
diff --git a/contrib/python/ipython/py2/IPython/core/events.py b/contrib/python/ipython/py2/IPython/core/events.py
index bfd09fec6a..776fa191da 100644
--- a/contrib/python/ipython/py2/IPython/core/events.py
+++ b/contrib/python/ipython/py2/IPython/core/events.py
@@ -69,7 +69,7 @@ class EventManager(object):
Any additional arguments are passed to all callbacks registered for this
event. Exceptions raised by callbacks are caught, and a message printed.
"""
- for func in self.callbacks[event][:]:
+ for func in self.callbacks[event][:]:
try:
func(*args, **kwargs)
except Exception:
diff --git a/contrib/python/ipython/py2/IPython/core/excolors.py b/contrib/python/ipython/py2/IPython/core/excolors.py
index 487bde18c8..de46ac13a5 100644
--- a/contrib/python/ipython/py2/IPython/core/excolors.py
+++ b/contrib/python/ipython/py2/IPython/core/excolors.py
@@ -19,7 +19,7 @@ def exception_colors():
"""Return a color table with fields for exception reporting.
The table is an instance of ColorSchemeTable with schemes added for
- 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
+ 'Neutral', 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
in.
Examples:
@@ -128,41 +128,41 @@ def exception_colors():
Normal = C.Normal,
))
- ex_colors.add_scheme(ColorScheme(
- 'Neutral',
- # The color to be used for the top line
- topline = C.Red,
-
- # The colors to be used in the traceback
- filename = C.LightGreen,
- lineno = C.LightGreen,
- name = C.LightPurple,
- vName = C.Cyan,
- val = C.LightGreen,
- em = C.Cyan,
-
- # Emphasized colors for the last frame of the traceback
- normalEm = C.Cyan,
- filenameEm = C.Green,
- linenoEm = C.Green,
- nameEm = C.Purple,
- valEm = C.Blue,
-
- # Colors for printing the exception
- excName = C.Red,
- #line = C.Brown, # brown often is displayed as yellow
- line = C.Red,
- caret = C.Normal,
- Normal = C.Normal,
- ))
-
+ ex_colors.add_scheme(ColorScheme(
+ 'Neutral',
+ # The color to be used for the top line
+ topline = C.Red,
+
+ # The colors to be used in the traceback
+ filename = C.LightGreen,
+ lineno = C.LightGreen,
+ name = C.LightPurple,
+ vName = C.Cyan,
+ val = C.LightGreen,
+ em = C.Cyan,
+
+ # Emphasized colors for the last frame of the traceback
+ normalEm = C.Cyan,
+ filenameEm = C.Green,
+ linenoEm = C.Green,
+ nameEm = C.Purple,
+ valEm = C.Blue,
+
+ # Colors for printing the exception
+ excName = C.Red,
+ #line = C.Brown, # brown often is displayed as yellow
+ line = C.Red,
+ caret = C.Normal,
+ Normal = C.Normal,
+ ))
+
# Hack: the 'neutral' colours are not very visible on a dark background on
# Windows. Since Windows command prompts have a dark background by default, and
# relatively few users are likely to alter that, we will use the 'Linux' colours,
# designed for a dark background, as the default on Windows.
if os.name == "nt":
ex_colors.add_scheme(ex_colors['Linux'].copy('Neutral'))
-
+
return ex_colors
class Deprec(object):
diff --git a/contrib/python/ipython/py2/IPython/core/extensions.py b/contrib/python/ipython/py2/IPython/core/extensions.py
index 58855466f1..81c5de462d 100644
--- a/contrib/python/ipython/py2/IPython/core/extensions.py
+++ b/contrib/python/ipython/py2/IPython/core/extensions.py
@@ -36,7 +36,7 @@ class ExtensionManager(Configurable):
the only argument. You can do anything you want with IPython at
that point, including defining new magic and aliases, adding new
components, etc.
-
+
You can also optionally define an :func:`unload_ipython_extension(ipython)`
function, which will be called if the user unloads or reloads the extension.
The extension manager will only call :func:`load_ipython_extension` again
@@ -49,12 +49,12 @@ class ExtensionManager(Configurable):
is added to ``sys.path`` automatically.
"""
- shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
+ shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None, **kwargs):
super(ExtensionManager, self).__init__(shell=shell, **kwargs)
- self.shell.observe(
- self._on_ipython_dir_changed, names=('ipython_dir',)
+ self.shell.observe(
+ self._on_ipython_dir_changed, names=('ipython_dir',)
)
self.loaded = set()
@@ -62,7 +62,7 @@ class ExtensionManager(Configurable):
def ipython_extension_dir(self):
return os.path.join(self.shell.ipython_dir, u'extensions')
- def _on_ipython_dir_changed(self, change):
+ def _on_ipython_dir_changed(self, change):
ensure_dir_exists(self.ipython_extension_dir)
def load_extension(self, module_str):
@@ -74,7 +74,7 @@ class ExtensionManager(Configurable):
"""
if module_str in self.loaded:
return "already loaded"
-
+
with self.shell.builtin_trap:
if module_str not in sys.modules:
try:
@@ -92,14 +92,14 @@ class ExtensionManager(Configurable):
This function looks up the extension's name in ``sys.modules`` and
simply calls ``mod.unload_ipython_extension(self)``.
-
+
Returns the string "no unload function" if the extension doesn't define
a function to unload itself, "not loaded" if the extension isn't loaded,
otherwise None.
"""
if module_str not in self.loaded:
return "not loaded"
-
+
if module_str in sys.modules:
mod = sys.modules[module_str]
if self._call_unload_ipython_extension(mod):
@@ -138,7 +138,7 @@ class ExtensionManager(Configurable):
return True
def install_extension(self, url, filename=None):
- """Download and install an IPython extension.
+ """Download and install an IPython extension.
If filename is given, the file will be so named (inside the extension
directory). Otherwise, the name from the URL will be used. The file must
diff --git a/contrib/python/ipython/py2/IPython/core/formatters.py b/contrib/python/ipython/py2/IPython/core/formatters.py
index d990619f27..06af83c1a9 100644
--- a/contrib/python/ipython/py2/IPython/core/formatters.py
+++ b/contrib/python/ipython/py2/IPython/core/formatters.py
@@ -21,12 +21,12 @@ from decorator import decorator
from traitlets.config.configurable import Configurable
from IPython.core.getipython import get_ipython
from IPython.utils.sentinel import Sentinel
-from IPython.utils.dir2 import get_real_method
+from IPython.utils.dir2 import get_real_method
from IPython.lib import pretty
from traitlets import (
Bool, Dict, Integer, Unicode, CUnicode, ObjectName, List,
ForwardDeclaredInstance,
- default, observe,
+ default, observe,
)
from IPython.utils.py3compat import (
with_metaclass, string_types, unicode_type,
@@ -35,28 +35,28 @@ from IPython.utils.py3compat import (
class DisplayFormatter(Configurable):
- active_types = List(Unicode(),
+ active_types = List(Unicode(),
help="""List of currently active mime-types to display.
You can use this to set a white-list for formats to display.
Most users will not need to change this value.
- """).tag(config=True)
-
- @default('active_types')
+ """).tag(config=True)
+
+ @default('active_types')
def _active_types_default(self):
return self.format_types
-
- @observe('active_types')
- def _active_types_changed(self, change):
+
+ @observe('active_types')
+ def _active_types_changed(self, change):
for key, formatter in self.formatters.items():
- if key in change['new']:
+ if key in change['new']:
formatter.enabled = True
else:
formatter.enabled = False
ipython_display_formatter = ForwardDeclaredInstance('FormatterABC')
- @default('ipython_display_formatter')
- def _default_formatter(self):
+ @default('ipython_display_formatter')
+ def _default_formatter(self):
return IPythonDisplayFormatter(parent=self)
mimebundle_formatter = ForwardDeclaredInstance('FormatterABC')
@@ -67,7 +67,7 @@ class DisplayFormatter(Configurable):
# A dict of formatter whose keys are format types (MIME types) and whose
# values are subclasses of BaseFormatter.
formatters = Dict()
- @default('formatters')
+ @default('formatters')
def _formatters_default(self):
"""Activate the default formatters."""
formatter_classes = [
@@ -305,21 +305,21 @@ class BaseFormatter(Configurable):
format_type = Unicode('text/plain')
_return_type = string_types
- enabled = Bool(True).tag(config=True)
+ enabled = Bool(True).tag(config=True)
print_method = ObjectName('__repr__')
# The singleton printers.
# Maps the IDs of the builtin singleton objects to the format functions.
- singleton_printers = Dict().tag(config=True)
+ singleton_printers = Dict().tag(config=True)
# The type-specific printers.
# Map type objects to the format functions.
- type_printers = Dict().tag(config=True)
+ type_printers = Dict().tag(config=True)
# The deferred-import type-specific printers.
# Map (modulename, classname) pairs to the format functions.
- deferred_printers = Dict().tag(config=True)
+ deferred_printers = Dict().tag(config=True)
@catch_format_error
def __call__(self, obj):
@@ -333,7 +333,7 @@ class BaseFormatter(Configurable):
else:
return printer(obj)
# Finally look for special method names
- method = get_real_method(obj, self.print_method)
+ method = get_real_method(obj, self.print_method)
if method is not None:
return method()
return None
@@ -586,37 +586,37 @@ class PlainTextFormatter(BaseFormatter):
# This subclass ignores this attribute as it always need to return
# something.
- enabled = Bool(True).tag(config=False)
+ enabled = Bool(True).tag(config=False)
- max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
+ max_seq_length = Integer(pretty.MAX_SEQ_LENGTH,
help="""Truncate large collections (lists, dicts, tuples, sets) to this size.
Set to 0 to disable truncation.
"""
- ).tag(config=True)
+ ).tag(config=True)
# Look for a _repr_pretty_ methods to use for pretty printing.
print_method = ObjectName('_repr_pretty_')
# Whether to pretty-print or not.
- pprint = Bool(True).tag(config=True)
+ pprint = Bool(True).tag(config=True)
# Whether to be verbose or not.
- verbose = Bool(False).tag(config=True)
+ verbose = Bool(False).tag(config=True)
# The maximum width.
- max_width = Integer(79).tag(config=True)
+ max_width = Integer(79).tag(config=True)
# The newline character.
- newline = Unicode('\n').tag(config=True)
+ newline = Unicode('\n').tag(config=True)
# format-string for pprinting floats
float_format = Unicode('%r')
# setter for float precision, either int or direct format-string
- float_precision = CUnicode('').tag(config=True)
+ float_precision = CUnicode('').tag(config=True)
- @observe('float_precision')
- def _float_precision_changed(self, change):
+ @observe('float_precision')
+ def _float_precision_changed(self, change):
"""float_precision changed, set float_format accordingly.
float_precision can be set by int or str.
@@ -630,7 +630,7 @@ class PlainTextFormatter(BaseFormatter):
This parameter can be set via the '%precision' magic.
"""
- new = change['new']
+ new = change['new']
if '%' in new:
# got explicit format string
fmt = new
@@ -663,17 +663,17 @@ class PlainTextFormatter(BaseFormatter):
self.float_format = fmt
# Use the default pretty printers from IPython.lib.pretty.
- @default('singleton_printers')
+ @default('singleton_printers')
def _singleton_printers_default(self):
return pretty._singleton_pprinters.copy()
- @default('type_printers')
+ @default('type_printers')
def _type_printers_default(self):
d = pretty._type_pprinters.copy()
d[float] = lambda obj,p,cycle: p.text(self.float_format%obj)
return d
- @default('deferred_printers')
+ @default('deferred_printers')
def _deferred_printers_default(self):
return pretty._deferred_type_pprinters.copy()
@@ -910,7 +910,7 @@ class IPythonDisplayFormatter(BaseFormatter):
printer(obj)
return True
# Finally look for special method names
- method = get_real_method(obj, self.print_method)
+ method = get_real_method(obj, self.print_method)
if method is not None:
method()
return True
@@ -1030,7 +1030,7 @@ def format_display_data(obj, include=None, exclude=None):
"""
from IPython.core.interactiveshell import InteractiveShell
- return InteractiveShell.instance().display_formatter.format(
+ return InteractiveShell.instance().display_formatter.format(
obj,
include,
exclude
diff --git a/contrib/python/ipython/py2/IPython/core/history.py b/contrib/python/ipython/py2/IPython/core/history.py
index 2e7fdbc845..1e8e227a50 100644
--- a/contrib/python/ipython/py2/IPython/core/history.py
+++ b/contrib/python/ipython/py2/IPython/core/history.py
@@ -1,8 +1,8 @@
""" History related magics and functionality """
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
from __future__ import print_function
import atexit
@@ -18,16 +18,16 @@ except ImportError:
sqlite3 = None
import threading
-from traitlets.config.configurable import LoggingConfigurable
+from traitlets.config.configurable import LoggingConfigurable
from decorator import decorator
from IPython.utils.decorators import undoc
from IPython.paths import locate_profile
from IPython.utils import py3compat
from traitlets import (
Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
- default, observe,
+ default, observe,
)
-from warnings import warn
+from warnings import warn
#-----------------------------------------------------------------------------
# Classes and functions
@@ -72,55 +72,55 @@ else:
class OperationalError(Exception):
"Dummy exception when sqlite could not be imported. Should never occur."
-# use 16kB as threshold for whether a corrupt history db should be saved
-# that should be at least 100 entries or so
-_SAVE_DB_SIZE = 16384
-
+# use 16kB as threshold for whether a corrupt history db should be saved
+# that should be at least 100 entries or so
+_SAVE_DB_SIZE = 16384
+
@decorator
def catch_corrupt_db(f, self, *a, **kw):
"""A decorator which wraps HistoryAccessor method calls to catch errors from
a corrupt SQLite database, move the old database out of the way, and create
a new one.
-
- We avoid clobbering larger databases because this may be triggered due to filesystem issues,
- not just a corrupt file.
+
+ We avoid clobbering larger databases because this may be triggered due to filesystem issues,
+ not just a corrupt file.
"""
try:
return f(self, *a, **kw)
- except (DatabaseError, OperationalError) as e:
- self._corrupt_db_counter += 1
- self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
- if self.hist_file != ':memory:':
- if self._corrupt_db_counter > self._corrupt_db_limit:
- self.hist_file = ':memory:'
- self.log.error("Failed to load history too many times, history will not be saved.")
- elif os.path.isfile(self.hist_file):
- # move the file out of the way
- base, ext = os.path.splitext(self.hist_file)
- size = os.stat(self.hist_file).st_size
- if size >= _SAVE_DB_SIZE:
- # if there's significant content, avoid clobbering
- now = datetime.datetime.now().isoformat().replace(':', '.')
- newpath = base + '-corrupt-' + now + ext
- # don't clobber previous corrupt backups
- for i in range(100):
- if not os.path.isfile(newpath):
- break
- else:
- newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
- else:
- # not much content, possibly empty; don't worry about clobbering
- # maybe we should just delete it?
- newpath = base + '-corrupt' + ext
- os.rename(self.hist_file, newpath)
- self.log.error("History file was moved to %s and a new file created.", newpath)
+ except (DatabaseError, OperationalError) as e:
+ self._corrupt_db_counter += 1
+ self.log.error("Failed to open SQLite history %s (%s).", self.hist_file, e)
+ if self.hist_file != ':memory:':
+ if self._corrupt_db_counter > self._corrupt_db_limit:
+ self.hist_file = ':memory:'
+ self.log.error("Failed to load history too many times, history will not be saved.")
+ elif os.path.isfile(self.hist_file):
+ # move the file out of the way
+ base, ext = os.path.splitext(self.hist_file)
+ size = os.stat(self.hist_file).st_size
+ if size >= _SAVE_DB_SIZE:
+ # if there's significant content, avoid clobbering
+ now = datetime.datetime.now().isoformat().replace(':', '.')
+ newpath = base + '-corrupt-' + now + ext
+ # don't clobber previous corrupt backups
+ for i in range(100):
+ if not os.path.isfile(newpath):
+ break
+ else:
+ newpath = base + '-corrupt-' + now + (u'-%i' % i) + ext
+ else:
+ # not much content, possibly empty; don't worry about clobbering
+ # maybe we should just delete it?
+ newpath = base + '-corrupt' + ext
+ os.rename(self.hist_file, newpath)
+ self.log.error("History file was moved to %s and a new file created.", newpath)
self.init_db()
return []
else:
- # Failed with :memory:, something serious is wrong
+ # Failed with :memory:, something serious is wrong
raise
-class HistoryAccessorBase(LoggingConfigurable):
+class HistoryAccessorBase(LoggingConfigurable):
"""An abstract class for History Accessors """
def get_tail(self, n=10, raw=True, output=False, include_latest=False):
@@ -143,13 +143,13 @@ class HistoryAccessor(HistoryAccessorBase):
This is intended for use by standalone history tools. IPython shells use
HistoryManager, below, which is a subclass of this."""
- # counter for init_db retries, so we don't keep trying over and over
- _corrupt_db_counter = 0
- # after two failures, fallback on :memory:
- _corrupt_db_limit = 2
-
+ # counter for init_db retries, so we don't keep trying over and over
+ _corrupt_db_counter = 0
+ # after two failures, fallback on :memory:
+ _corrupt_db_limit = 2
+
# String holding the path to the history file
- hist_file = Unicode(
+ hist_file = Unicode(
help="""Path to file to use for SQLite history database.
By default, IPython will put the history database in the IPython
@@ -161,13 +161,13 @@ class HistoryAccessor(HistoryAccessorBase):
local disk, e.g::
ipython --HistoryManager.hist_file=/tmp/ipython_hist.sqlite
-
- you can also use the specific value `:memory:` (including the colon
- at both end but not the back ticks), to avoid creating an history file.
+
+ you can also use the specific value `:memory:` (including the colon
+ at both end but not the back ticks), to avoid creating an history file.
- """).tag(config=True)
+ """).tag(config=True)
- enabled = Bool(True,
+ enabled = Bool(True,
help="""enable the SQLite history
set enabled=False to disable the SQLite history,
@@ -175,22 +175,22 @@ class HistoryAccessor(HistoryAccessorBase):
and no background saving thread. This may be necessary in some
threaded environments where IPython is embedded.
"""
- ).tag(config=True)
+ ).tag(config=True)
- connection_options = Dict(
+ connection_options = Dict(
help="""Options for configuring the SQLite connection
These options are passed as keyword args to sqlite3.connect
when establishing database conenctions.
"""
- ).tag(config=True)
+ ).tag(config=True)
# The SQLite database
db = Any()
- @observe('db')
- def _db_changed(self, change):
+ @observe('db')
+ def _db_changed(self, change):
"""validate the db, since it can be an Instance of two different types"""
- new = change['new']
+ new = change['new']
connection_types = (DummyDB,)
if sqlite3 is not None:
connection_types = (DummyDB, sqlite3.Connection)
@@ -266,8 +266,8 @@ class HistoryAccessor(HistoryAccessorBase):
(session integer, line integer, output text,
PRIMARY KEY (session, line))""")
self.db.commit()
- # success! reset corrupt db count
- self._corrupt_db_counter = 0
+ # success! reset corrupt db count
+ self._corrupt_db_counter = 0
def writeout_cache(self):
"""Overridden by HistoryManager to dump the cache before certain
@@ -486,7 +486,7 @@ class HistoryManager(HistoryAccessor):
input_hist_raw = List([""])
# A list of directories visited during session
dir_hist = List()
- @default('dir_hist')
+ @default('dir_hist')
def _dir_hist_default(self):
try:
return [py3compat.getcwd()]
@@ -502,13 +502,13 @@ class HistoryManager(HistoryAccessor):
# The number of the current session in the history database
session_number = Integer()
- db_log_output = Bool(False,
+ db_log_output = Bool(False,
help="Should the history database include output? (default: no)"
- ).tag(config=True)
- db_cache_size = Integer(0,
+ ).tag(config=True)
+ db_cache_size = Integer(0,
help="Write to database every x commands (higher values save disk access & power).\n"
"Values of 1 or less effectively disable caching."
- ).tag(config=True)
+ ).tag(config=True)
# The input and output caches
db_input_cache = List()
db_output_cache = List()
diff --git a/contrib/python/ipython/py2/IPython/core/historyapp.py b/contrib/python/ipython/py2/IPython/core/historyapp.py
index d51426d2ca..d083a78822 100644
--- a/contrib/python/ipython/py2/IPython/core/historyapp.py
+++ b/contrib/python/ipython/py2/IPython/core/historyapp.py
@@ -34,17 +34,17 @@ This is an handy alias to `ipython history trim --keep=0`
class HistoryTrim(BaseIPythonApplication):
description = trim_hist_help
- backup = Bool(False,
- help="Keep the old history file as history.sqlite.<N>"
- ).tag(config=True)
+ backup = Bool(False,
+ help="Keep the old history file as history.sqlite.<N>"
+ ).tag(config=True)
- keep = Int(1000,
- help="Number of recent lines to keep in the database."
- ).tag(config=True)
+ keep = Int(1000,
+ help="Number of recent lines to keep in the database."
+ ).tag(config=True)
flags = Dict(dict(
backup = ({'HistoryTrim' : {'backup' : True}},
- backup.help
+ backup.help
)
))
@@ -120,18 +120,18 @@ class HistoryTrim(BaseIPythonApplication):
class HistoryClear(HistoryTrim):
description = clear_hist_help
- keep = Int(0,
+ keep = Int(0,
help="Number of recent lines to keep in the database.")
- force = Bool(False,
- help="Don't prompt user for confirmation"
- ).tag(config=True)
+ force = Bool(False,
+ help="Don't prompt user for confirmation"
+ ).tag(config=True)
flags = Dict(dict(
force = ({'HistoryClear' : {'force' : True}},
- force.help),
+ force.help),
f = ({'HistoryTrim' : {'force' : True}},
- force.help
+ force.help
)
))
aliases = Dict()
diff --git a/contrib/python/ipython/py2/IPython/core/hooks.py b/contrib/python/ipython/py2/IPython/core/hooks.py
index e6fc84087f..a93bc31627 100644
--- a/contrib/python/ipython/py2/IPython/core/hooks.py
+++ b/contrib/python/ipython/py2/IPython/core/hooks.py
@@ -37,7 +37,7 @@ example, you could use a startup file like this::
import os
import subprocess
-import warnings
+import warnings
import sys
from IPython.core.error import TryNext
@@ -84,24 +84,24 @@ def editor(self, filename, linenum=None, wait=True):
import tempfile
def fix_error_editor(self,filename,linenum,column,msg):
- """DEPRECATED
-
- Open the editor at the given filename, linenumber, column and
+ """DEPRECATED
+
+ Open the editor at the given filename, linenumber, column and
show an error message. This is used for correcting syntax errors.
The current implementation only has special support for the VIM editor,
and falls back on the 'editor' hook if VIM is not used.
- Call ip.set_hook('fix_error_editor',yourfunc) to use your own function,
+ Call ip.set_hook('fix_error_editor',yourfunc) to use your own function,
"""
-
- warnings.warn("""
-`fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed
-in future versions. It appears to be used only for automatically fixing syntax
-error that has been broken for a few years and has thus been removed. If you
-happend to use this function and still need it please make your voice heard on
+
+ warnings.warn("""
+`fix_error_editor` is pending deprecation as of IPython 5.0 and will be removed
+in future versions. It appears to be used only for automatically fixing syntax
+error that has been broken for a few years and has thus been removed. If you
+happend to use this function and still need it please make your voice heard on
the mailing list ipython-dev@python.org , or on the GitHub Issue tracker:
-https://github.com/ipython/ipython/issues/9649 """, UserWarning)
-
+https://github.com/ipython/ipython/issues/9649 """, UserWarning)
+
def vim_quickfix_file():
t = tempfile.NamedTemporaryFile()
t.write('%s:%d:%d:%s\n' % (filename,linenum,column,msg))
diff --git a/contrib/python/ipython/py2/IPython/core/interactiveshell.py b/contrib/python/ipython/py2/IPython/core/interactiveshell.py
index ad8824b606..67b84a6e5f 100644
--- a/contrib/python/ipython/py2/IPython/core/interactiveshell.py
+++ b/contrib/python/ipython/py2/IPython/core/interactiveshell.py
@@ -31,7 +31,7 @@ from io import open as io_open
from pickleshare import PickleShareDB
from traitlets.config.configurable import SingletonConfigurable
-from IPython.core import oinspect
+from IPython.core import oinspect
from IPython.core import magic
from IPython.core import page
from IPython.core import prefilter
@@ -42,7 +42,7 @@ from IPython.core.autocall import ExitAutocall
from IPython.core.builtin_trap import BuiltinTrap
from IPython.core.events import EventManager, available_events
from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
-from IPython.core.debugger import Pdb
+from IPython.core.debugger import Pdb
from IPython.core.display_trap import DisplayTrap
from IPython.core.displayhook import DisplayHook
from IPython.core.displaypub import DisplayPublisher
@@ -50,14 +50,14 @@ from IPython.core.error import InputRejected, UsageError
from IPython.core.extensions import ExtensionManager
from IPython.core.formatters import DisplayFormatter
from IPython.core.history import HistoryManager
-from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
+from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
from IPython.core.logger import Logger
from IPython.core.macro import Macro
from IPython.core.payload import PayloadManager
from IPython.core.prefilter import PrefilterManager
from IPython.core.profiledir import ProfileDir
from IPython.core.usage import default_banner
-from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
+from IPython.testing.skipdoctest import skip_doctest_py2, skip_doctest
from IPython.display import display
from IPython.utils import PyColorize
from IPython.utils import io
@@ -67,45 +67,45 @@ from IPython.utils.decorators import undoc
from IPython.utils.io import ask_yes_no
from IPython.utils.ipstruct import Struct
from IPython.paths import get_ipython_dir
-from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
+from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists
from IPython.utils.process import system, getoutput
from IPython.utils.py3compat import (builtin_mod, unicode_type, string_types,
with_metaclass, iteritems)
from IPython.utils.strdispatch import StrDispatch
from IPython.utils.syspathcontext import prepended_to_syspath
-from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
-from IPython.utils.tempdir import TemporaryDirectory
-from traitlets import (
- Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
- observe, default,
-)
-from warnings import warn
-from logging import error
+from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
+from IPython.utils.tempdir import TemporaryDirectory
+from traitlets import (
+ Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
+ observe, default,
+)
+from warnings import warn
+from logging import error
import IPython.core.hooks
-# NoOpContext is deprecated, but ipykernel imports it from here.
-# See https://github.com/ipython/ipykernel/issues/157
-from IPython.utils.contexts import NoOpContext
-
-try:
- import docrepr.sphinxify as sphx
-
- def sphinxify(doc):
- with TemporaryDirectory() as dirname:
- return {
- 'text/html': sphx.sphinxify(doc, dirname),
- 'text/plain': doc
- }
-except ImportError:
- sphinxify = None
-
-
-class ProvisionalWarning(DeprecationWarning):
- """
- Warning class for unstable features
- """
- pass
-
+# NoOpContext is deprecated, but ipykernel imports it from here.
+# See https://github.com/ipython/ipykernel/issues/157
+from IPython.utils.contexts import NoOpContext
+
+try:
+ import docrepr.sphinxify as sphx
+
+ def sphinxify(doc):
+ with TemporaryDirectory() as dirname:
+ return {
+ 'text/html': sphx.sphinxify(doc, dirname),
+ 'text/plain': doc
+ }
+except ImportError:
+ sphinxify = None
+
+
+class ProvisionalWarning(DeprecationWarning):
+ """
+ Warning class for unstable features
+ """
+ pass
+
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
@@ -141,10 +141,10 @@ class SpaceInInput(Exception): pass
def get_default_colors():
- "DEPRECATED"
- warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
- DeprecationWarning, stacklevel=2)
- return 'Neutral'
+ "DEPRECATED"
+ warn('get_default_color is Deprecated, and is `Neutral` on all platforms.',
+ DeprecationWarning, stacklevel=2)
+ return 'Neutral'
class SeparateUnicode(Unicode):
@@ -187,28 +187,28 @@ class ExecutionResult(object):
if self.error_in_exec is not None:
raise self.error_in_exec
- def __repr__(self):
- if sys.version_info > (3,):
- name = self.__class__.__qualname__
- else:
- name = self.__class__.__name__
- return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
- (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
-
+ def __repr__(self):
+ if sys.version_info > (3,):
+ name = self.__class__.__qualname__
+ else:
+ name = self.__class__.__name__
+ return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
+ (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
+
class InteractiveShell(SingletonConfigurable):
"""An enhanced, interactive shell for Python."""
_instance = None
-
- ast_transformers = List([], help=
+
+ ast_transformers = List([], help=
"""
A list of ast.NodeTransformer subclass instances, which will be applied
to user input before code is run.
"""
- ).tag(config=True)
+ ).tag(config=True)
- autocall = Enum((0,1,2), default_value=0, help=
+ autocall = Enum((0,1,2), default_value=0, help=
"""
Make IPython automatically call any callable object even if you didn't
type explicit parentheses. For example, 'str 43' becomes 'str(43)'
@@ -217,29 +217,29 @@ class InteractiveShell(SingletonConfigurable):
arguments on the line, and '2' for 'full' autocall, where all callable
objects are automatically called (even if no arguments are present).
"""
- ).tag(config=True)
+ ).tag(config=True)
# TODO: remove all autoindent logic and put into frontends.
# We can't do this yet because even runlines uses the autoindent.
- autoindent = Bool(True, help=
+ autoindent = Bool(True, help=
"""
Autoindent IPython code entered interactively.
"""
- ).tag(config=True)
-
- automagic = Bool(True, help=
+ ).tag(config=True)
+
+ automagic = Bool(True, help=
"""
Enable magic commands to be called without the leading %.
"""
- ).tag(config=True)
-
- banner1 = Unicode(default_banner,
+ ).tag(config=True)
+
+ banner1 = Unicode(default_banner,
help="""The part of the banner to be printed before the profile"""
- ).tag(config=True)
- banner2 = Unicode('',
+ ).tag(config=True)
+ banner2 = Unicode('',
help="""The part of the banner to be printed after the profile"""
- ).tag(config=True)
+ ).tag(config=True)
- cache_size = Integer(1000, help=
+ cache_size = Integer(1000, help=
"""
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
@@ -248,20 +248,20 @@ class InteractiveShell(SingletonConfigurable):
issued). This limit is defined because otherwise you'll spend more
time re-flushing a too small cache than working
"""
- ).tag(config=True)
- color_info = Bool(True, help=
+ ).tag(config=True)
+ color_info = Bool(True, help=
"""
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.
"""
- ).tag(config=True)
- colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
- default_value='Neutral',
- help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
- ).tag(config=True)
- debug = Bool(False).tag(config=True)
- deep_reload = Bool(False, help=
+ ).tag(config=True)
+ colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
+ default_value='Neutral',
+ help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
+ ).tag(config=True)
+ debug = Bool(False).tag(config=True)
+ deep_reload = Bool(False, help=
"""
**Deprecated**
@@ -275,47 +275,47 @@ class InteractiveShell(SingletonConfigurable):
deep_reload is off, IPython will use the normal reload(), but
deep_reload will still be available as dreload().
"""
- ).tag(config=True)
- disable_failing_post_execute = Bool(False,
+ ).tag(config=True)
+ disable_failing_post_execute = Bool(False,
help="Don't call post-execute functions that have failed in the past."
- ).tag(config=True)
+ ).tag(config=True)
display_formatter = Instance(DisplayFormatter, allow_none=True)
displayhook_class = Type(DisplayHook)
display_pub_class = Type(DisplayPublisher)
-
- sphinxify_docstring = Bool(False, help=
- """
- Enables rich html representation of docstrings. (This requires the
- docrepr module).
- """).tag(config=True)
-
- @observe("sphinxify_docstring")
- def _sphinxify_docstring_changed(self, change):
- if change['new']:
- warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
-
- enable_html_pager = Bool(False, help=
- """
- (Provisional API) enables html representation in mime bundles sent
- to pagers.
- """).tag(config=True)
-
- @observe("enable_html_pager")
- def _enable_html_pager_changed(self, change):
- if change['new']:
- warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
-
+
+ sphinxify_docstring = Bool(False, help=
+ """
+ Enables rich html representation of docstrings. (This requires the
+ docrepr module).
+ """).tag(config=True)
+
+ @observe("sphinxify_docstring")
+ def _sphinxify_docstring_changed(self, change):
+ if change['new']:
+ warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
+
+ enable_html_pager = Bool(False, help=
+ """
+ (Provisional API) enables html representation in mime bundles sent
+ to pagers.
+ """).tag(config=True)
+
+ @observe("enable_html_pager")
+ def _enable_html_pager_changed(self, change):
+ if change['new']:
+ warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
+
data_pub_class = None
- exit_now = Bool(False)
+ exit_now = Bool(False)
exiter = Instance(ExitAutocall)
- @default('exiter')
+ @default('exiter')
def _exiter_default(self):
return ExitAutocall(self)
# Monotonically increasing execution counter
execution_count = Integer(1)
filename = Unicode("<ipython console>")
- ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
+ ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
# Input splitter, to transform input line by line and detect when a block
# is ready to be executed.
@@ -327,90 +327,90 @@ class InteractiveShell(SingletonConfigurable):
input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
(), {'line_input_checker': False})
- logstart = Bool(False, help=
+ logstart = Bool(False, help=
"""
Start logging to the default log file in overwrite mode.
Use `logappend` to specify a log file to **append** logs to.
"""
- ).tag(config=True)
- logfile = Unicode('', help=
+ ).tag(config=True)
+ logfile = Unicode('', help=
"""
The name of the logfile to use.
"""
- ).tag(config=True)
- logappend = Unicode('', help=
+ ).tag(config=True)
+ logappend = Unicode('', help=
"""
Start logging to the given file in append mode.
Use `logfile` to specify a log file to **overwrite** logs to.
"""
- ).tag(config=True)
+ ).tag(config=True)
object_info_string_level = Enum((0,1,2), default_value=0,
- ).tag(config=True)
- pdb = Bool(False, help=
+ ).tag(config=True)
+ pdb = Bool(False, help=
"""
Automatically call the pdb debugger after every exception.
"""
- ).tag(config=True)
- display_page = Bool(False,
+ ).tag(config=True)
+ display_page = Bool(False,
help="""If True, anything that would be passed to the pager
will be displayed as regular output instead."""
- ).tag(config=True)
+ ).tag(config=True)
# deprecated prompt traits:
-
- prompt_in1 = Unicode('In [\\#]: ',
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
- prompt_in2 = Unicode(' .\\D.: ',
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
- prompt_out = Unicode('Out[\\#]: ',
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
- prompts_pad_left = Bool(True,
- help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
- ).tag(config=True)
-
- @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
- def _prompt_trait_changed(self, change):
- name = change['name']
- warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
- name=name)
+
+ prompt_in1 = Unicode('In [\\#]: ',
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+ prompt_in2 = Unicode(' .\\D.: ',
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+ prompt_out = Unicode('Out[\\#]: ',
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+ prompts_pad_left = Bool(True,
+ help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
+ ).tag(config=True)
+
+ @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
+ def _prompt_trait_changed(self, change):
+ name = change['name']
+ warn("InteractiveShell.{name} is deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly.".format(
+ name=name)
)
# protect against weird cases where self.config may not exist:
- show_rewritten_input = Bool(True,
+ show_rewritten_input = Bool(True,
help="Show rewritten input, e.g. for autocall."
- ).tag(config=True)
+ ).tag(config=True)
- quiet = Bool(False).tag(config=True)
+ quiet = Bool(False).tag(config=True)
- history_length = Integer(10000,
- help='Total length of command history'
- ).tag(config=True)
+ history_length = Integer(10000,
+ help='Total length of command history'
+ ).tag(config=True)
- history_load_length = Integer(1000, help=
+ history_load_length = Integer(1000, help=
"""
The number of saved history entries to be loaded
- into the history buffer at startup.
+ into the history buffer at startup.
"""
- ).tag(config=True)
+ ).tag(config=True)
ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
- default_value='last_expr',
+ default_value='last_expr',
help="""
'all', 'last', 'last_expr' or 'none', specifying which nodes should be
- run interactively (displaying output from expressions)."""
- ).tag(config=True)
+ run interactively (displaying output from expressions)."""
+ ).tag(config=True)
# TODO: this part of prompt management should be moved to the frontends.
# Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
- 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)
+ 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)
xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
- default_value='Context').tag(config=True)
+ default_value='Context').tag(config=True)
# Subcomponents of InteractiveShell
alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
@@ -436,8 +436,8 @@ class InteractiveShell(SingletonConfigurable):
# Tracks any GUI loop loaded for pylab
pylab_gui_select = None
- last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
-
+ last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
+
def __init__(self, ipython_dir=None, profile_dir=None,
user_module=None, user_ns=None,
custom_exceptions=((), None), **kwargs):
@@ -445,9 +445,9 @@ class InteractiveShell(SingletonConfigurable):
# This is where traits with a config_key argument are updated
# from the values on config.
super(InteractiveShell, self).__init__(**kwargs)
- 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')
+ 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')
self.configurables = [self]
# These are relatively independent and stateless
@@ -455,7 +455,7 @@ class InteractiveShell(SingletonConfigurable):
self.init_profile_dir(profile_dir)
self.init_instance_attrs()
self.init_environment()
-
+
# Check if we're in a virtualenv, and set up sys.path.
self.init_virtualenv()
@@ -522,12 +522,12 @@ class InteractiveShell(SingletonConfigurable):
#-------------------------------------------------------------------------
# Trait changed handlers
#-------------------------------------------------------------------------
- @observe('ipython_dir')
- def _ipython_dir_changed(self, change):
- ensure_dir_exists(change['new'])
+ @observe('ipython_dir')
+ def _ipython_dir_changed(self, change):
+ ensure_dir_exists(change['new'])
def set_autoindent(self,value=None):
- """Set the autoindent flag.
+ """Set the autoindent flag.
If called with no arguments, it acts as a toggle."""
if value is None:
@@ -598,10 +598,10 @@ class InteractiveShell(SingletonConfigurable):
pyformat = PyColorize.Parser().format
self.pycolorize = lambda src: pyformat(src,'str',self.colors)
- def refresh_style(self):
- # No-op here, used in subclass
- pass
-
+ def refresh_style(self):
+ # No-op here, used in subclass
+ pass
+
def init_pushd_popd_magic(self):
# for pushd/popd management
self.home_dir = get_home_dir()
@@ -653,10 +653,10 @@ class InteractiveShell(SingletonConfigurable):
# override sys.stdout and sys.stderr themselves, you need to do that
# *before* instantiating this class, because io holds onto
# references to the underlying streams.
- # 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.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)
@@ -700,15 +700,15 @@ class InteractiveShell(SingletonConfigurable):
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.
-
+
Adapted from code snippets online.
-
+
http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
"""
if 'VIRTUAL_ENV' not in os.environ:
# Not in a virtualenv
return
-
+
# venv detection:
# 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.
@@ -722,15 +722,15 @@ class InteractiveShell(SingletonConfigurable):
if any(p.startswith(p_venv) for p in paths):
# Running properly in the virtualenv, don't need to do anything
return
-
+
warn("Attempting to work in a virtualenv. If you encounter problems, please "
"install IPython inside the virtualenv.")
if sys.platform == "win32":
- virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
+ virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
else:
virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
'python%d.%d' % sys.version_info[:2], 'site-packages')
-
+
import site
sys.path.insert(0, virtual_env)
site.addsitedir(virtual_env)
@@ -765,7 +765,7 @@ class InteractiveShell(SingletonConfigurable):
#-------------------------------------------------------------------------
# Things related to the banner
#-------------------------------------------------------------------------
-
+
@property
def banner(self):
banner = self.banner1
@@ -778,8 +778,8 @@ class InteractiveShell(SingletonConfigurable):
def show_banner(self, banner=None):
if banner is None:
banner = self.banner
- sys.stdout.write(banner)
-
+ sys.stdout.write(banner)
+
#-------------------------------------------------------------------------
# Things related to hooks
#-------------------------------------------------------------------------
@@ -796,10 +796,10 @@ class InteractiveShell(SingletonConfigurable):
# default hooks have priority 100, i.e. low; user hooks should have
# 0-100 priority
self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
-
+
if self.display_page:
self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
-
+
def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
_warn_deprecated=True):
"""set_hook(name,hook) -> sets an internal IPython hook.
@@ -857,13 +857,13 @@ class InteractiveShell(SingletonConfigurable):
def register_post_execute(self, func):
"""DEPRECATED: Use ip.events.register('post_run_cell', func)
-
+
Register a function for calling after code execution.
"""
warn("ip.register_post_execute is deprecated, use "
"ip.events.register('post_run_cell', func) instead.")
self.events.register('post_run_cell', func)
-
+
def _clear_warning_registry(self):
# clear the warning registry, so that different code blocks with
# overlapping line number ranges don't cause spurious suppression of
@@ -877,14 +877,14 @@ class InteractiveShell(SingletonConfigurable):
def new_main_mod(self, filename, modname):
"""Return a new 'main' module object for user code execution.
-
+
``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.
-
+
``modname`` should be the module name - normally either '__main__' or
the basename of the file without the extension.
-
+
When scripts are executed via %run, we must keep a reference to their
__main__ module around so that Python doesn't
clear it, rendering references to module globals useless.
@@ -905,12 +905,12 @@ class InteractiveShell(SingletonConfigurable):
else:
main_mod.__dict__.clear()
main_mod.__name__ = modname
-
+
main_mod.__file__ = filename
# It seems pydoc (and perhaps others) needs any module instance to
# implement a __nonzero__ method
main_mod.__nonzero__ = lambda : True
-
+
return main_mod
def clear_main_mod_cache(self):
@@ -962,7 +962,7 @@ class InteractiveShell(SingletonConfigurable):
'Control auto-activation of pdb at exceptions')
def debugger(self,force=False):
- """Call the pdb debugger.
+ """Call the pdb debugger.
Keywords:
@@ -979,7 +979,7 @@ class InteractiveShell(SingletonConfigurable):
error('No traceback has been produced, nothing to debug.')
return
- self.InteractiveTB.debugger(force=True)
+ self.InteractiveTB.debugger(force=True)
#-------------------------------------------------------------------------
# Things related to IPython's various namespaces
@@ -1063,17 +1063,17 @@ class InteractiveShell(SingletonConfigurable):
'user_local':self.user_ns,
'builtin':builtin_mod.__dict__
}
-
+
@property
def user_global_ns(self):
return self.user_module.__dict__
def prepare_user_module(self, user_module=None, user_ns=None):
"""Prepare the module and namespace in which user code will be run.
-
+
When IPython is started normally, both parameters are None: a new module
is created automatically, and its __dict__ used as the namespace.
-
+
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
@@ -1096,17 +1096,17 @@ class InteractiveShell(SingletonConfigurable):
user_ns.setdefault("__name__", "__main__")
user_module = DummyMod()
user_module.__dict__ = user_ns
-
+
if user_module is None:
user_module = types.ModuleType("__main__",
doc="Automatically created module for IPython interactive environment")
-
+
# 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
user_module.__dict__.setdefault('__builtin__', builtin_mod)
user_module.__dict__.setdefault('__builtins__', builtin_mod)
-
+
if user_ns is None:
user_ns = user_module.__dict__
@@ -1162,7 +1162,7 @@ class InteractiveShell(SingletonConfigurable):
# For more details:
# http://mail.python.org/pipermail/python-dev/2001-April/014068.html
ns = dict()
-
+
# make global variables for user access to the histories
ns['_ih'] = self.history_manager.input_hist_parsed
ns['_oh'] = self.history_manager.output_hist
@@ -1177,7 +1177,7 @@ class InteractiveShell(SingletonConfigurable):
# Store myself as the public api!!!
ns['get_ipython'] = self.get_ipython
-
+
ns['exit'] = self.exiter
ns['quit'] = self.exiter
@@ -1191,12 +1191,12 @@ class InteractiveShell(SingletonConfigurable):
# Finally, update the real user's namespace
self.user_ns.update(ns)
-
+
@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.
-
+
Note that this does not include the displayhook, which also caches
objects from the output."""
return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
@@ -1230,9 +1230,9 @@ class InteractiveShell(SingletonConfigurable):
drop_keys.discard('__name__')
for k in drop_keys:
del ns[k]
-
+
self.user_ns_hidden.clear()
-
+
# Restore the user namespaces to minimal usability
self.init_user_ns()
@@ -1261,7 +1261,7 @@ class InteractiveShell(SingletonConfigurable):
raise ValueError("Refusing to delete %s" % varname)
ns_refs = self.all_ns_refs
-
+
if by_name: # Delete by name
for ns in ns_refs:
try:
@@ -1358,11 +1358,11 @@ class InteractiveShell(SingletonConfigurable):
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.
-
+
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.
-
+
Parameters
----------
variables : dict
@@ -1520,20 +1520,20 @@ class InteractiveShell(SingletonConfigurable):
def _inspect(self, meth, oname, namespaces=None, **kw):
"""Generic interface to the inspector system.
- This function is meant to be called by pdef, pdoc & friends.
- """
+ This function is meant to be called by pdef, pdoc & friends.
+ """
info = self._object_find(oname, namespaces)
- docformat = sphinxify if self.sphinxify_docstring else None
+ docformat = sphinxify if self.sphinxify_docstring else None
if info.found:
pmethod = getattr(self.inspector, meth)
- # TODO: only apply format_screen to the plain/text repr of the mime
- # bundle.
- formatter = format_screen if info.ismagic else docformat
+ # TODO: only apply format_screen to the plain/text repr of the mime
+ # bundle.
+ formatter = format_screen if info.ismagic else docformat
if meth == 'pdoc':
pmethod(info.obj, oname, formatter)
elif meth == 'pinfo':
- pmethod(info.obj, oname, formatter, info,
- enable_html_pager=self.enable_html_pager, **kw)
+ pmethod(info.obj, oname, formatter, info,
+ enable_html_pager=self.enable_html_pager, **kw)
else:
pmethod(info.obj, oname)
else:
@@ -1553,18 +1553,18 @@ class InteractiveShell(SingletonConfigurable):
def object_inspect_text(self, oname, detail_level=0):
"""Get object info as formatted text"""
- 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'`.
- """
+ 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'`.
+ """
with self.builtin_trap:
info = self._object_find(oname)
if info.found:
- return self.inspector._get_info(info.obj, oname, info=info,
+ return self.inspector._get_info(info.obj, oname, info=info,
detail_level=detail_level
)
else:
@@ -1583,8 +1583,8 @@ class InteractiveShell(SingletonConfigurable):
# Things related to exception handling and tracebacks (not debugging)
#-------------------------------------------------------------------------
- debugger_cls = Pdb
-
+ debugger_cls = Pdb
+
def init_traceback_handlers(self, custom_exceptions):
# Syntax error handler.
self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
@@ -1595,8 +1595,8 @@ class InteractiveShell(SingletonConfigurable):
self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
color_scheme='NoColor',
tb_offset = 1,
- check_cache=check_linecache_ipython,
- debugger_cls=self.debugger_cls)
+ check_cache=check_linecache_ipython,
+ debugger_cls=self.debugger_cls)
# 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
@@ -1610,7 +1610,7 @@ class InteractiveShell(SingletonConfigurable):
self.InteractiveTB.set_mode(mode=self.xmode)
def set_custom_exc(self, exc_tuple, handler):
- """set_custom_exc(exc_tuple, handler)
+ """set_custom_exc(exc_tuple, handler)
Set a custom exception handler, which will be called if any of the
exceptions in exc_tuple occur in the mainloop (specifically, in the
@@ -1653,19 +1653,19 @@ class InteractiveShell(SingletonConfigurable):
assert type(exc_tuple)==type(()) , \
"The custom exceptions must be given AS A TUPLE."
- def dummy_handler(self, etype, value, tb, tb_offset=None):
+ def dummy_handler(self, etype, value, tb, tb_offset=None):
print('*** Simple custom exception handler ***')
print('Exception type :',etype)
print('Exception value:',value)
print('Traceback :',tb)
#print 'Source code :','\n'.join(self.buffer)
-
+
def validate_stb(stb):
"""validate structured traceback return type
-
+
return type of CustomTB *should* be a list of strings, but allow
single strings or None, which are harmless.
-
+
This function will *always* return a list of strings,
and will raise a TypeError if stb is inappropriate.
"""
@@ -1688,7 +1688,7 @@ class InteractiveShell(SingletonConfigurable):
else:
def wrapped(self,etype,value,tb,tb_offset=None):
"""wrap CustomTB handler, to protect IPython from user code
-
+
This makes it harder (but not impossible) for custom exception
handlers to crash IPython.
"""
@@ -1698,11 +1698,11 @@ class InteractiveShell(SingletonConfigurable):
except:
# clear custom handler immediately
self.set_custom_exc((), None)
- print("Custom TB Handler failed, unregistering", file=sys.stderr)
+ print("Custom TB Handler failed, unregistering", file=sys.stderr)
# show the exception in handler first
stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
- print(self.InteractiveTB.stb2text(stb))
- print("The original exception:")
+ print(self.InteractiveTB.stb2text(stb))
+ print("The original exception:")
stb = self.InteractiveTB.structured_traceback(
(etype,value,tb), tb_offset=tb_offset
)
@@ -1737,10 +1737,10 @@ class InteractiveShell(SingletonConfigurable):
def _get_exc_info(self, exc_tuple=None):
"""get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
-
+
Ensures sys.last_type,value,traceback hold the exc_info we found,
from whichever source.
-
+
raises ValueError if none of these contain any information
"""
if exc_tuple is None:
@@ -1752,10 +1752,10 @@ class InteractiveShell(SingletonConfigurable):
if hasattr(sys, 'last_type'):
etype, value, tb = sys.last_type, sys.last_value, \
sys.last_traceback
-
+
if etype is None:
raise ValueError("No exception to find")
-
+
# 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
@@ -1764,16 +1764,16 @@ class InteractiveShell(SingletonConfigurable):
sys.last_type = etype
sys.last_value = value
sys.last_traceback = tb
-
+
return etype, value, tb
-
+
def show_usage_error(self, exc):
"""Show a short message for UsageErrors
-
+
These are special exceptions that shouldn't show a traceback.
"""
- print("UsageError: %s" % exc, file=sys.stderr)
-
+ print("UsageError: %s" % exc, file=sys.stderr)
+
def get_exception_only(self, exc_tuple=None):
"""
Return as a string (ending with a newline) the exception that
@@ -1800,9 +1800,9 @@ class InteractiveShell(SingletonConfigurable):
try:
etype, value, tb = self._get_exc_info(exc_tuple)
except ValueError:
- print('No traceback available to show.', file=sys.stderr)
+ print('No traceback available to show.', file=sys.stderr)
return
-
+
if issubclass(etype, SyntaxError):
# Though this won't be called by syntax errors in the input
# line, there may be SyntaxError cases with imported code.
@@ -1835,7 +1835,7 @@ class InteractiveShell(SingletonConfigurable):
self._showtraceback(etype, value, stb)
except KeyboardInterrupt:
- print('\n' + self.get_exception_only(), file=sys.stderr)
+ print('\n' + self.get_exception_only(), file=sys.stderr)
def _showtraceback(self, etype, evalue, stb):
"""Actually show a traceback.
@@ -1843,7 +1843,7 @@ class InteractiveShell(SingletonConfigurable):
Subclasses may override this method to put the traceback on a different
place, like a side channel.
"""
- print(self.InteractiveTB.stb2text(stb))
+ print(self.InteractiveTB.stb2text(stb))
def showsyntaxerror(self, filename=None):
"""Display the syntax error that just occurred.
@@ -1862,7 +1862,7 @@ class InteractiveShell(SingletonConfigurable):
except:
# Not the format we expect; leave it alone
pass
-
+
stb = self.SyntaxTB.structured_traceback(etype, value, [])
self._showtraceback(etype, value, stb)
@@ -1881,12 +1881,12 @@ class InteractiveShell(SingletonConfigurable):
#-------------------------------------------------------------------------
def init_readline(self):
- """DEPRECATED
-
- Moved to terminal subclass, here only to simplify the init logic."""
+ """DEPRECATED
+
+ Moved to terminal subclass, here only to simplify the init logic."""
# Set a number of methods that depend on readline to be no-op
- warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
- DeprecationWarning, stacklevel=2)
+ warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
+ DeprecationWarning, stacklevel=2)
self.set_custom_completer = no_op
@skip_doctest
@@ -1923,7 +1923,7 @@ class InteractiveShell(SingletonConfigurable):
self.Completer = IPCompleter(shell=self,
namespace=self.user_ns,
global_namespace=self.user_global_ns,
- use_readline=False,
+ use_readline=False,
parent=self,
)
self.configurables.append(self.Completer)
@@ -1941,7 +1941,7 @@ class InteractiveShell(SingletonConfigurable):
self.set_hook('complete_command', reset_completer, str_key = '%reset')
- @skip_doctest_py2
+ @skip_doctest_py2
def complete(self, text, line=None, cursor_pos=None):
"""Return the completed text and a list of completions.
@@ -2020,7 +2020,7 @@ class InteractiveShell(SingletonConfigurable):
self.register_magics = self.magics_manager.register
self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
- m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
+ m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
)
@@ -2040,11 +2040,11 @@ class InteractiveShell(SingletonConfigurable):
# should be split into a prompt manager and displayhook. We probably
# even need a centralize colors management object.
self.magic('colors %s' % self.colors)
-
+
# 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):
- self.magics_manager.register_function(func,
+ self.magics_manager.register_function(func,
magic_kind=magic_kind, magic_name=magic_name)
def run_line_magic(self, magic_name, line):
@@ -2083,7 +2083,7 @@ class InteractiveShell(SingletonConfigurable):
def run_cell_magic(self, magic_name, line, cell):
"""Execute the given cell magic.
-
+
Parameters
----------
magic_name : str
@@ -2230,7 +2230,7 @@ class InteractiveShell(SingletonConfigurable):
try:
ec = os.system(cmd)
except KeyboardInterrupt:
- print('\n' + self.get_exception_only(), file=sys.stderr)
+ print('\n' + self.get_exception_only(), file=sys.stderr)
ec = -2
else:
cmd = py3compat.unicode_to_str(cmd)
@@ -2249,11 +2249,11 @@ class InteractiveShell(SingletonConfigurable):
ec = subprocess.call(cmd, shell=True, executable=executable)
except KeyboardInterrupt:
# intercept control-C; a long traceback is not useful here
- print('\n' + self.get_exception_only(), file=sys.stderr)
+ print('\n' + self.get_exception_only(), file=sys.stderr)
ec = 130
if ec > 128:
ec = -(ec - 128)
-
+
# 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. Note the semantics
@@ -2316,7 +2316,7 @@ class InteractiveShell(SingletonConfigurable):
def init_payload(self):
self.payload_manager = PayloadManager(parent=self)
self.configurables.append(self.payload_manager)
-
+
#-------------------------------------------------------------------------
# Things related to the prefilter
#-------------------------------------------------------------------------
@@ -2347,8 +2347,8 @@ class InteractiveShell(SingletonConfigurable):
if not self.show_rewritten_input:
return
- # This is overridden in TerminalInteractiveShell to use fancy prompts
- print("------> " + cmd)
+ # This is overridden in TerminalInteractiveShell to use fancy prompts
+ print("------> " + cmd)
#-------------------------------------------------------------------------
# Things related to extracting values/expressions from kernel and user_ns
@@ -2356,13 +2356,13 @@ class InteractiveShell(SingletonConfigurable):
def _user_obj_error(self):
"""return simple exception dict
-
+
for use in user_expressions
"""
-
+
etype, evalue, tb = self._get_exc_info()
stb = self.InteractiveTB.get_exception_only(etype, evalue)
-
+
exc_info = {
u'status' : 'error',
u'traceback' : stb,
@@ -2371,13 +2371,13 @@ class InteractiveShell(SingletonConfigurable):
}
return exc_info
-
+
def _format_user_obj(self, obj):
"""format a user object to display dict
-
+
for use in user_expressions
"""
-
+
data, md = self.display_formatter.format(obj)
value = {
'status' : 'ok',
@@ -2385,7 +2385,7 @@ class InteractiveShell(SingletonConfigurable):
'metadata' : md,
}
return value
-
+
def user_expressions(self, expressions):
"""Evaluate a dict of expressions in the user's namespace.
@@ -2404,7 +2404,7 @@ class InteractiveShell(SingletonConfigurable):
out = {}
user_ns = self.user_ns
global_ns = self.user_global_ns
-
+
for key, expr in iteritems(expressions):
try:
value = self._format_user_obj(eval(expr, global_ns, user_ns))
@@ -2475,7 +2475,7 @@ class InteractiveShell(SingletonConfigurable):
# Python inserts the script's directory into sys.path
dname = os.path.dirname(fname)
- with prepended_to_syspath(dname), self.builtin_trap:
+ with prepended_to_syspath(dname), self.builtin_trap:
try:
glob, loc = (where + (None, ))[:2]
py3compat.execfile(
@@ -2532,7 +2532,7 @@ class InteractiveShell(SingletonConfigurable):
# behavior of running a script from the system command line, where
# Python inserts the script's directory into sys.path
dname = os.path.dirname(fname)
-
+
def get_cells():
"""generator for sequence of code blocks to run"""
if fname.endswith('.ipynb'):
@@ -2616,9 +2616,9 @@ class InteractiveShell(SingletonConfigurable):
result = ExecutionResult()
if (not raw_cell) or raw_cell.isspace():
- self.last_execution_succeeded = True
+ self.last_execution_succeeded = True
return result
-
+
if silent:
store_history = False
@@ -2629,7 +2629,7 @@ class InteractiveShell(SingletonConfigurable):
if store_history:
self.execution_count += 1
result.error_before_exec = value
- self.last_execution_succeeded = False
+ self.last_execution_succeeded = False
return result
self.events.trigger('pre_execute')
@@ -2685,10 +2685,10 @@ class InteractiveShell(SingletonConfigurable):
# Compile to bytecode
try:
code_ast = compiler.ast_parse(cell, filename=cell_name)
- except self.custom_exceptions as e:
- etype, value, tb = sys.exc_info()
- self.CustomTB(etype, value, tb)
- return error_before_exec(e)
+ except self.custom_exceptions as e:
+ etype, value, tb = sys.exc_info()
+ self.CustomTB(etype, value, tb)
+ return error_before_exec(e)
except IndentationError as e:
self.showindentationerror()
return error_before_exec(e)
@@ -2710,10 +2710,10 @@ class InteractiveShell(SingletonConfigurable):
# Execute the user code
interactivity = "none" if silent else self.ast_node_interactivity
- has_raised = self.run_ast_nodes(code_ast.body, cell_name,
+ has_raised = self.run_ast_nodes(code_ast.body, cell_name,
interactivity=interactivity, compiler=compiler, result=result)
-
- self.last_execution_succeeded = not has_raised
+
+ self.last_execution_succeeded = not has_raised
# Reset this so later displayed values do not modify the
# ExecutionResult
@@ -2731,16 +2731,16 @@ class InteractiveShell(SingletonConfigurable):
self.execution_count += 1
return result
-
+
def transform_ast(self, node):
"""Apply the AST transformations from self.ast_transformers
-
+
Parameters
----------
node : ast.Node
The root node to be transformed. Typically called with the ast.Module
produced by parsing user input.
-
+
Returns
-------
An ast.Node corresponding to the node it was called with. Note that it
@@ -2758,11 +2758,11 @@ class InteractiveShell(SingletonConfigurable):
except Exception:
warn("AST transformer %r threw an error. It will be unregistered." % transformer)
self.ast_transformers.remove(transformer)
-
+
if self.ast_transformers:
ast.fix_missing_locations(node)
return node
-
+
def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
compiler=compile, result=None):
@@ -2883,7 +2883,7 @@ class InteractiveShell(SingletonConfigurable):
if result is not None:
result.error_in_exec = e
self.showtraceback(exception_only=True)
- warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
+ warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
except self.custom_exceptions:
etype, value, tb = sys.exc_info()
if result is not None:
@@ -2928,17 +2928,17 @@ class InteractiveShell(SingletonConfigurable):
def enable_gui(self, gui=None):
raise NotImplementedError('Implement enable_gui in a subclass')
-
+
def enable_matplotlib(self, gui=None):
"""Enable interactive matplotlib and inline figure support.
-
+
This takes the following steps:
-
+
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
-
+
Parameters
----------
gui : optional, string
@@ -2952,7 +2952,7 @@ class InteractiveShell(SingletonConfigurable):
"""
from IPython.core import pylabtools as pt
gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
-
+
if gui != 'inline':
# If we have our first gui selection, store it
if self.pylab_gui_select is None:
@@ -2962,16 +2962,16 @@ class InteractiveShell(SingletonConfigurable):
print ('Warning: Cannot change to a different GUI toolkit: %s.'
' Using %s instead.' % (gui, self.pylab_gui_select))
gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
-
+
pt.activate_matplotlib(backend)
pt.configure_inline_support(self, backend)
-
+
# 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)
-
+
return gui, backend
def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
@@ -2981,7 +2981,7 @@ class InteractiveShell(SingletonConfigurable):
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
optionally selected with the optional ``gui`` argument.
-
+
This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
Parameters
@@ -3001,9 +3001,9 @@ class InteractiveShell(SingletonConfigurable):
This argument is ignored, no welcome message will be displayed.
"""
from IPython.core.pylabtools import import_pylab
-
+
gui, backend = self.enable_matplotlib(gui)
-
+
# 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
@@ -3076,19 +3076,19 @@ class InteractiveShell(SingletonConfigurable):
tmp_file.close()
return filename
- @undoc
+ @undoc
def write(self,data):
- """DEPRECATED: Write a string to the default output"""
- warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
- DeprecationWarning, stacklevel=2)
- sys.stdout.write(data)
+ """DEPRECATED: Write a string to the default output"""
+ warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
+ DeprecationWarning, stacklevel=2)
+ sys.stdout.write(data)
- @undoc
+ @undoc
def write_err(self,data):
- """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)
+ """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)
def ask_yes_no(self, prompt, default=None, interrupt=None):
if self.quiet:
@@ -3160,8 +3160,8 @@ class InteractiveShell(SingletonConfigurable):
if code:
return code
try:
- if target.startswith(('http://', 'https://')):
- return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
+ if target.startswith(('http://', 'https://')):
+ return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
except UnicodeDecodeError:
if not py_only :
# Deferred import
@@ -3171,7 +3171,7 @@ class InteractiveShell(SingletonConfigurable):
from urllib import urlopen
response = urlopen(target)
return response.read().decode('latin1')
- raise ValueError(("'%s' seem to be unreadable.") % target)
+ raise ValueError(("'%s' seem to be unreadable.") % target)
potential_target = [target]
try :
@@ -3253,11 +3253,11 @@ class InteractiveShell(SingletonConfigurable):
self.restore_sys_module_state()
- # Overridden in terminal subclass to change prompts
- def switch_doctest_mode(self, mode):
- pass
-
-
+ # Overridden in terminal subclass to change prompts
+ def switch_doctest_mode(self, mode):
+ pass
+
+
class InteractiveShellABC(with_metaclass(abc.ABCMeta, object)):
"""An abstract base class for InteractiveShell."""
diff --git a/contrib/python/ipython/py2/IPython/core/magic.py b/contrib/python/ipython/py2/IPython/core/magic.py
index 61a929fd23..f3a0b5be33 100644
--- a/contrib/python/ipython/py2/IPython/core/magic.py
+++ b/contrib/python/ipython/py2/IPython/core/magic.py
@@ -27,8 +27,8 @@ from IPython.utils.ipstruct import Struct
from IPython.utils.process import arg_split
from IPython.utils.py3compat import string_types, iteritems
from IPython.utils.text import dedent
-from traitlets import Bool, Dict, Instance, observe
-from logging import error
+from traitlets import Bool, Dict, Instance, observe
+from logging import error
#-----------------------------------------------------------------------------
# Globals
@@ -298,12 +298,12 @@ class MagicsManager(Configurable):
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
- auto_magic = Bool(True, help=
- "Automatically call line magics without requiring explicit % prefix"
- ).tag(config=True)
- @observe('auto_magic')
- def _auto_magic_changed(self, change):
- self.shell.automagic = change['new']
+ auto_magic = Bool(True, help=
+ "Automatically call line magics without requiring explicit % prefix"
+ ).tag(config=True)
+ @observe('auto_magic')
+ def _auto_magic_changed(self, change):
+ self.shell.automagic = change['new']
_auto_status = [
'Automagic is OFF, % prefix IS needed for line magics.',
diff --git a/contrib/python/ipython/py2/IPython/core/magics/auto.py b/contrib/python/ipython/py2/IPython/core/magics/auto.py
index f87bafdeb1..dc229d509b 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/auto.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/auto.py
@@ -1,7 +1,7 @@
"""Implementation of magic functions that control various automatic behaviors.
"""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
@@ -17,7 +17,7 @@ from __future__ import absolute_import
# Our own packages
from IPython.core.magic import Bunch, Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
-from logging import error
+from logging import error
#-----------------------------------------------------------------------------
# Magic implementation classes
diff --git a/contrib/python/ipython/py2/IPython/core/magics/basic.py b/contrib/python/ipython/py2/IPython/core/magics/basic.py
index ca69e2e698..529cdd2b65 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/basic.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/basic.py
@@ -1,7 +1,7 @@
"""Implementation of basic magic functions."""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
import argparse
import io
@@ -15,8 +15,8 @@ from IPython.utils.text import format_screen, dedent, indent
from IPython.testing.skipdoctest import skip_doctest
from IPython.utils.ipstruct import Struct
from IPython.utils.py3compat import unicode_type
-from warnings import warn
-from logging import error
+from warnings import warn
+from logging import error
class MagicsDisplay(object):
@@ -328,7 +328,7 @@ Currently the magic system has the following functions:""",
"""
def color_switch_err(name):
warn('Error changing %s color schemes.\n%s' %
- (name, sys.exc_info()[1]), stacklevel=2)
+ (name, sys.exc_info()[1]), stacklevel=2)
new_scheme = parameter_s.strip()
@@ -338,13 +338,13 @@ Currently the magic system has the following functions:""",
# local shortcut
shell = self.shell
- # Set shell colour scheme
+ # Set shell colour scheme
try:
- shell.colors = new_scheme
- shell.refresh_style()
+ shell.colors = new_scheme
+ shell.refresh_style()
except:
- color_switch_err('shell')
-
+ color_switch_err('shell')
+
# Set exception colors
try:
shell.InteractiveTB.set_colors(scheme = new_scheme)
@@ -458,12 +458,12 @@ Currently the magic system has the following functions:""",
shell.magic('xmode ' + dstore.xmode)
- # mode here is the state before we switch; switch_doctest_mode takes
- # the mode we're switching to.
- shell.switch_doctest_mode(not mode)
-
+ # mode here is the state before we switch; switch_doctest_mode takes
+ # the mode we're switching to.
+ shell.switch_doctest_mode(not mode)
+
# Store new mode and inform
- dstore.mode = bool(not mode)
+ dstore.mode = bool(not mode)
mode_label = ['OFF','ON'][dstore.mode]
print('Doctest mode is:', mode_label)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/code.py b/contrib/python/ipython/py2/IPython/core/magics/code.py
index 4c1a40f197..c91d24c639 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/code.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/code.py
@@ -1,7 +1,7 @@
"""Implementation of code management magic functions.
"""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
@@ -32,9 +32,9 @@ from IPython.testing.skipdoctest import skip_doctest
from IPython.utils import py3compat
from IPython.utils.py3compat import string_types
from IPython.utils.contexts import preserve_keys
-from IPython.utils.path import get_py_filename
-from warnings import warn
-from logging import error
+from IPython.utils.path import get_py_filename
+from warnings import warn
+from logging import error
from IPython.utils.text import get_text_list
#-----------------------------------------------------------------------------
@@ -138,37 +138,37 @@ def extract_symbols(code, symbols):
return blocks, not_found
-def strip_initial_indent(lines):
- """For %load, strip indent from lines until finding an unindented line.
-
- https://github.com/ipython/ipython/issues/9775
- """
- indent_re = re.compile(r'\s+')
-
- it = iter(lines)
- first_line = next(it)
- indent_match = indent_re.match(first_line)
-
- if indent_match:
- # First line was indented
- indent = indent_match.group()
- yield first_line[len(indent):]
-
- for line in it:
- if line.startswith(indent):
- yield line[len(indent):]
- else:
- # Less indented than the first line - stop dedenting
- yield line
- break
- else:
- yield first_line
-
- # Pass the remaining lines through without dedenting
- for line in it:
- yield line
-
-
+def strip_initial_indent(lines):
+ """For %load, strip indent from lines until finding an unindented line.
+
+ https://github.com/ipython/ipython/issues/9775
+ """
+ indent_re = re.compile(r'\s+')
+
+ it = iter(lines)
+ first_line = next(it)
+ indent_match = indent_re.match(first_line)
+
+ if indent_match:
+ # First line was indented
+ indent = indent_match.group()
+ yield first_line[len(indent):]
+
+ for line in it:
+ if line.startswith(indent):
+ yield line[len(indent):]
+ else:
+ # Less indented than the first line - stop dedenting
+ yield line
+ break
+ else:
+ yield first_line
+
+ # Pass the remaining lines through without dedenting
+ for line in it:
+ yield line
+
+
class InteractivelyDefined(Exception):
"""Exception for interactively defined variable in magic_edit"""
def __init__(self, index):
@@ -219,7 +219,7 @@ class CodeMagics(Magics):
append = 'a' in opts
mode = 'a' if append else 'w'
ext = u'.ipy' if raw else u'.py'
- fname, codefrom = args[0], " ".join(args[1:])
+ fname, codefrom = args[0], " ".join(args[1:])
if not fname.endswith((u'.py',u'.ipy')):
fname += ext
file_exists = os.path.isfile(fname)
@@ -371,7 +371,7 @@ class CodeMagics(Magics):
lines = contents.split('\n')
slices = extract_code_ranges(ranges)
contents = [lines[slice(*slc)] for slc in slices]
- contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
+ contents = '\n'.join(strip_initial_indent(chain.from_iterable(contents)))
l = len(contents)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/config.py b/contrib/python/ipython/py2/IPython/core/magics/config.py
index 9505697791..184388f064 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/config.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/config.py
@@ -1,7 +1,7 @@
"""Implementation of configuration-related magic functions.
"""
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Copyright (c) 2012 The IPython Development Team.
#
@@ -20,7 +20,7 @@ import re
# Our own packages
from IPython.core.error import UsageError
from IPython.core.magic import Magics, magics_class, line_magic
-from logging import error
+from logging import error
#-----------------------------------------------------------------------------
# Magic implementation classes
diff --git a/contrib/python/ipython/py2/IPython/core/magics/display.py b/contrib/python/ipython/py2/IPython/core/magics/display.py
index c4a8f44d9a..a0a74a62cc 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/display.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/display.py
@@ -25,32 +25,32 @@ from IPython.core.magic import (
@magics_class
class DisplayMagics(Magics):
"""Magics for displaying various output types with literals
-
- Defines javascript/latex/svg/html cell magics for writing
+
+ Defines javascript/latex/svg/html cell magics for writing
blocks in those languages, to be rendered in the frontend.
"""
-
- @cell_magic
- def js(self, line, cell):
- """Run the cell block of Javascript code
-
- Alias of `%%javascript`
- """
- self.javascript(line, cell)
-
+
@cell_magic
+ def js(self, line, cell):
+ """Run the cell block of Javascript code
+
+ Alias of `%%javascript`
+ """
+ self.javascript(line, cell)
+
+ @cell_magic
def javascript(self, line, cell):
"""Run the cell block of Javascript code"""
display(Javascript(cell))
-
-
+
+
@cell_magic
def latex(self, line, cell):
"""Render the cell as a block of latex
-
+
The subset of latex which is support depends on the implementation in
- the client. In the Jupyter Notebook, this magic only renders the subset
- of latex defined by MathJax
+ the client. In the Jupyter Notebook, this magic only renders the subset
+ of latex defined by MathJax
[here](https://docs.mathjax.org/en/v2.5-latest/tex.html)."""
display(Latex(cell))
diff --git a/contrib/python/ipython/py2/IPython/core/magics/execution.py b/contrib/python/ipython/py2/IPython/core/magics/execution.py
index 3734b0cdae..2597cab3fc 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/execution.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/execution.py
@@ -5,7 +5,7 @@
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
-from __future__ import absolute_import
+from __future__ import absolute_import
import ast
import bdb
@@ -28,7 +28,7 @@ except ImportError:
except ImportError:
profile = pstats = None
-from IPython.core import oinspect
+from IPython.core import oinspect
from IPython.core import magic_arguments
from IPython.core import page
from IPython.core.error import UsageError
@@ -42,10 +42,10 @@ from IPython.utils.contexts import preserve_keys
from IPython.utils.capture import capture_output
from IPython.utils.ipstruct import Struct
from IPython.utils.module_paths import find_mod
-from IPython.utils.path import get_py_filename, shellglob
+from IPython.utils.path import get_py_filename, shellglob
from IPython.utils.timing import clock, clock2
-from warnings import warn
-from logging import error
+from warnings import warn
+from logging import error
if PY3:
from io import StringIO
@@ -61,12 +61,12 @@ class TimeitResult(object):
"""
Object returned by the timeit magic with info about the run.
- Contains the following attributes :
+ Contains the following attributes :
- loops: (int) number of loops done per measurement
- repeat: (int) number of times the measurement has been repeated
- best: (float) best execution time / number
- all_runs: (list of float) execution time of each run (in s)
+ loops: (int) number of loops done per measurement
+ repeat: (int) number of times the measurement has been repeated
+ best: (float) best execution time / number
+ all_runs: (list of float) execution time of each run (in s)
compile_time: (float) time of statement compilation (s)
"""
@@ -705,54 +705,54 @@ python-profiler package from non-free.""")
try:
stats = None
- if 'p' in opts:
- stats = self._run_with_profiler(code, opts, code_ns)
- else:
- if 'd' in opts:
- bp_file, bp_line = parse_breakpoint(
- opts.get('b', ['1'])[0], filename)
- self._run_with_debugger(
- code, code_ns, filename, bp_line, bp_file)
+ if 'p' in opts:
+ stats = self._run_with_profiler(code, opts, code_ns)
+ else:
+ if 'd' in opts:
+ bp_file, bp_line = parse_breakpoint(
+ opts.get('b', ['1'])[0], filename)
+ self._run_with_debugger(
+ code, code_ns, filename, bp_line, bp_file)
else:
- if 'm' in opts:
- def run():
- self.shell.safe_run_module(modulename, prog_ns)
+ if 'm' in opts:
+ def run():
+ self.shell.safe_run_module(modulename, prog_ns)
else:
- if runner is None:
- runner = self.default_runner
- if runner is None:
- runner = self.shell.safe_execfile
-
- def run():
- runner(filename, prog_ns, prog_ns,
- exit_ignore=exit_ignore)
-
- if 't' in opts:
- # timed execution
- try:
- nruns = int(opts['N'][0])
- if nruns < 1:
- error('Number of runs must be >=1')
- return
- except (KeyError):
- nruns = 1
- self._run_with_timing(run, nruns)
- else:
- # regular execution
- run()
-
- if 'i' in opts:
- self.shell.user_ns['__name__'] = __name__save
- else:
- # update IPython interactive namespace
-
- # Some forms of read errors on the file may mean the
- # __name__ key was never set; using pop we don't have to
- # worry about a possible KeyError.
- prog_ns.pop('__name__', None)
-
- with preserve_keys(self.shell.user_ns, '__file__'):
- self.shell.user_ns.update(prog_ns)
+ if runner is None:
+ runner = self.default_runner
+ if runner is None:
+ runner = self.shell.safe_execfile
+
+ def run():
+ runner(filename, prog_ns, prog_ns,
+ exit_ignore=exit_ignore)
+
+ if 't' in opts:
+ # timed execution
+ try:
+ nruns = int(opts['N'][0])
+ if nruns < 1:
+ error('Number of runs must be >=1')
+ return
+ except (KeyError):
+ nruns = 1
+ self._run_with_timing(run, nruns)
+ else:
+ # regular execution
+ run()
+
+ if 'i' in opts:
+ self.shell.user_ns['__name__'] = __name__save
+ else:
+ # update IPython interactive namespace
+
+ # Some forms of read errors on the file may mean the
+ # __name__ key was never set; using pop we don't have to
+ # worry about a possible KeyError.
+ prog_ns.pop('__name__', None)
+
+ with preserve_keys(self.shell.user_ns, '__file__'):
+ self.shell.user_ns.update(prog_ns)
finally:
# It's a bit of a mystery why, but __builtins__ can change from
# being a module to becoming a dict missing some key data after
@@ -801,11 +801,11 @@ python-profiler package from non-free.""")
If the break point given by `bp_line` is not valid.
"""
- deb = self.shell.InteractiveTB.pdb
- if not deb:
- self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
- deb = self.shell.InteractiveTB.pdb
-
+ deb = self.shell.InteractiveTB.pdb
+ if not deb:
+ self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
+ deb = self.shell.InteractiveTB.pdb
+
# deb.checkline() fails if deb.curframe exists but is None; it can
# handle it not existing. https://github.com/ipython/ipython/issues/10028
if hasattr(deb, 'curframe'):
diff --git a/contrib/python/ipython/py2/IPython/core/magics/history.py b/contrib/python/ipython/py2/IPython/core/magics/history.py
index 5967591394..d24bfd2a4e 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/history.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/history.py
@@ -15,7 +15,7 @@ from __future__ import print_function
# Stdlib
import os
-import sys
+import sys
from io import open as io_open
# Our own packages
@@ -148,7 +148,7 @@ class HistoryMagics(Magics):
# Check if output to specific file was requested.
outfname = args.filename
if not outfname:
- outfile = sys.stdout # default
+ outfile = sys.stdout # default
# We don't want to close stdout at the end!
close_at_end = False
else:
diff --git a/contrib/python/ipython/py2/IPython/core/magics/logging.py b/contrib/python/ipython/py2/IPython/core/magics/logging.py
index 90214ab54a..22500f8156 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/logging.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/logging.py
@@ -18,7 +18,7 @@ import sys
# Our own packages
from IPython.core.magic import Magics, magics_class, line_magic
-from warnings import warn
+from warnings import warn
from IPython.utils.py3compat import str_to_unicode
#-----------------------------------------------------------------------------
diff --git a/contrib/python/ipython/py2/IPython/core/magics/osm.py b/contrib/python/ipython/py2/IPython/core/magics/osm.py
index 352cf2d451..f48259ee02 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/osm.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/osm.py
@@ -323,7 +323,7 @@ class OSMagics(Magics):
else:
- opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
+ opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
# jump to previous
if ps == '-':
try:
@@ -437,7 +437,7 @@ class OSMagics(Magics):
"""
dir_s = self.shell.dir_stack
- tgt = os.path.expanduser(parameter_s)
+ tgt = os.path.expanduser(parameter_s)
cwd = py3compat.getcwd().replace(self.shell.home_dir,'~')
if tgt:
self.cd(parameter_s)
@@ -775,8 +775,8 @@ class OSMagics(Magics):
The file will be overwritten unless the -a (--append) flag is specified.
"""
args = magic_arguments.parse_argstring(self.writefile, line)
- filename = os.path.expanduser(args.filename)
-
+ filename = os.path.expanduser(args.filename)
+
if os.path.exists(filename):
if args.append:
print("Appending to %s" % filename)
diff --git a/contrib/python/ipython/py2/IPython/core/magics/pylab.py b/contrib/python/ipython/py2/IPython/core/magics/pylab.py
index 6c5cd68a59..62308d5e49 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/pylab.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/pylab.py
@@ -18,7 +18,7 @@ from traitlets.config.application import Application
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
from IPython.testing.skipdoctest import skip_doctest
-from warnings import warn
+from warnings import warn
from IPython.core.pylabtools import backends
#-----------------------------------------------------------------------------
diff --git a/contrib/python/ipython/py2/IPython/core/magics/script.py b/contrib/python/ipython/py2/IPython/core/magics/script.py
index 3fbddc38a8..bfcad64919 100644
--- a/contrib/python/ipython/py2/IPython/core/magics/script.py
+++ b/contrib/python/ipython/py2/IPython/core/magics/script.py
@@ -1,8 +1,8 @@
"""Magic functions for running cells in various scripts."""
from __future__ import print_function
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import errno
import os
@@ -19,7 +19,7 @@ from IPython.core.magic import (
from IPython.lib.backgroundjobs import BackgroundJobManager
from IPython.utils import py3compat
from IPython.utils.process import arg_split
-from traitlets import List, Dict, default
+from traitlets import List, Dict, default
#-----------------------------------------------------------------------------
# Magic implementation classes
@@ -68,7 +68,7 @@ class ScriptMagics(Magics):
with a program in a subprocess, and registers a few top-level
magics that call %%script with common interpreters.
"""
- script_magics = List(
+ script_magics = List(
help="""Extra script cell magics to define
This generates simple wrappers of `%%script foo` as `%%foo`.
@@ -76,8 +76,8 @@ class ScriptMagics(Magics):
If you want to add script magics that aren't on your path,
specify them in script_paths
""",
- ).tag(config=True)
- @default('script_magics')
+ ).tag(config=True)
+ @default('script_magics')
def _script_magics_default(self):
"""default to a common list of programs"""
@@ -98,13 +98,13 @@ class ScriptMagics(Magics):
return defaults
- script_paths = Dict(
+ script_paths = Dict(
help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
Only necessary for items in script_magics where the default path will not
find the right interpreter.
"""
- ).tag(config=True)
+ ).tag(config=True)
def __init__(self, shell=None):
super(ScriptMagics, self).__init__(shell=shell)
diff --git a/contrib/python/ipython/py2/IPython/core/oinspect.py b/contrib/python/ipython/py2/IPython/core/oinspect.py
index 55a4efe8c0..b11e24e435 100644
--- a/contrib/python/ipython/py2/IPython/core/oinspect.py
+++ b/contrib/python/ipython/py2/IPython/core/oinspect.py
@@ -17,7 +17,7 @@ __all__ = ['Inspector','InspectColors']
# stdlib modules
import inspect
import linecache
-import warnings
+import warnings
import os
from textwrap import dedent
import types
@@ -42,19 +42,19 @@ from IPython.utils.wildcard import list_namespace
from IPython.utils.coloransi import TermColors, ColorScheme, ColorSchemeTable
from IPython.utils.py3compat import cast_unicode, string_types, PY3
from IPython.utils.signatures import signature
-from IPython.utils.colorable import Colorable
+from IPython.utils.colorable import Colorable
-from pygments import highlight
+from pygments import highlight
try:
# PythonLexer was renamed to Python2Lexer in pygments 2.5
from pygments.lexers import Python2Lexer
except ImportError:
from pygments.lexers import PythonLexer as Python2Lexer
-from pygments.formatters import HtmlFormatter
-
-def pylight(code):
+from pygments.formatters import HtmlFormatter
+
+def pylight(code):
return highlight(code, Python2Lexer(), HtmlFormatter(noclasses=True))
-
+
# builtin docstrings to ignore
_func_call_docstring = types.FunctionType.__call__.__doc__
_object_init_docstring = object.__init__.__doc__
@@ -124,8 +124,8 @@ def getdoc(obj):
It also attempts to call a getdoc() method on the given object. This
allows objects which provide their docstrings via non-standard mechanisms
- (like Pyro proxies) to still be inspected by ipython's ? system.
- """
+ (like Pyro proxies) to still be inspected by ipython's ? system.
+ """
# Allow objects to offer customized documentation via a getdoc method:
try:
ds = obj.getdoc()
@@ -141,7 +141,7 @@ def getdoc(obj):
return py3compat.cast_unicode(docstr, encoding=encoding)
except Exception:
# Harden against an inspect failure, which can occur with
- # extensions modules.
+ # extensions modules.
raise
return None
@@ -376,16 +376,16 @@ def find_source_lines(obj):
return lineno
-class Inspector(Colorable):
+class Inspector(Colorable):
def __init__(self, color_table=InspectColors,
code_color_table=PyColorize.ANSICodeColors,
scheme='NoColor',
- str_detail_level=0,
- parent=None, config=None):
- super(Inspector, self).__init__(parent=parent, config=config)
+ str_detail_level=0,
+ parent=None, config=None):
+ super(Inspector, self).__init__(parent=parent, config=config)
self.color_table = color_table
- self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
+ self.parser = PyColorize.Parser(out='str', parent=self, style=scheme)
self.format = self.parser.format
self.str_detail_level = str_detail_level
self.set_active_scheme(scheme)
@@ -438,11 +438,11 @@ class Inspector(Colorable):
if output is None:
self.noinfo('definition header',oname)
else:
- print(header,self.format(output), end=' ')
+ print(header,self.format(output), end=' ')
# In Python 3, all classes are new-style, so they all have __init__.
@skip_doctest_py3
- def pdoc(self, obj, oname='', formatter=None):
+ def pdoc(self, obj, oname='', formatter=None):
"""Print the docstring for any object.
Optional:
@@ -480,7 +480,7 @@ class Inspector(Colorable):
lines = []
ds = getdoc(obj)
if formatter:
- ds = formatter(ds).get('plain/text', ds)
+ ds = formatter(ds).get('plain/text', ds)
if ds:
lines.append(head("Class docstring:"))
lines.append(indent(ds))
@@ -517,7 +517,7 @@ class Inspector(Colorable):
def pfile(self, obj, oname=''):
"""Show the whole file where an object was defined."""
-
+
lineno = find_source_lines(obj)
if lineno is None:
self.noinfo('file', oname)
@@ -553,184 +553,184 @@ class Inspector(Colorable):
title_width = max(len(title) + 2 for title, _ in fields)
for title, content in fields:
if len(content.splitlines()) > 1:
- title = header(title + ':') + '\n'
+ title = header(title + ':') + '\n'
else:
- title = header((title + ':').ljust(title_width))
+ title = header((title + ':').ljust(title_width))
out.append(cast_unicode(title) + cast_unicode(content))
return "\n".join(out)
- def _mime_format(self, text, formatter=None):
- """Return a mime bundle representation of the input text.
-
- - if `formatter` is None, the returned mime bundle has
- a `text/plain` field, with the input text.
- a `text/html` field with a `<pre>` tag containing the input text.
-
- - if `formatter` is not None, it must be a callable transforming the
- input text into a mime bundle. Default values for `text/plain` and
- `text/html` representations are the ones described above.
-
- Note:
-
- Formatters returning strings are supported but this behavior is deprecated.
-
- """
- text = cast_unicode(text)
- defaults = {
- 'text/plain': text,
- 'text/html': '<pre>' + text + '</pre>'
- }
-
- if formatter is None:
- return defaults
- else:
- formatted = formatter(text)
-
- if not isinstance(formatted, dict):
- # Handle the deprecated behavior of a formatter returning
- # a string instead of a mime bundle.
- return {
- 'text/plain': formatted,
- 'text/html': '<pre>' + formatted + '</pre>'
- }
-
- else:
- return dict(defaults, **formatted)
-
-
- def format_mime(self, bundle):
-
- text_plain = bundle['text/plain']
-
- text = ''
- heads, bodies = list(zip(*text_plain))
- _len = max(len(h) for h in heads)
-
- for head, body in zip(heads, bodies):
- body = body.strip('\n')
- delim = '\n' if '\n' in body else ' '
- text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
-
- bundle['text/plain'] = text
- return bundle
-
- def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
- """Retrieve an info dict and format it."""
-
- info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
-
- _mime = {
- 'text/plain': [],
- 'text/html': '',
- }
-
- def append_field(bundle, title, key, formatter=None):
- field = info[key]
- if field is not None:
- formatted_field = self._mime_format(field, formatter)
- bundle['text/plain'].append((title, formatted_field['text/plain']))
- bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
-
- def code_formatter(text):
- return {
- 'text/plain': self.format(text),
- 'text/html': pylight(text)
- }
-
+ def _mime_format(self, text, formatter=None):
+ """Return a mime bundle representation of the input text.
+
+ - if `formatter` is None, the returned mime bundle has
+ a `text/plain` field, with the input text.
+ a `text/html` field with a `<pre>` tag containing the input text.
+
+ - if `formatter` is not None, it must be a callable transforming the
+ input text into a mime bundle. Default values for `text/plain` and
+ `text/html` representations are the ones described above.
+
+ Note:
+
+ Formatters returning strings are supported but this behavior is deprecated.
+
+ """
+ text = cast_unicode(text)
+ defaults = {
+ 'text/plain': text,
+ 'text/html': '<pre>' + text + '</pre>'
+ }
+
+ if formatter is None:
+ return defaults
+ else:
+ formatted = formatter(text)
+
+ if not isinstance(formatted, dict):
+ # Handle the deprecated behavior of a formatter returning
+ # a string instead of a mime bundle.
+ return {
+ 'text/plain': formatted,
+ 'text/html': '<pre>' + formatted + '</pre>'
+ }
+
+ else:
+ return dict(defaults, **formatted)
+
+
+ def format_mime(self, bundle):
+
+ text_plain = bundle['text/plain']
+
+ text = ''
+ heads, bodies = list(zip(*text_plain))
+ _len = max(len(h) for h in heads)
+
+ for head, body in zip(heads, bodies):
+ body = body.strip('\n')
+ delim = '\n' if '\n' in body else ' '
+ text += self.__head(head+':') + (_len - len(head))*' ' +delim + body +'\n'
+
+ bundle['text/plain'] = text
+ return bundle
+
+ def _get_info(self, obj, oname='', formatter=None, info=None, detail_level=0):
+ """Retrieve an info dict and format it."""
+
+ info = self._info(obj, oname=oname, info=info, detail_level=detail_level)
+
+ _mime = {
+ 'text/plain': [],
+ 'text/html': '',
+ }
+
+ def append_field(bundle, title, key, formatter=None):
+ field = info[key]
+ if field is not None:
+ formatted_field = self._mime_format(field, formatter)
+ bundle['text/plain'].append((title, formatted_field['text/plain']))
+ bundle['text/html'] += '<h1>' + title + '</h1>\n' + formatted_field['text/html'] + '\n'
+
+ def code_formatter(text):
+ return {
+ 'text/plain': self.format(text),
+ 'text/html': pylight(text)
+ }
+
if info['isalias']:
- append_field(_mime, 'Repr', 'string_form')
+ append_field(_mime, 'Repr', 'string_form')
elif info['ismagic']:
- if detail_level > 0:
- append_field(_mime, 'Source', 'source', code_formatter)
+ if detail_level > 0:
+ append_field(_mime, 'Source', 'source', code_formatter)
else:
- append_field(_mime, 'Docstring', 'docstring', formatter)
- append_field(_mime, 'File', 'file')
+ append_field(_mime, 'Docstring', 'docstring', formatter)
+ append_field(_mime, 'File', 'file')
elif info['isclass'] or is_simple_callable(obj):
# Functions, methods, classes
- append_field(_mime, 'Signature', 'definition', code_formatter)
- append_field(_mime, 'Init signature', 'init_definition', code_formatter)
+ append_field(_mime, 'Signature', 'definition', code_formatter)
+ append_field(_mime, 'Init signature', 'init_definition', code_formatter)
if detail_level > 0 and info['source']:
- append_field(_mime, 'Source', 'source', code_formatter)
+ append_field(_mime, 'Source', 'source', code_formatter)
else:
- append_field(_mime, 'Docstring', 'docstring', formatter)
- append_field(_mime, 'Init docstring', 'init_docstring', formatter)
+ append_field(_mime, 'Docstring', 'docstring', formatter)
+ append_field(_mime, 'Init docstring', 'init_docstring', formatter)
- append_field(_mime, 'File', 'file')
- append_field(_mime, 'Type', 'type_name')
+ append_field(_mime, 'File', 'file')
+ append_field(_mime, 'Type', 'type_name')
else:
# General Python objects
append_field(_mime, 'Signature', 'definition', code_formatter)
append_field(_mime, 'Call signature', 'call_def', code_formatter)
- append_field(_mime, 'Type', 'type_name')
+ append_field(_mime, 'Type', 'type_name')
# Base class for old-style instances
if (not py3compat.PY3) and isinstance(obj, types.InstanceType) and info['base_class']:
- append_field(_mime, 'Base Class', 'base_class')
+ append_field(_mime, 'Base Class', 'base_class')
- append_field(_mime, 'String form', 'string_form')
+ append_field(_mime, 'String form', 'string_form')
# Namespace
if info['namespace'] != 'Interactive':
- append_field(_mime, 'Namespace', 'namespace')
+ append_field(_mime, 'Namespace', 'namespace')
- append_field(_mime, 'Length', 'length')
+ append_field(_mime, 'Length', 'length')
append_field(_mime, 'File', 'file')
# Source or docstring, depending on detail level and whether
# source found.
- if detail_level > 0:
- append_field(_mime, 'Source', 'source', code_formatter)
- else:
- append_field(_mime, 'Docstring', 'docstring', formatter)
-
- append_field(_mime, 'Class docstring', 'class_docstring', formatter)
- append_field(_mime, 'Init docstring', 'init_docstring', formatter)
- append_field(_mime, 'Call docstring', 'call_docstring', formatter)
+ if detail_level > 0:
+ append_field(_mime, 'Source', 'source', code_formatter)
+ else:
+ append_field(_mime, 'Docstring', 'docstring', formatter)
+
+ append_field(_mime, 'Class docstring', 'class_docstring', formatter)
+ append_field(_mime, 'Init docstring', 'init_docstring', formatter)
+ append_field(_mime, 'Call docstring', 'call_docstring', formatter)
-
- return self.format_mime(_mime)
-
- def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
+
+ return self.format_mime(_mime)
+
+ def pinfo(self, obj, oname='', formatter=None, info=None, detail_level=0, enable_html_pager=True):
"""Show detailed information about an object.
Optional arguments:
- oname: name of the variable pointing to the object.
- - formatter: callable (optional)
- A special formatter for docstrings.
-
- The formatter is a callable that takes a string as an input
- and returns either a formatted string or a mime type bundle
- in the form of a dictionnary.
-
- Although the support of custom formatter returning a string
- instead of a mime type bundle is deprecated.
+ - formatter: callable (optional)
+ A special formatter for docstrings.
+ The formatter is a callable that takes a string as an input
+ and returns either a formatted string or a mime type bundle
+ in the form of a dictionnary.
+
+ Although the support of custom formatter returning a string
+ instead of a mime type bundle is deprecated.
+
- info: a structure with some information fields which may have been
precomputed already.
- detail_level: if set to 1, more information is given.
"""
- info = self._get_info(obj, oname, formatter, info, detail_level)
- if not enable_html_pager:
- del info['text/html']
- page.page(info)
-
+ info = self._get_info(obj, oname, formatter, info, detail_level)
+ if not enable_html_pager:
+ del info['text/html']
+ page.page(info)
+
def info(self, obj, oname='', formatter=None, info=None, detail_level=0):
- """DEPRECATED. Compute a dict with detailed information about an object.
- """
- if formatter is not None:
- warnings.warn('The `formatter` keyword argument to `Inspector.info`'
- 'is deprecated as of IPython 5.0 and will have no effects.',
- DeprecationWarning, stacklevel=2)
- return self._info(obj, oname=oname, info=info, detail_level=detail_level)
-
- def _info(self, obj, oname='', info=None, detail_level=0):
+ """DEPRECATED. Compute a dict with detailed information about an object.
+ """
+ if formatter is not None:
+ warnings.warn('The `formatter` keyword argument to `Inspector.info`'
+ 'is deprecated as of IPython 5.0 and will have no effects.',
+ DeprecationWarning, stacklevel=2)
+ return self._info(obj, oname=oname, info=info, detail_level=detail_level)
+
+ def _info(self, obj, oname='', info=None, detail_level=0):
"""Compute a dict with detailed information about an object.
Optional arguments:
@@ -774,7 +774,7 @@ class Inspector(Colorable):
out = dict(name=oname, found=True, isalias=isalias, ismagic=ismagic)
string_max = 200 # max size of strings to show (snipped if longer)
- shalf = int((string_max - 5) / 2)
+ shalf = int((string_max - 5) / 2)
if ismagic:
obj_type_name = 'Magic function'
@@ -846,43 +846,43 @@ class Inspector(Colorable):
# Constructor docstring for classes
if inspect.isclass(obj):
out['isclass'] = True
-
- # get the init signature:
+
+ # get the init signature:
try:
- init_def = self._getdef(obj, oname)
+ init_def = self._getdef(obj, oname)
except AttributeError:
- init_def = None
-
- # get the __init__ docstring
- try:
- obj_init = obj.__init__
- except AttributeError:
- init_ds = None
+ init_def = None
+
+ # get the __init__ docstring
+ try:
+ obj_init = obj.__init__
+ except AttributeError:
+ init_ds = None
else:
- if init_def is None:
- # Get signature from init if top-level sig failed.
- # Can happen for built-in types (list, etc.).
- try:
- init_def = self._getdef(obj_init, oname)
- except AttributeError:
- pass
- init_ds = getdoc(obj_init)
+ if init_def is None:
+ # Get signature from init if top-level sig failed.
+ # Can happen for built-in types (list, etc.).
+ try:
+ init_def = self._getdef(obj_init, oname)
+ except AttributeError:
+ pass
+ init_ds = getdoc(obj_init)
# Skip Python's auto-generated docstrings
if init_ds == _object_init_docstring:
init_ds = None
- if init_def:
- out['init_definition'] = init_def
-
- if init_ds:
- out['init_docstring'] = init_ds
+ if init_def:
+ out['init_definition'] = init_def
+ if init_ds:
+ out['init_docstring'] = init_ds
+
# and class docstring for instances:
else:
# reconstruct the function definition and print it:
defln = self._getdef(obj, oname)
if defln:
- out['definition'] = defln
+ out['definition'] = defln
# First, check whether the instance docstring is identical to the
# class one, and print it separately if they don't coincide. In
@@ -915,10 +915,10 @@ class Inspector(Colorable):
# Call form docstring for callable instances
if safe_hasattr(obj, '__call__') and not is_simple_callable(obj):
call_def = self._getdef(obj.__call__, oname)
- if call_def and (call_def != out.get('definition')):
+ if call_def and (call_def != out.get('definition')):
# it may never be the case that call def and definition differ,
# but don't include the same signature twice
- out['call_def'] = call_def
+ out['call_def'] = call_def
call_ds = getdoc(obj.__call__)
# Skip Python's auto-generated docstrings
if call_ds == _func_call_docstring:
diff --git a/contrib/python/ipython/py2/IPython/core/page.py b/contrib/python/ipython/py2/IPython/core/page.py
index 6d213c9f29..a9de4f4805 100644
--- a/contrib/python/ipython/py2/IPython/core/page.py
+++ b/contrib/python/ipython/py2/IPython/core/page.py
@@ -38,7 +38,7 @@ def display_page(strng, start=0, screen_lines=25):
else:
if start:
strng = u'\n'.join(strng.splitlines()[start:])
- data = { 'text/plain': strng }
+ data = { 'text/plain': strng }
display(data, raw=True)
@@ -56,25 +56,25 @@ def page_dumb(strng, start=0, screen_lines=25):
"""Very dumb 'pager' in Python, for when nothing else works.
Only moves forward, same interface as page(), except for pager_cmd and
- mode.
- """
- if isinstance(strng, dict):
- strng = strng.get('text/plain', '')
+ mode.
+ """
+ if isinstance(strng, dict):
+ strng = strng.get('text/plain', '')
out_ln = strng.splitlines()[start:]
screens = chop(out_ln,screen_lines-1)
if len(screens) == 1:
- print(os.linesep.join(screens[0]))
+ print(os.linesep.join(screens[0]))
else:
last_escape = ""
for scr in screens[0:-1]:
hunk = os.linesep.join(scr)
- print(last_escape + hunk)
+ print(last_escape + hunk)
if not page_more():
return
esc_list = esc_re.findall(hunk)
if len(esc_list) > 0:
last_escape = esc_list[-1]
- print(last_escape + os.linesep.join(screens[-1]))
+ print(last_escape + os.linesep.join(screens[-1]))
def _detect_screen_size(screen_lines_def):
"""Attempt to work out the number of lines on the screen.
@@ -192,13 +192,13 @@ def pager_page(strng, start=0, screen_lines=0, pager_cmd=None):
try:
screen_lines += _detect_screen_size(screen_lines_def)
except (TypeError, UnsupportedOperation):
- print(str_toprint)
+ print(str_toprint)
return
#print 'numlines',numlines,'screenlines',screen_lines # dbg
if numlines <= screen_lines :
#print '*** normal print' # dbg
- print(str_toprint)
+ print(str_toprint)
else:
# Try to open pager and default to internal one if that fails.
# All failure modes are tagged as 'retval=1', to match the return
@@ -300,7 +300,7 @@ def get_pager_cmd(pager_cmd=None):
Makes some attempts at finding an OS-correct one.
"""
if os.name == 'posix':
- default_pager_cmd = 'less -R' # -R for color control sequences
+ default_pager_cmd = 'less -R' # -R for color control sequences
elif os.name in ['nt','dos']:
default_pager_cmd = 'type'
@@ -309,10 +309,10 @@ def get_pager_cmd(pager_cmd=None):
pager_cmd = os.environ['PAGER']
except:
pager_cmd = default_pager_cmd
-
- if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
- pager_cmd += ' -R'
-
+
+ if pager_cmd == 'less' and '-r' not in os.environ.get('LESS', '').lower():
+ pager_cmd += ' -R'
+
return pager_cmd
@@ -340,13 +340,13 @@ if os.name == 'nt' and os.environ.get('TERM','dumb') != 'emacs':
@return: True if need print more lines, False if quit
"""
- sys.stdout.write('---Return to continue, q to quit--- ')
+ sys.stdout.write('---Return to continue, q to quit--- ')
ans = msvcrt.getwch()
if ans in ("q", "Q"):
result = False
else:
result = True
- sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
+ sys.stdout.write("\b"*37 + " "*37 + "\b"*37)
return result
else:
def page_more():
diff --git a/contrib/python/ipython/py2/IPython/core/prefilter.py b/contrib/python/ipython/py2/IPython/core/prefilter.py
index cbed3fd80a..1f2367fe52 100644
--- a/contrib/python/ipython/py2/IPython/core/prefilter.py
+++ b/contrib/python/ipython/py2/IPython/core/prefilter.py
@@ -6,8 +6,8 @@ Prefilters transform user input before it is exec'd by Python. These
transforms are used to implement additional syntax such as !ls and %magic.
"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
from keyword import iskeyword
import re
@@ -24,7 +24,7 @@ from IPython.core.macro import Macro
from IPython.core.splitinput import LineInfo
from traitlets import (
- List, Integer, Unicode, Bool, Instance, CRegExp
+ List, Integer, Unicode, Bool, Instance, CRegExp
)
#-----------------------------------------------------------------------------
@@ -114,7 +114,7 @@ class PrefilterManager(Configurable):
or :meth:`sort_transformers` method after changing the priority.
"""
- multi_line_specials = Bool(True).tag(config=True)
+ multi_line_specials = Bool(True).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
def __init__(self, shell=None, **kwargs):
@@ -344,12 +344,12 @@ class PrefilterManager(Configurable):
class PrefilterTransformer(Configurable):
"""Transform a line of user input."""
- priority = Integer(100).tag(config=True)
+ priority = Integer(100).tag(config=True)
# Transformers don't currently use shell or prefilter_manager, but as we
# move away from checkers and handlers, they will need them.
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
- enabled = Bool(True).tag(config=True)
+ enabled = Bool(True).tag(config=True)
def __init__(self, shell=None, prefilter_manager=None, **kwargs):
super(PrefilterTransformer, self).__init__(
@@ -374,10 +374,10 @@ class PrefilterTransformer(Configurable):
class PrefilterChecker(Configurable):
"""Inspect an input line and return a handler for that line."""
- priority = Integer(100).tag(config=True)
+ priority = Integer(100).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
- enabled = Bool(True).tag(config=True)
+ enabled = Bool(True).tag(config=True)
def __init__(self, shell=None, prefilter_manager=None, **kwargs):
super(PrefilterChecker, self).__init__(
@@ -396,8 +396,8 @@ class PrefilterChecker(Configurable):
class EmacsChecker(PrefilterChecker):
- priority = Integer(100).tag(config=True)
- enabled = Bool(False).tag(config=True)
+ priority = Integer(100).tag(config=True)
+ enabled = Bool(False).tag(config=True)
def check(self, line_info):
"Emacs ipython-mode tags certain input lines."
@@ -409,7 +409,7 @@ class EmacsChecker(PrefilterChecker):
class MacroChecker(PrefilterChecker):
- priority = Integer(250).tag(config=True)
+ priority = Integer(250).tag(config=True)
def check(self, line_info):
obj = self.shell.user_ns.get(line_info.ifun)
@@ -421,7 +421,7 @@ class MacroChecker(PrefilterChecker):
class IPyAutocallChecker(PrefilterChecker):
- priority = Integer(300).tag(config=True)
+ priority = Integer(300).tag(config=True)
def check(self, line_info):
"Instances of IPyAutocall in user_ns get autocalled immediately"
@@ -435,7 +435,7 @@ class IPyAutocallChecker(PrefilterChecker):
class AssignmentChecker(PrefilterChecker):
- priority = Integer(600).tag(config=True)
+ priority = Integer(600).tag(config=True)
def check(self, line_info):
"""Check to see if user is assigning to a var for the first time, in
@@ -453,7 +453,7 @@ class AssignmentChecker(PrefilterChecker):
class AutoMagicChecker(PrefilterChecker):
- priority = Integer(700).tag(config=True)
+ priority = Integer(700).tag(config=True)
def check(self, line_info):
"""If the ifun is magic, and automagic is on, run it. Note: normal,
@@ -477,7 +477,7 @@ class AutoMagicChecker(PrefilterChecker):
class PythonOpsChecker(PrefilterChecker):
- priority = Integer(900).tag(config=True)
+ priority = Integer(900).tag(config=True)
def check(self, line_info):
"""If the 'rest' of the line begins with a function call or pretty much
@@ -492,14 +492,14 @@ class PythonOpsChecker(PrefilterChecker):
class AutocallChecker(PrefilterChecker):
- priority = Integer(1000).tag(config=True)
+ priority = Integer(1000).tag(config=True)
- function_name_regexp = CRegExp(re_fun_name,
- help="RegExp to identify potential function names."
- ).tag(config=True)
- exclude_regexp = CRegExp(re_exclude_auto,
- help="RegExp to exclude strings with this start from autocalling."
- ).tag(config=True)
+ function_name_regexp = CRegExp(re_fun_name,
+ help="RegExp to identify potential function names."
+ ).tag(config=True)
+ exclude_regexp = CRegExp(re_exclude_auto,
+ help="RegExp to exclude strings with this start from autocalling."
+ ).tag(config=True)
def check(self, line_info):
"Check if the initial word/function is callable and autocall is on."
diff --git a/contrib/python/ipython/py2/IPython/core/profileapp.py b/contrib/python/ipython/py2/IPython/core/profileapp.py
index b8e5fd26ac..3f9ce97b8b 100644
--- a/contrib/python/ipython/py2/IPython/core/profileapp.py
+++ b/contrib/python/ipython/py2/IPython/core/profileapp.py
@@ -32,7 +32,7 @@ from IPython.core.profiledir import ProfileDir
from IPython.utils.importstring import import_item
from IPython.paths import get_ipython_dir, get_ipython_package_dir
from IPython.utils import py3compat
-from traitlets import Unicode, Bool, Dict, observe
+from traitlets import Unicode, Bool, Dict, observe
#-----------------------------------------------------------------------------
# Constants
@@ -149,14 +149,14 @@ class ProfileList(Application):
)
))
- ipython_dir = Unicode(get_ipython_dir(),
+ ipython_dir = Unicode(get_ipython_dir(),
help="""
The name of the IPython directory. This directory is used for logging
configuration (through profiles), history storage, etc. The default
is usually $HOME/.ipython. This options can also be specified through
the environment variable IPYTHONDIR.
"""
- ).tag(config=True)
+ ).tag(config=True)
def _print_profiles(self, profiles):
@@ -211,24 +211,24 @@ class ProfileCreate(BaseIPythonApplication):
name = u'ipython-profile'
description = create_help
examples = _create_examples
- auto_create = Bool(True)
+ auto_create = Bool(True)
def _log_format_default(self):
return "[%(name)s] %(message)s"
def _copy_config_files_default(self):
return True
- parallel = Bool(False,
- help="whether to include parallel computing config files"
- ).tag(config=True)
-
- @observe('parallel')
- def _parallel_changed(self, change):
+ parallel = Bool(False,
+ help="whether to include parallel computing config files"
+ ).tag(config=True)
+
+ @observe('parallel')
+ def _parallel_changed(self, change):
parallel_files = [ 'ipcontroller_config.py',
'ipengine_config.py',
'ipcluster_config.py'
]
- if change['new']:
+ if change['new']:
for cf in parallel_files:
self.config_files.append(cf)
else:
diff --git a/contrib/python/ipython/py2/IPython/core/profiledir.py b/contrib/python/ipython/py2/IPython/core/profiledir.py
index b777f13da0..e0e754a78f 100644
--- a/contrib/python/ipython/py2/IPython/core/profiledir.py
+++ b/contrib/python/ipython/py2/IPython/core/profiledir.py
@@ -12,7 +12,7 @@ from traitlets.config.configurable import LoggingConfigurable
from IPython.paths import get_ipython_package_dir
from IPython.utils.path import expand_path, ensure_dir_exists
from IPython.utils import py3compat
-from traitlets import Unicode, Bool, observe
+from traitlets import Unicode, Bool, observe
#-----------------------------------------------------------------------------
# Module errors
@@ -47,18 +47,18 @@ class ProfileDir(LoggingConfigurable):
pid_dir = Unicode(u'')
static_dir = Unicode(u'')
- location = Unicode(u'',
+ location = Unicode(u'',
help="""Set the profile location directly. This overrides the logic used by the
`profile` option.""",
- ).tag(config=True)
+ ).tag(config=True)
_location_isset = Bool(False) # flag for detecting multiply set location
- @observe('location')
- def _location_changed(self, change):
+ @observe('location')
+ def _location_changed(self, change):
if self._location_isset:
raise RuntimeError("Cannot set profile location more than once.")
self._location_isset = True
- new = change['new']
+ new = change['new']
ensure_dir_exists(new)
# ensure config files exist:
@@ -68,7 +68,7 @@ class ProfileDir(LoggingConfigurable):
self.pid_dir = os.path.join(new, self.pid_dir_name)
self.static_dir = os.path.join(new, self.static_dir_name)
self.check_dirs()
-
+
def _mkdir(self, path, mode=None):
"""ensure a directory exists at a given path
@@ -102,13 +102,13 @@ class ProfileDir(LoggingConfigurable):
raise
return True
-
- @observe('log_dir')
- def check_log_dir(self, change=None):
+
+ @observe('log_dir')
+ def check_log_dir(self, change=None):
self._mkdir(self.log_dir)
-
- @observe('startup_dir')
- def check_startup_dir(self, change=None):
+
+ @observe('startup_dir')
+ def check_startup_dir(self, change=None):
self._mkdir(self.startup_dir)
readme = os.path.join(self.startup_dir, 'README')
@@ -118,12 +118,12 @@ class ProfileDir(LoggingConfigurable):
with open(readme, 'wb') as f:
f.write(pkgutil.get_data(__name__, 'profile/README_STARTUP'))
- @observe('security_dir')
- def check_security_dir(self, change=None):
+ @observe('security_dir')
+ def check_security_dir(self, change=None):
self._mkdir(self.security_dir, 0o40700)
- @observe('pid_dir')
- def check_pid_dir(self, change=None):
+ @observe('pid_dir')
+ def check_pid_dir(self, change=None):
self._mkdir(self.pid_dir, 0o40700)
def check_dirs(self):
diff --git a/contrib/python/ipython/py2/IPython/core/prompts.py b/contrib/python/ipython/py2/IPython/core/prompts.py
index 7802bc5363..cc6bcb721f 100644
--- a/contrib/python/ipython/py2/IPython/core/prompts.py
+++ b/contrib/python/ipython/py2/IPython/core/prompts.py
@@ -1,8 +1,8 @@
# -*- coding: utf-8 -*-
-"""Being removed
+"""Being removed
"""
-from IPython.utils import py3compat
+from IPython.utils import py3compat
class LazyEvaluate(object):
"""This is used for formatting strings with values that need to be updated
diff --git a/contrib/python/ipython/py2/IPython/core/pylabtools.py b/contrib/python/ipython/py2/IPython/core/pylabtools.py
index a1932d8c48..ace18b57e8 100644
--- a/contrib/python/ipython/py2/IPython/core/pylabtools.py
+++ b/contrib/python/ipython/py2/IPython/core/pylabtools.py
@@ -377,7 +377,7 @@ def configure_inline_support(shell, backend):
from ipykernel.pylab.backend_inline import InlineBackend
except ImportError:
return
- import matplotlib
+ import matplotlib
cfg = InlineBackend.instance(parent=shell)
cfg.shell = shell
@@ -391,9 +391,9 @@ def configure_inline_support(shell, backend):
# Save rcParams that will be overwrittern
shell._saved_rcParams = dict()
for k in cfg.rc:
- shell._saved_rcParams[k] = matplotlib.rcParams[k]
+ shell._saved_rcParams[k] = matplotlib.rcParams[k]
# load inline_rc
- matplotlib.rcParams.update(cfg.rc)
+ matplotlib.rcParams.update(cfg.rc)
new_backend_name = "inline"
else:
from ipykernel.pylab.backend_inline import flush_figures
@@ -402,7 +402,7 @@ def configure_inline_support(shell, backend):
except ValueError:
pass
if hasattr(shell, '_saved_rcParams'):
- matplotlib.rcParams.update(shell._saved_rcParams)
+ matplotlib.rcParams.update(shell._saved_rcParams)
del shell._saved_rcParams
new_backend_name = "other"
diff --git a/contrib/python/ipython/py2/IPython/core/release.py b/contrib/python/ipython/py2/IPython/core/release.py
index 94dea1073b..127e59629f 100644
--- a/contrib/python/ipython/py2/IPython/core/release.py
+++ b/contrib/python/ipython/py2/IPython/core/release.py
@@ -19,11 +19,11 @@ name = 'ipython'
# IPython version information. An empty _version_extra corresponds to a full
# release. 'dev' as a _version_extra string means this is a development
# version
-_version_major = 5
+_version_major = 5
_version_minor = 9
-_version_patch = 0
+_version_patch = 0
_version_extra = '.dev'
-# _version_extra = 'rc1'
+# _version_extra = 'rc1'
_version_extra = '' # Uncomment this for full releases
# release.codename is deprecated in 2.0, will be removed in 3.0
diff --git a/contrib/python/ipython/py2/IPython/core/shellapp.py b/contrib/python/ipython/py2/IPython/core/shellapp.py
index 213648246e..0684b41880 100644
--- a/contrib/python/ipython/py2/IPython/core/shellapp.py
+++ b/contrib/python/ipython/py2/IPython/core/shellapp.py
@@ -24,15 +24,15 @@ from IPython.utils import py3compat
from IPython.utils.contexts import preserve_keys
from IPython.utils.path import filefind
from traitlets import (
- Unicode, Instance, List, Bool, CaselessStrEnum, observe,
+ Unicode, Instance, List, Bool, CaselessStrEnum, observe,
)
-from IPython.terminal import pt_inputhooks
+from IPython.terminal import pt_inputhooks
#-----------------------------------------------------------------------------
# Aliases and Flags
#-----------------------------------------------------------------------------
-gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
+gui_keys = tuple(sorted(pt_inputhooks.backends) + sorted(pt_inputhooks.aliases))
backend_keys = sorted(pylabtools.backends.keys())
backend_keys.insert(0, 'auto')
@@ -102,7 +102,7 @@ shell_aliases['cache-size'] = 'InteractiveShell.cache_size'
class InteractiveShellApp(Configurable):
"""A Mixin for applications that start InteractiveShell instances.
-
+
Provides configurables for loading extensions and executing files
as part of configuring a Shell environment.
@@ -115,73 +115,73 @@ class InteractiveShellApp(Configurable):
- :meth:`init_extensions`
- :meth:`init_code`
"""
- extensions = List(Unicode(),
+ extensions = List(Unicode(),
help="A list of dotted module names of IPython extensions to load."
- ).tag(config=True)
- extra_extension = Unicode('',
+ ).tag(config=True)
+ extra_extension = Unicode('',
help="dotted module name of an IPython extension to load."
- ).tag(config=True)
+ ).tag(config=True)
- reraise_ipython_extension_failures = Bool(False,
+ reraise_ipython_extension_failures = Bool(False,
help="Reraise exceptions encountered loading IPython extensions?",
- ).tag(config=True)
+ ).tag(config=True)
# Extensions that are always loaded (not configurable)
- default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
-
- hide_initial_ns = Bool(True,
+ default_extensions = List(Unicode(), [u'storemagic']).tag(config=False)
+
+ hide_initial_ns = Bool(True,
help="""Should variables loaded at startup (by startup files, exec_lines, etc.)
be hidden from tools like %who?"""
- ).tag(config=True)
+ ).tag(config=True)
- exec_files = List(Unicode(),
+ exec_files = List(Unicode(),
help="""List of files to run at IPython startup."""
- ).tag(config=True)
- exec_PYTHONSTARTUP = Bool(True,
+ ).tag(config=True)
+ exec_PYTHONSTARTUP = Bool(True,
help="""Run the file referenced by the PYTHONSTARTUP environment
variable at IPython startup."""
- ).tag(config=True)
- file_to_run = Unicode('',
- help="""A file to be run""").tag(config=True)
+ ).tag(config=True)
+ file_to_run = Unicode('',
+ help="""A file to be run""").tag(config=True)
- exec_lines = List(Unicode(),
+ exec_lines = List(Unicode(),
help="""lines of code to run at IPython startup."""
- ).tag(config=True)
- code_to_run = Unicode('',
+ ).tag(config=True)
+ code_to_run = Unicode('',
help="Execute the given command string."
- ).tag(config=True)
- module_to_run = Unicode('',
+ ).tag(config=True)
+ module_to_run = Unicode('',
help="Run the module as a script."
- ).tag(config=True)
- gui = CaselessStrEnum(gui_keys, allow_none=True,
+ ).tag(config=True)
+ gui = CaselessStrEnum(gui_keys, allow_none=True,
help="Enable GUI event loop integration with any of {0}.".format(gui_keys)
- ).tag(config=True)
+ ).tag(config=True)
matplotlib = CaselessStrEnum(backend_keys, allow_none=True,
help="""Configure matplotlib for interactive use with
the default matplotlib backend."""
- ).tag(config=True)
+ ).tag(config=True)
pylab = CaselessStrEnum(backend_keys, allow_none=True,
help="""Pre-load matplotlib and numpy for interactive use,
selecting a particular matplotlib backend and loop integration.
"""
- ).tag(config=True)
- pylab_import_all = Bool(True,
+ ).tag(config=True)
+ pylab_import_all = Bool(True,
help="""If true, IPython will populate the user namespace with numpy, pylab, etc.
and an ``import *`` is done from numpy and pylab, when using pylab mode.
-
+
When False, pylab mode should not import any names into the user namespace.
"""
- ).tag(config=True)
+ ).tag(config=True)
shell = Instance('IPython.core.interactiveshell.InteractiveShellABC',
allow_none=True)
- # whether interact-loop should start
- interact = Bool(True)
-
+ # whether interact-loop should start
+ interact = Bool(True)
+
user_ns = Instance(dict, args=None, allow_none=True)
- @observe('user_ns')
- def _user_ns_changed(self, change):
+ @observe('user_ns')
+ def _user_ns_changed(self, change):
if self.shell is not None:
- self.shell.user_ns = change['new']
+ self.shell.user_ns = change['new']
self.shell.init_user_ns()
def init_path(self):
@@ -205,10 +205,10 @@ class InteractiveShellApp(Configurable):
elif self.gui:
enable = shell.enable_gui
key = self.gui
-
+
if not enable:
return
-
+
try:
r = enable(key)
except ImportError:
@@ -219,7 +219,7 @@ class InteractiveShellApp(Configurable):
self.log.warning("GUI event loop or pylab initialization failed")
self.shell.showtraceback()
return
-
+
if isinstance(r, tuple):
gui, backend = r[:2]
self.log.info("Enabling GUI event loop integration, "
@@ -265,16 +265,16 @@ class InteractiveShellApp(Configurable):
self._run_startup_files()
self._run_exec_lines()
self._run_exec_files()
-
+
# Hide variables defined here from %who etc.
if self.hide_initial_ns:
self.shell.user_ns_hidden.update(self.shell.user_ns)
-
+
# command-line execution (ipython -i script.py, ipython -m module)
# should *not* be excluded from %whos
self._run_cmd_line_code()
self._run_module()
-
+
# flush output, so itwon't be attached to the first cell
sys.stdout.flush()
sys.stderr.flush()
@@ -301,7 +301,7 @@ class InteractiveShellApp(Configurable):
def _exec_file(self, fname, shell_futures=False):
try:
full_filename = filefind(fname, [u'.', self.ipython_dir])
- except IOError:
+ except IOError:
self.log.warning("File not found: %r"%fname)
return
# Make sure that the running script gets a proper sys.argv as if it
@@ -337,7 +337,7 @@ class InteractiveShellApp(Configurable):
os.path.join(p, 'startup') for p in chain(ENV_CONFIG_DIRS, SYSTEM_CONFIG_DIRS)
]
startup_files = []
-
+
if self.exec_PYTHONSTARTUP and os.environ.get('PYTHONSTARTUP', False) and \
not (self.file_to_run or self.code_to_run or self.module_to_run):
python_startup = os.environ['PYTHONSTARTUP']
@@ -352,7 +352,7 @@ class InteractiveShellApp(Configurable):
startup_files += glob.glob(os.path.join(startup_dir, '*.ipy'))
if not startup_files:
return
-
+
self.log.debug("Running startup files from %s...", startup_dir)
try:
for fname in sorted(startup_files):
@@ -386,20 +386,20 @@ class InteractiveShellApp(Configurable):
self.log.warning("Error in executing line in user namespace: %s" %
line)
self.shell.showtraceback()
- if not self.interact:
- self.exit(1)
+ if not self.interact:
+ self.exit(1)
# Like Python itself, ignore the second if the first of these is present
elif self.file_to_run:
fname = self.file_to_run
- if os.path.isdir(fname):
- fname = os.path.join(fname, "__main__.py")
+ if os.path.isdir(fname):
+ fname = os.path.join(fname, "__main__.py")
try:
self._exec_file(fname, shell_futures=True)
except:
self.shell.showtraceback(tb_offset=4)
- if not self.interact:
- self.exit(1)
+ if not self.interact:
+ self.exit(1)
def _run_module(self):
"""Run module specified at the command-line."""
diff --git a/contrib/python/ipython/py2/IPython/core/ultratb.py b/contrib/python/ipython/py2/IPython/core/ultratb.py
index a855145825..f327943eb8 100644
--- a/contrib/python/ipython/py2/IPython/core/ultratb.py
+++ b/contrib/python/ipython/py2/IPython/core/ultratb.py
@@ -38,12 +38,12 @@ Give it a shot--you'll love it or you'll hate it.
variables (but otherwise includes the information and context given by
Verbose).
-.. note::
-
- The verbose mode print all variables in the stack, which means it can
- potentially leak sensitive information like access keys, or unencryted
- password.
+.. note::
+ The verbose mode print all variables in the stack, which means it can
+ potentially leak sensitive information like access keys, or unencryted
+ password.
+
Installation instructions for VerboseTB::
import sys,ultratb
@@ -67,9 +67,9 @@ ColorSchemeTable class. Currently the following exist:
- LightBG: similar to Linux but swaps dark/light colors to be more readable
in light background terminals.
- - Neutral: a neutral color scheme that should be readable on both light and
- dark background
-
+ - Neutral: a neutral color scheme that should be readable on both light and
+ dark background
+
You can implement other color schemes easily, the syntax is fairly
self-explanatory. Please send back new schemes you develop to the author for
possible inclusion in future releases.
@@ -88,7 +88,7 @@ Inheritance diagram:
# the file COPYING, distributed as part of this software.
#*****************************************************************************
-from __future__ import absolute_import
+from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
@@ -125,11 +125,11 @@ from IPython.utils import path as util_path
from IPython.utils import py3compat
from IPython.utils import ulinecache
from IPython.utils.data import uniq_stable
-from IPython.utils.terminal import get_terminal_size
-from logging import info, error
-
-import IPython.utils.colorable as colorable
+from IPython.utils.terminal import get_terminal_size
+from logging import info, error
+import IPython.utils.colorable as colorable
+
# Globals
# amount of space to put line numbers before verbose tracebacks
INDENT_SIZE = 8
@@ -226,8 +226,8 @@ def findsource(object):
# the length of lines, which causes an error. Safeguard against that.
lnum = min(object.co_firstlineno, len(lines)) - 1
while lnum > 0:
- if pmatch(lines[lnum]):
- break
+ if pmatch(lines[lnum]):
+ break
lnum -= 1
return lines, lnum
@@ -283,11 +283,11 @@ def getargs(co):
remain.pop()
size = count.pop()
stack[-size:] = [stack[-size:]]
- if not remain:
- break
+ if not remain:
+ break
remain[-1] = remain[-1] - 1
- if not remain:
- break
+ if not remain:
+ break
args[i] = stack[0]
varargs = None
@@ -413,7 +413,7 @@ def _format_traceback_lines(lnum, index, lines, Colors, lvals=None, scheme=None)
if i == lnum:
# This is the line with the error
pad = numbers_width - len(str(i))
- num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
+ num = '%s%s' % (debugger.make_arrow(pad), str(lnum))
line = '%s%s%s %s%s' % (Colors.linenoEm, num,
Colors.line, line, Colors.Normal)
else:
@@ -481,22 +481,22 @@ def find_recursion(etype, value, records):
#---------------------------------------------------------------------------
# Module classes
-class TBTools(colorable.Colorable):
+class TBTools(colorable.Colorable):
"""Basic tools used by all traceback printer classes."""
# Number of frames to skip when reporting tracebacks
tb_offset = 0
- def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
+ def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None, config=None):
# Whether to call the interactive pdb debugger after printing
# tracebacks or not
- super(TBTools, self).__init__(parent=parent, config=config)
+ super(TBTools, self).__init__(parent=parent, config=config)
self.call_pdb = call_pdb
# Output stream to write to. Note that we store the original value in
# a private attribute and then make the public ostream a property, so
- # that we can delay accessing sys.stdout until runtime. The way
- # things are written now, the sys.stdout object is dynamically managed
+ # that we can delay accessing sys.stdout until runtime. The way
+ # things are written now, the sys.stdout object is dynamically managed
# so a reference to it should NEVER be stored statically. This
# property approach confines this detail to a single location, and all
# subclasses can simply access self.ostream for writing.
@@ -509,7 +509,7 @@ class TBTools(colorable.Colorable):
self.old_scheme = color_scheme # save initial value for toggles
if call_pdb:
- self.pdb = debugger.Pdb()
+ self.pdb = debugger.Pdb()
else:
self.pdb = None
@@ -519,12 +519,12 @@ class TBTools(colorable.Colorable):
Valid values are:
- None: the default, which means that IPython will dynamically resolve
- to sys.stdout. This ensures compatibility with most tools, including
+ to sys.stdout. This ensures compatibility with most tools, including
Windows (where plain stdout doesn't recognize ANSI escapes).
- Any object with 'write' and 'flush' attributes.
"""
- return sys.stdout if self._ostream is None else self._ostream
+ return sys.stdout if self._ostream is None else self._ostream
def _set_ostream(self, val):
assert val is None or (hasattr(val, 'write') and hasattr(val, 'flush'))
@@ -596,9 +596,9 @@ class ListTB(TBTools):
Because they are meant to be called without a full traceback (only a
list), instances of this class can't call the interactive pdb debugger."""
- def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
+ def __init__(self, color_scheme='NoColor', call_pdb=False, ostream=None, parent=None):
TBTools.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
- ostream=ostream, parent=parent)
+ ostream=ostream, parent=parent)
def __call__(self, etype, value, elist):
self.ostream.flush()
@@ -711,10 +711,10 @@ class ListTB(TBTools):
have_filedata = False
Colors = self.Colors
list = []
- stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
+ stype = py3compat.cast_unicode(Colors.excName + etype.__name__ + Colors.Normal)
if value is None:
# Not sure if this can still happen in Python 2.6 and above
- list.append(stype + '\n')
+ list.append(stype + '\n')
else:
if issubclass(etype, SyntaxError):
have_filedata = True
@@ -754,10 +754,10 @@ class ListTB(TBTools):
except Exception:
s = self._some_str(value)
if s:
- list.append('%s%s:%s %s\n' % (stype, Colors.excName,
+ list.append('%s%s:%s %s\n' % (stype, Colors.excName,
Colors.Normal, s))
else:
- list.append('%s\n' % stype)
+ list.append('%s\n' % stype)
# sync with user hooks
if have_filedata:
@@ -795,9 +795,9 @@ class ListTB(TBTools):
def _some_str(self, value):
# Lifted from traceback.py
try:
- return py3compat.cast_unicode(str(value))
+ return py3compat.cast_unicode(str(value))
except:
- return u'<unprintable %s object>' % type(value).__name__
+ return u'<unprintable %s object>' % type(value).__name__
#----------------------------------------------------------------------------
@@ -811,7 +811,7 @@ class VerboseTB(TBTools):
def __init__(self, color_scheme='Linux', call_pdb=False, ostream=None,
tb_offset=0, long_header=False, include_vars=True,
- check_cache=None, debugger_cls = None):
+ check_cache=None, debugger_cls = None):
"""Specify traceback offset, headers and color scheme.
Define how many frames to drop from the tracebacks. Calling it with
@@ -832,8 +832,8 @@ class VerboseTB(TBTools):
check_cache = linecache.checkcache
self.check_cache = check_cache
- self.debugger_cls = debugger_cls or debugger.Pdb
-
+ self.debugger_cls = debugger_cls or debugger.Pdb
+
def format_records(self, records, last_unique, recursion_repeat):
"""Format the stack frames of the traceback"""
frames = []
@@ -929,12 +929,12 @@ class VerboseTB(TBTools):
elif file.endswith(('.pyc', '.pyo')):
# Look up the corresponding source file.
- try:
- file = openpy.source_from_cache(file)
- except ValueError:
- # Failed to get the source file for some reason
- # E.g. https://github.com/ipython/ipython/issues/9486
- return '%s %s\n' % (link, call)
+ try:
+ file = openpy.source_from_cache(file)
+ except ValueError:
+ # Failed to get the source file for some reason
+ # E.g. https://github.com/ipython/ipython/issues/9486
+ return '%s %s\n' % (link, call)
def linereader(file=file, lnum=[lnum], getline=ulinecache.getline):
line = getline(file, lnum[0])
@@ -1038,21 +1038,21 @@ class VerboseTB(TBTools):
colors = self.Colors # just a shorthand + quicker name lookup
colorsnormal = colors.Normal # used a lot
exc = '%s%s%s' % (colors.excName, etype, colorsnormal)
- width = min(75, get_terminal_size()[0])
+ width = min(75, get_terminal_size()[0])
if long_version:
# Header with the exception type, python version, and date
pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable
date = time.ctime(time.time())
- head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
- exc, ' ' * (width - len(str(etype)) - len(pyver)),
- pyver, date.rjust(width) )
+ head = '%s%s%s\n%s%s%s\n%s' % (colors.topline, '-' * width, colorsnormal,
+ exc, ' ' * (width - len(str(etype)) - len(pyver)),
+ pyver, date.rjust(width) )
head += "\nA problem occurred executing Python code. Here is the sequence of function" \
"\ncalls leading up to the error, with the most recent (innermost) call last."
else:
# Simplified header
head = '%s%s' % (exc, 'Traceback (most recent call last)'. \
- rjust(width - len(str(etype))) )
+ rjust(width - len(str(etype))) )
return head
@@ -1171,7 +1171,7 @@ class VerboseTB(TBTools):
colors = self.Colors # just a shorthand + quicker name lookup
colorsnormal = colors.Normal # used a lot
- head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
+ head = '%s%s%s' % (colors.topline, '-' * min(75, get_terminal_size()[0]), colorsnormal)
structured_traceback_parts = [head]
if py3compat.PY3:
chained_exceptions_tb_offset = 0
@@ -1287,7 +1287,7 @@ class FormattedTB(VerboseTB, ListTB):
def __init__(self, mode='Plain', color_scheme='Linux', call_pdb=False,
ostream=None,
tb_offset=0, long_header=False, include_vars=False,
- check_cache=None, debugger_cls=None):
+ check_cache=None, debugger_cls=None):
# NEVER change the order of this list. Put new modes at the end:
self.valid_modes = ['Plain', 'Context', 'Verbose']
@@ -1296,7 +1296,7 @@ class FormattedTB(VerboseTB, ListTB):
VerboseTB.__init__(self, color_scheme=color_scheme, call_pdb=call_pdb,
ostream=ostream, tb_offset=tb_offset,
long_header=long_header, include_vars=include_vars,
- check_cache=check_cache, debugger_cls=debugger_cls)
+ check_cache=check_cache, debugger_cls=debugger_cls)
# Different types of tracebacks are joined with different separators to
# form a single string. They are taken from this dict
@@ -1446,7 +1446,7 @@ class SyntaxTB(ListTB):
newtext = ulinecache.getline(value.filename, value.lineno)
if newtext:
value.text = newtext
- self.last_syntax_error = value
+ self.last_syntax_error = value
return super(SyntaxTB, self).structured_traceback(etype, value, elist,
tb_offset=tb_offset, context=context)
diff --git a/contrib/python/ipython/py2/IPython/core/usage.py b/contrib/python/ipython/py2/IPython/core/usage.py
index c4d3c16eca..26506281a7 100644
--- a/contrib/python/ipython/py2/IPython/core/usage.py
+++ b/contrib/python/ipython/py2/IPython/core/usage.py
@@ -114,7 +114,7 @@ MAIN FEATURES
your history for lines that match what you've typed so far, completing as
much as it can.
- - %hist: search history by index.
+ - %hist: search history by index.
* Persistent command history across sessions.
@@ -337,9 +337,9 @@ default_banner_parts = [
default_banner = ''.join(default_banner_parts)
-# deprecated GUI banner
+# deprecated GUI banner
-default_gui_banner = '\n'.join([
- 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed',
- default_banner,
-])
+default_gui_banner = '\n'.join([
+ 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed',
+ default_banner,
+])
diff --git a/contrib/python/ipython/py2/IPython/extensions/storemagic.py b/contrib/python/ipython/py2/IPython/extensions/storemagic.py
index 2fd1abf993..7de7271772 100644
--- a/contrib/python/ipython/py2/IPython/extensions/storemagic.py
+++ b/contrib/python/ipython/py2/IPython/extensions/storemagic.py
@@ -11,8 +11,8 @@ To automatically restore stored variables at startup, add this to your
"""
from __future__ import print_function
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import inspect, os, sys, textwrap
@@ -61,11 +61,11 @@ class StoreMagics(Magics):
Provides the %store magic."""
- autorestore = Bool(False, help=
+ autorestore = Bool(False, help=
"""If True, any %store-d variables will be automatically restored
when IPython starts.
"""
- ).tag(config=True)
+ ).tag(config=True)
def __init__(self, shell):
super(StoreMagics, self).__init__(shell=shell)
diff --git a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
index ad7bd0f981..34de37d525 100644
--- a/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
+++ b/contrib/python/ipython/py2/IPython/external/decorators/_numpy_testing_utils.py
@@ -85,7 +85,7 @@ class WarningManager:
else:
return None
- def __exit__(self, type_, value, traceback):
+ def __exit__(self, type_, value, traceback):
if not self._entered:
raise RuntimeError("Cannot exit %r without entering first" % self)
self._module.filters = self._filters
@@ -101,8 +101,8 @@ def assert_warns(warning_class, func, *args, **kw):
# XXX: once we may depend on python >= 2.6, this can be replaced by the
# warnings module context manager.
- with WarningManager(record=True) as l:
- warnings.simplefilter('always')
+ with WarningManager(record=True) as l:
+ warnings.simplefilter('always')
func(*args, **kw)
if not len(l) > 0:
raise AssertionError("No warning raised when calling %s"
diff --git a/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py b/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
index b724126bbb..62ae52e94e 100644
--- a/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
+++ b/contrib/python/ipython/py2/IPython/lib/backgroundjobs.py
@@ -36,7 +36,7 @@ import threading
from IPython import get_ipython
from IPython.core.ultratb import AutoFormattedTB
-from logging import error
+from logging import error
from IPython.utils.py3compat import string_types
diff --git a/contrib/python/ipython/py2/IPython/lib/deepreload.py b/contrib/python/ipython/py2/IPython/lib/deepreload.py
index 76b493c0bb..45efcb45d2 100644
--- a/contrib/python/ipython/py2/IPython/lib/deepreload.py
+++ b/contrib/python/ipython/py2/IPython/lib/deepreload.py
@@ -351,11 +351,11 @@ def _dreload(module, **kwargs):
import reload explicitly from `IPython.lib.deepreload` to use it
"""
- # this was marked as deprecated and for 5.0 removal, but
- # IPython.core_builtin_trap have a Deprecation warning for 6.0, so cannot
- # remove that now.
+ # this was marked as deprecated and for 5.0 removal, but
+ # IPython.core_builtin_trap have a Deprecation warning for 6.0, so cannot
+ # remove that now.
warn("""
-injecting `dreload` in interactive namespace is deprecated since IPython 4.0.
+injecting `dreload` in interactive namespace is deprecated since IPython 4.0.
Please import `reload` explicitly from `IPython.lib.deepreload`.
""", DeprecationWarning, stacklevel=2)
reload(module, **kwargs)
diff --git a/contrib/python/ipython/py2/IPython/lib/demo.py b/contrib/python/ipython/py2/IPython/lib/demo.py
index b0f3503ed7..7b047ad82a 100644
--- a/contrib/python/ipython/py2/IPython/lib/demo.py
+++ b/contrib/python/ipython/py2/IPython/lib/demo.py
@@ -326,7 +326,7 @@ class Demo(object):
if index is None:
if self.finished:
- print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
+ print('Demo finished. Use <demo_name>.reset() if you want to rerun it.')
return None
index = self.block_index
else:
@@ -397,8 +397,8 @@ class Demo(object):
return
print(self.marquee('<%s> block # %s (%s remaining)' %
- (self.title,index,self.nblocks-index-1)))
- print(self.src_blocks_colored[index])
+ (self.title,index,self.nblocks-index-1)))
+ print(self.src_blocks_colored[index])
sys.stdout.flush()
def show_all(self):
@@ -412,11 +412,11 @@ class Demo(object):
for index,block in enumerate(self.src_blocks_colored):
if silent[index]:
print(marquee('<%s> SILENT block # %s (%s remaining)' %
- (title,index,nblocks-index-1)))
+ (title,index,nblocks-index-1)))
else:
print(marquee('<%s> block # %s (%s remaining)' %
- (title,index,nblocks-index-1)))
- print(block, end=' ')
+ (title,index,nblocks-index-1)))
+ print(block, end=' ')
sys.stdout.flush()
def run_cell(self,source):
@@ -442,17 +442,17 @@ class Demo(object):
self.block_index += 1
if self._silent[index]:
print(marquee('Executing silent block # %s (%s remaining)' %
- (index,self.nblocks-index-1)))
+ (index,self.nblocks-index-1)))
else:
self.pre_cmd()
self.show(index)
if self.auto_all or self._auto[index]:
- print(marquee('output:'))
+ print(marquee('output:'))
else:
- print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
+ print(marquee('Press <q> to quit, <Enter> to execute...'), end=' ')
ans = py3compat.input().strip()
if ans:
- print(marquee('Block NOT executed'))
+ print(marquee('Block NOT executed'))
return
try:
save_argv = sys.argv
@@ -470,10 +470,10 @@ class Demo(object):
if self.block_index == self.nblocks:
mq1 = self.marquee('END OF DEMO')
if mq1:
- # avoid spurious print if empty marquees are used
- print()
- print(mq1)
- print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
+ # avoid spurious print if empty marquees are used
+ print()
+ print(mq1)
+ print(self.marquee('Use <demo_name>.reset() if you want to rerun it.'))
self.finished = True
# These methods are meant to be overridden by subclasses who may wish to
diff --git a/contrib/python/ipython/py2/IPython/lib/display.py b/contrib/python/ipython/py2/IPython/lib/display.py
index 9221e2e062..5a8d79ad47 100644
--- a/contrib/python/ipython/py2/IPython/lib/display.py
+++ b/contrib/python/ipython/py2/IPython/lib/display.py
@@ -41,7 +41,7 @@ class Audio(DisplayObject):
filename : unicode
Path to a local file to load the data from.
embed : boolean
- Should the audio data be embedded using a data URI (True) or should
+ Should the audio data be embedded using a data URI (True) or should
the original source be referenced. Set this to True if you want the
audio to playable later with no internet connection in the notebook.
diff --git a/contrib/python/ipython/py2/IPython/lib/inputhook.py b/contrib/python/ipython/py2/IPython/lib/inputhook.py
index e6e8f2dbbc..e742264914 100644
--- a/contrib/python/ipython/py2/IPython/lib/inputhook.py
+++ b/contrib/python/ipython/py2/IPython/lib/inputhook.py
@@ -1,7 +1,7 @@
# coding: utf-8
"""
-Deprecated since IPython 5.0
-
+Deprecated since IPython 5.0
+
Inputhook management for GUI event loop integration.
"""
@@ -19,13 +19,13 @@ import platform
import sys
from distutils.version import LooseVersion as V
-from warnings import warn
-
-
-warn("`IPython.lib.inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
-
+from warnings import warn
+
+warn("`IPython.lib.inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
+
+
#-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
@@ -105,10 +105,10 @@ else:
class InputHookManager(object):
- """DEPRECATED since IPython 5.0
-
- Manage PyOS_InputHook for different GUI toolkits.
+ """DEPRECATED since IPython 5.0
+ Manage PyOS_InputHook for different GUI toolkits.
+
This class installs various hooks under ``PyOSInputHook`` to handle
GUI event loop integration.
"""
@@ -130,25 +130,25 @@ class InputHookManager(object):
self._current_gui = None
def get_pyos_inputhook(self):
- """DEPRECATED since IPython 5.0
-
- Return the current PyOS_InputHook as a ctypes.c_void_p."""
- warn("`get_pyos_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ """DEPRECATED since IPython 5.0
+
+ Return the current PyOS_InputHook as a ctypes.c_void_p."""
+ warn("`get_pyos_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
return ctypes.c_void_p.in_dll(ctypes.pythonapi,"PyOS_InputHook")
def get_pyos_inputhook_as_func(self):
- """DEPRECATED since IPython 5.0
-
- Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
- warn("`get_pyos_inputhook_as_func` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ """DEPRECATED since IPython 5.0
+
+ Return the current PyOS_InputHook as a ctypes.PYFUNCYPE."""
+ warn("`get_pyos_inputhook_as_func` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
return self.PYFUNC.in_dll(ctypes.pythonapi,"PyOS_InputHook")
def set_inputhook(self, callback):
- """DEPRECATED since IPython 5.0
-
- Set PyOS_InputHook to callback and return the previous one."""
+ """DEPRECATED since IPython 5.0
+
+ Set PyOS_InputHook to callback and return the previous one."""
# On platforms with 'readline' support, it's all too likely to
# have a KeyboardInterrupt signal delivered *even before* an
# initial ``try:`` clause in the callback can be executed, so
@@ -164,10 +164,10 @@ class InputHookManager(object):
return original
def clear_inputhook(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Set PyOS_InputHook to NULL and return the previous one.
+ """DEPRECATED since IPython 5.0
+ Set PyOS_InputHook to NULL and return the previous one.
+
Parameters
----------
app : optional, ignored
@@ -176,8 +176,8 @@ class InputHookManager(object):
the actual value of the parameter is ignored. This uniform interface
makes it easier to have user-level entry points in the main IPython
app like :meth:`enable_gui`."""
- warn("`clear_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`clear_inputhook` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
pyos_inputhook_ptr = self.get_pyos_inputhook()
original = self.get_pyos_inputhook_as_func()
pyos_inputhook_ptr.value = ctypes.c_void_p(None).value
@@ -186,10 +186,10 @@ class InputHookManager(object):
return original
def clear_app_refs(self, gui=None):
- """DEPRECATED since IPython 5.0
-
- Clear IPython's internal reference to an application instance.
+ """DEPRECATED since IPython 5.0
+ Clear IPython's internal reference to an application instance.
+
Whenever we create an app for a user on qt4 or wx, we hold a
reference to the app. This is needed because in some cases bad things
can happen if a user doesn't hold a reference themselves. This
@@ -202,17 +202,17 @@ class InputHookManager(object):
the app for that toolkit. References are not held for gtk or tk
as those toolkits don't have the notion of an app.
"""
- warn("`clear_app_refs` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`clear_app_refs` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if gui is None:
self.apps = {}
elif gui in self.apps:
del self.apps[gui]
def register(self, toolkitname, *aliases):
- """DEPRECATED since IPython 5.0
-
- Register a class to provide the event loop for a given GUI.
+ """DEPRECATED since IPython 5.0
+
+ Register a class to provide the event loop for a given GUI.
This is intended to be used as a class decorator. It should be passed
the names with which to register this GUI integration. The classes
@@ -225,8 +225,8 @@ class InputHookManager(object):
def enable(self, app=None):
...
"""
- warn("`register` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`register` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
def decorator(cls):
if ctypes is not None:
inst = cls(self)
@@ -237,18 +237,18 @@ class InputHookManager(object):
return decorator
def current_gui(self):
- """DEPRECATED since IPython 5.0
-
- Return a string indicating the currently active GUI or None."""
- warn("`current_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ """DEPRECATED since IPython 5.0
+
+ Return a string indicating the currently active GUI or None."""
+ warn("`current_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
return self._current_gui
def enable_gui(self, gui=None, app=None):
- """DEPRECATED since IPython 5.0
-
- Switch amongst GUI input hooks by name.
+ """DEPRECATED since IPython 5.0
+ Switch amongst GUI input hooks by name.
+
This is a higher level method than :meth:`set_inputhook` - it uses the
GUI name to look up a registered object which enables the input hook
for that GUI.
@@ -271,8 +271,8 @@ class InputHookManager(object):
PyOS_InputHook wrapper object or the GUI toolkit app created, if there was
one.
"""
- warn("`enable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`enable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if gui in (None, GUI_NONE):
return self.disable_gui()
@@ -289,28 +289,28 @@ class InputHookManager(object):
app = gui_hook.enable(app)
if app is not None:
app._in_event_loop = True
- self.apps[gui] = app
+ self.apps[gui] = app
return app
def disable_gui(self):
- """DEPRECATED since IPython 5.0
-
- Disable GUI event loop integration.
+ """DEPRECATED since IPython 5.0
+
+ Disable GUI event loop integration.
If an application was registered, this sets its ``_in_event_loop``
attribute to False. It then calls :meth:`clear_inputhook`.
"""
- warn("`disable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("`disable_gui` is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
gui = self._current_gui
if gui in self.apps:
self.apps[gui]._in_event_loop = False
return self.clear_inputhook()
class InputHookBase(object):
- """DEPRECATED since IPython 5.0
-
- Base class for input hooks for specific toolkits.
+ """DEPRECATED since IPython 5.0
+
+ Base class for input hooks for specific toolkits.
Subclasses should define an :meth:`enable` method with one argument, ``app``,
which will either be an instance of the toolkit's application class, or None.
@@ -326,20 +326,20 @@ inputhook_manager = InputHookManager()
@inputhook_manager.register('osx')
class NullInputHook(InputHookBase):
- """DEPRECATED since IPython 5.0
-
- A null inputhook that doesn't need to do anything"""
+ """DEPRECATED since IPython 5.0
+
+ A null inputhook that doesn't need to do anything"""
def enable(self, app=None):
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
@inputhook_manager.register('wx')
class WxInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with wxPython.
+ """DEPRECATED since IPython 5.0
+ Enable event loop integration with wxPython.
+
Parameters
----------
app : WX Application, optional.
@@ -359,8 +359,8 @@ class WxInputHook(InputHookBase):
import wx
app = wx.App(redirect=False, clearSigInt=False)
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import wx
wx_version = V(wx.__version__).version
@@ -383,14 +383,14 @@ class WxInputHook(InputHookBase):
return app
def disable(self):
- """DEPRECATED since IPython 5.0
-
- Disable event loop integration with wxPython.
+ """DEPRECATED since IPython 5.0
+ Disable event loop integration with wxPython.
+
This restores appnapp on OS X
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if _use_appnope():
from appnope import nap
nap()
@@ -398,9 +398,9 @@ class WxInputHook(InputHookBase):
@inputhook_manager.register('qt', 'qt4')
class Qt4InputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with PyQt4.
+ """DEPRECATED since IPython 5.0
+
+ Enable event loop integration with PyQt4.
Parameters
----------
@@ -421,8 +421,8 @@ class Qt4InputHook(InputHookBase):
from PyQt4 import QtCore
app = QtGui.QApplication(sys.argv)
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
from IPython.lib.inputhookqt4 import create_inputhook_qt4
app, inputhook_qt4 = create_inputhook_qt4(self.manager, app)
self.manager.set_inputhook(inputhook_qt4)
@@ -433,14 +433,14 @@ class Qt4InputHook(InputHookBase):
return app
def disable_qt4(self):
- """DEPRECATED since IPython 5.0
-
- Disable event loop integration with PyQt4.
+ """DEPRECATED since IPython 5.0
+ Disable event loop integration with PyQt4.
+
This restores appnapp on OS X
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if _use_appnope():
from appnope import nap
nap()
@@ -449,8 +449,8 @@ class Qt4InputHook(InputHookBase):
@inputhook_manager.register('qt5')
class Qt5InputHook(Qt4InputHook):
def enable(self, app=None):
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
os.environ['QT_API'] = 'pyqt5'
return Qt4InputHook.enable(self, app)
@@ -458,10 +458,10 @@ class Qt5InputHook(Qt4InputHook):
@inputhook_manager.register('gtk')
class GtkInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with PyGTK.
+ """DEPRECATED since IPython 5.0
+ Enable event loop integration with PyGTK.
+
Parameters
----------
app : ignored
@@ -475,8 +475,8 @@ class GtkInputHook(InputHookBase):
the PyGTK to integrate with terminal based applications like
IPython.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import gtk
try:
gtk.set_interactive(True)
@@ -489,10 +489,10 @@ class GtkInputHook(InputHookBase):
@inputhook_manager.register('tk')
class TkInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with Tk.
+ """DEPRECATED since IPython 5.0
+ Enable event loop integration with Tk.
+
Parameters
----------
app : toplevel :class:`Tkinter.Tk` widget, optional.
@@ -506,8 +506,8 @@ class TkInputHook(InputHookBase):
:class:`InputHookManager`, since creating that object automatically
sets ``PyOS_InputHook``.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
if app is None:
try:
from tkinter import Tk # Py 3
@@ -522,10 +522,10 @@ class TkInputHook(InputHookBase):
@inputhook_manager.register('glut')
class GlutInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with GLUT.
+ """DEPRECATED since IPython 5.0
+ Enable event loop integration with GLUT.
+
Parameters
----------
@@ -547,8 +547,8 @@ class GlutInputHook(InputHookBase):
The default screen mode is set to:
glut.GLUT_DOUBLE | glut.GLUT_RGBA | glut.GLUT_DEPTH
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import OpenGL.GLUT as glut
from IPython.lib.inputhookglut import glut_display_mode, \
@@ -576,16 +576,16 @@ class GlutInputHook(InputHookBase):
def disable(self):
- """DEPRECATED since IPython 5.0
-
- Disable event loop integration with glut.
+ """DEPRECATED since IPython 5.0
+
+ Disable event loop integration with glut.
This sets PyOS_InputHook to NULL and set the display function to a
dummy one and set the timer to a dummy timer that will be triggered
very far in the future.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
import OpenGL.GLUT as glut
from glut_support import glutMainLoopEvent
@@ -596,10 +596,10 @@ class GlutInputHook(InputHookBase):
@inputhook_manager.register('pyglet')
class PygletInputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with pyglet.
+ """DEPRECATED since IPython 5.0
+ Enable event loop integration with pyglet.
+
Parameters
----------
app : ignored
@@ -614,8 +614,8 @@ class PygletInputHook(InputHookBase):
IPython.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
from IPython.lib.inputhookpyglet import inputhook_pyglet
self.manager.set_inputhook(inputhook_pyglet)
return app
@@ -624,10 +624,10 @@ class PygletInputHook(InputHookBase):
@inputhook_manager.register('gtk3')
class Gtk3InputHook(InputHookBase):
def enable(self, app=None):
- """DEPRECATED since IPython 5.0
-
- Enable event loop integration with Gtk3 (gir bindings).
+ """DEPRECATED since IPython 5.0
+ Enable event loop integration with Gtk3 (gir bindings).
+
Parameters
----------
app : ignored
@@ -641,8 +641,8 @@ class Gtk3InputHook(InputHookBase):
the Gtk3 to integrate with terminal based applications like
IPython.
"""
- warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
- DeprecationWarning, stacklevel=2)
+ warn("This function is deprecated since IPython 5.0 and will be removed in future versions.",
+ DeprecationWarning, stacklevel=2)
from IPython.lib.inputhookgtk3 import inputhook_gtk3
self.manager.set_inputhook(inputhook_gtk3)
diff --git a/contrib/python/ipython/py2/IPython/lib/latextools.py b/contrib/python/ipython/py2/IPython/lib/latextools.py
index c3230dd489..5b3c93dc63 100644
--- a/contrib/python/ipython/py2/IPython/lib/latextools.py
+++ b/contrib/python/ipython/py2/IPython/lib/latextools.py
@@ -39,24 +39,24 @@ class LaTeXTool(SingletonConfigurable):
# for display style, the default ["matplotlib", "dvipng"] can
# be used. To NOT use dvipng so that other repr such as
# unicode pretty printing is used, you can use ["matplotlib"].
- ).tag(config=True)
+ ).tag(config=True)
use_breqn = Bool(
True,
help="Use breqn.sty to automatically break long equations. "
"This configuration takes effect only for dvipng backend.",
- ).tag(config=True)
+ ).tag(config=True)
packages = List(
['amsmath', 'amsthm', 'amssymb', 'bm'],
help="A list of packages to use for dvipng backend. "
"'breqn' will be automatically appended when use_breqn=True.",
- ).tag(config=True)
+ ).tag(config=True)
preamble = Unicode(
help="Additional preamble to use when generating LaTeX source "
"for dvipng backend.",
- ).tag(config=True)
+ ).tag(config=True)
def latex_to_png(s, encode=False, backend=None, wrap=False):
@@ -64,7 +64,7 @@ def latex_to_png(s, encode=False, backend=None, wrap=False):
Parameters
----------
- s : str
+ s : str
The raw string containing valid inline LaTeX.
encode : bool, optional
Should the PNG data base64 encoded to make it JSON'able.
@@ -97,24 +97,24 @@ def latex_to_png(s, encode=False, backend=None, wrap=False):
def latex_to_png_mpl(s, wrap):
try:
from matplotlib import mathtext
- from pyparsing import ParseFatalException
+ from pyparsing import ParseFatalException
except ImportError:
return None
-
+
# mpl mathtext doesn't support display math, force inline
s = s.replace('$$', '$')
if wrap:
s = u'${0}$'.format(s)
- try:
- mt = mathtext.MathTextParser('bitmap')
- f = BytesIO()
- mt.to_png(f, s, fontsize=12)
- return f.getvalue()
- except (ValueError, RuntimeError, ParseFatalException):
- return None
-
+ try:
+ mt = mathtext.MathTextParser('bitmap')
+ f = BytesIO()
+ mt.to_png(f, s, fontsize=12)
+ return f.getvalue()
+ except (ValueError, RuntimeError, ParseFatalException):
+ return None
+
def latex_to_png_dvipng(s, wrap):
try:
find_cmd('latex')
@@ -142,8 +142,8 @@ def latex_to_png_dvipng(s, wrap):
with open(outfile, "rb") as f:
return f.read()
- except subprocess.CalledProcessError:
- return None
+ except subprocess.CalledProcessError:
+ return None
finally:
shutil.rmtree(workdir)
diff --git a/contrib/python/ipython/py2/IPython/lib/lexers.py b/contrib/python/ipython/py2/IPython/lib/lexers.py
index 9160ae1245..1b81e3db61 100644
--- a/contrib/python/ipython/py2/IPython/lib/lexers.py
+++ b/contrib/python/ipython/py2/IPython/lib/lexers.py
@@ -44,7 +44,7 @@ from pygments.lexer import (
Lexer, DelegatingLexer, RegexLexer, do_insertions, bygroups, using,
)
from pygments.token import (
- Generic, Keyword, Literal, Name, Operator, Other, Text, Error,
+ Generic, Keyword, Literal, Name, Operator, Other, Text, Error,
)
from pygments.util import get_bool_opt
@@ -235,13 +235,13 @@ class IPythonConsoleLexer(Lexer):
# The regexps used to determine what is input and what is output.
# The default prompts for IPython are:
#
- # in = 'In [#]: '
- # continuation = ' .D.: '
- # template = 'Out[#]: '
- #
- # Where '#' is the 'prompt number' or 'execution count' and 'D'
- # D is a number of dots matching the width of the execution count
+ # in = 'In [#]: '
+ # continuation = ' .D.: '
+ # template = 'Out[#]: '
#
+ # Where '#' is the 'prompt number' or 'execution count' and 'D'
+ # D is a number of dots matching the width of the execution count
+ #
in1_regex = r'In \[[0-9]+\]: '
in2_regex = r' \.\.+\.: '
out_regex = r'Out\[[0-9]+\]: '
@@ -475,9 +475,9 @@ class IPythonConsoleLexer(Lexer):
self.insertions.append((len(self.buffer), [insertion]))
self.buffer += code
- for token in self.buffered_tokens():
- yield token
-
+ for token in self.buffered_tokens():
+ yield token
+
class IPyLexer(Lexer):
"""
Primary lexer for all IPython-like code.
diff --git a/contrib/python/ipython/py2/IPython/lib/pretty.py b/contrib/python/ipython/py2/IPython/lib/pretty.py
index 28eee523c5..09d638cbcb 100644
--- a/contrib/python/ipython/py2/IPython/lib/pretty.py
+++ b/contrib/python/ipython/py2/IPython/lib/pretty.py
@@ -85,7 +85,7 @@ import re
import datetime
from collections import deque
-from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
+from IPython.utils.py3compat import PY3, PYPY, cast_unicode, string_types
from IPython.utils.encoding import get_stream_enc
from io import StringIO
@@ -609,8 +609,8 @@ def _dict_pprinter_factory(start, end):
def inner(obj, p, cycle):
if cycle:
return p.text('{...}')
- step = len(start)
- p.begin_group(step, start)
+ step = len(start)
+ p.begin_group(step, start)
keys = obj.keys()
# if dict isn't large enough to be truncated, sort keys before displaying
# From Python 3.7, dicts preserve order by definition, so we don't sort.
@@ -624,7 +624,7 @@ def _dict_pprinter_factory(start, end):
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
- p.end_group(step, end)
+ p.end_group(step, end)
return inner
@@ -634,11 +634,11 @@ def _super_pprint(obj, p, cycle):
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
- if PYPY: # In PyPy, super() objects don't have __self__ attributes
- dself = obj.__repr__.__self__
- p.pretty(None if dself is obj else dself)
- else:
- p.pretty(obj.__self__)
+ if PYPY: # In PyPy, super() objects don't have __self__ attributes
+ dself = obj.__repr__.__self__
+ p.pretty(None if dself is obj else dself)
+ else:
+ p.pretty(obj.__self__)
p.end_group(8, '>')
@@ -672,10 +672,10 @@ def _type_pprint(obj, p, cycle):
# Heap allocated types might not have the module attribute,
# and others may set it to None.
- # Checks for a __repr__ override in the metaclass. Can't compare the
- # type(obj).__repr__ directly because in PyPy the representation function
- # inherited from type isn't the same type.__repr__
- if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
+ # Checks for a __repr__ override in the metaclass. Can't compare the
+ # type(obj).__repr__ directly because in PyPy the representation function
+ # inherited from type isn't the same type.__repr__
+ if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
_repr_pprint(obj, p, cycle)
return
@@ -762,15 +762,15 @@ _type_pprinters = {
}
try:
- # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
- # using dict.setdefault avoids overwritting the dict printer
- _type_pprinters.setdefault(types.DictProxyType,
- _dict_pprinter_factory('dict_proxy({', '})'))
+ # In PyPy, types.DictProxyType is dict, setting the dictproxy printer
+ # using dict.setdefault avoids overwritting the dict printer
+ _type_pprinters.setdefault(types.DictProxyType,
+ _dict_pprinter_factory('dict_proxy({', '})'))
_type_pprinters[types.ClassType] = _type_pprint
_type_pprinters[types.SliceType] = _repr_pprint
except AttributeError: # Python 3
- _type_pprinters[types.MappingProxyType] = \
- _dict_pprinter_factory('mappingproxy({', '})')
+ _type_pprinters[types.MappingProxyType] = \
+ _dict_pprinter_factory('mappingproxy({', '})')
_type_pprinters[slice] = _repr_pprint
try:
diff --git a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
index 8df9ace1f3..2173954c20 100644
--- a/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
+++ b/contrib/python/ipython/py2/IPython/sphinxext/ipython_directive.py
@@ -874,7 +874,7 @@ class IPythonDirective(Directive):
# EmbeddedSphinxShell is created, its interactive shell member
# is the same for each instance.
- if mplbackend and 'matplotlib.backends' not in sys.modules:
+ if mplbackend and 'matplotlib.backends' not in sys.modules:
import matplotlib
matplotlib.use(mplbackend)
diff --git a/contrib/python/ipython/py2/IPython/terminal/debugger.py b/contrib/python/ipython/py2/IPython/terminal/debugger.py
index c68a3204a6..4be1bae6a8 100644
--- a/contrib/python/ipython/py2/IPython/terminal/debugger.py
+++ b/contrib/python/ipython/py2/IPython/terminal/debugger.py
@@ -1,46 +1,46 @@
import signal
import sys
-from IPython.core.debugger import Pdb
-
-from IPython.core.completer import IPCompleter
-from .ptutils import IPythonPTCompleter
+from IPython.core.debugger import Pdb
+
+from IPython.core.completer import IPCompleter
+from .ptutils import IPythonPTCompleter
from .shortcuts import suspend_to_bg, cursor_in_leading_ws
-
+
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import (Condition, HasFocus, HasSelection,
ViInsertMode, EmacsInsertMode)
from prompt_toolkit.keys import Keys
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
-from prompt_toolkit.token import Token
-from prompt_toolkit.shortcuts import create_prompt_application
-from prompt_toolkit.interface import CommandLineInterface
-from prompt_toolkit.enums import EditingMode
-
-
-class TerminalPdb(Pdb):
- def __init__(self, *args, **kwargs):
- Pdb.__init__(self, *args, **kwargs)
- self._ptcomp = None
- self.pt_init()
-
- def pt_init(self):
- def get_prompt_tokens(cli):
- return [(Token.Prompt, self.prompt)]
-
+from prompt_toolkit.token import Token
+from prompt_toolkit.shortcuts import create_prompt_application
+from prompt_toolkit.interface import CommandLineInterface
+from prompt_toolkit.enums import EditingMode
+
+
+class TerminalPdb(Pdb):
+ def __init__(self, *args, **kwargs):
+ Pdb.__init__(self, *args, **kwargs)
+ self._ptcomp = None
+ self.pt_init()
+
+ def pt_init(self):
+ def get_prompt_tokens(cli):
+ return [(Token.Prompt, self.prompt)]
+
def patch_stdout(**kwargs):
return self.pt_cli.patch_stdout_context(**kwargs)
- if self._ptcomp is None:
- compl = IPCompleter(shell=self.shell,
- namespace={},
- global_namespace={},
- use_readline=False,
- parent=self.shell,
- )
+ if self._ptcomp is None:
+ compl = IPCompleter(shell=self.shell,
+ namespace={},
+ global_namespace={},
+ use_readline=False,
+ parent=self.shell,
+ )
self._ptcomp = IPythonPTCompleter(compl, patch_stdout=patch_stdout)
-
+
kbmanager = KeyBindingManager.for_prompt()
supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend
@@ -55,55 +55,55 @@ class TerminalPdb(Pdb):
))(display_completions_like_readline)
multicolumn = (self.shell.display_completions == 'multicolumn')
- self._pt_app = create_prompt_application(
- editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
+ self._pt_app = create_prompt_application(
+ editing_mode=getattr(EditingMode, self.shell.editing_mode.upper()),
key_bindings_registry=kbmanager.registry,
- history=self.shell.debugger_history,
- completer= self._ptcomp,
- enable_history_search=True,
- mouse_support=self.shell.mouse_support,
+ history=self.shell.debugger_history,
+ completer= self._ptcomp,
+ enable_history_search=True,
+ mouse_support=self.shell.mouse_support,
get_prompt_tokens=get_prompt_tokens,
display_completions_in_columns=multicolumn,
style=self.shell.style
- )
- self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop)
-
- def cmdloop(self, intro=None):
- """Repeatedly issue a prompt, accept input, parse an initial prefix
- off the received input, and dispatch to action methods, passing them
- the remainder of the line as argument.
-
- override the same methods from cmd.Cmd to provide prompt toolkit replacement.
- """
- if not self.use_rawinput:
- raise ValueError('Sorry ipdb does not support use_rawinput=False')
-
- self.preloop()
-
- try:
- if intro is not None:
- self.intro = intro
- if self.intro:
- self.stdout.write(str(self.intro)+"\n")
- stop = None
- while not stop:
- if self.cmdqueue:
- line = self.cmdqueue.pop(0)
- else:
- self._ptcomp.ipy_completer.namespace = self.curframe_locals
- self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
- try:
- line = self.pt_cli.run(reset_current_buffer=True).text
- except EOFError:
- line = 'EOF'
- line = self.precmd(line)
- stop = self.onecmd(line)
- stop = self.postcmd(stop, line)
- self.postloop()
- except Exception:
- raise
-
-
+ )
+ self.pt_cli = CommandLineInterface(self._pt_app, eventloop=self.shell._eventloop)
+
+ def cmdloop(self, intro=None):
+ """Repeatedly issue a prompt, accept input, parse an initial prefix
+ off the received input, and dispatch to action methods, passing them
+ the remainder of the line as argument.
+
+ override the same methods from cmd.Cmd to provide prompt toolkit replacement.
+ """
+ if not self.use_rawinput:
+ raise ValueError('Sorry ipdb does not support use_rawinput=False')
+
+ self.preloop()
+
+ try:
+ if intro is not None:
+ self.intro = intro
+ if self.intro:
+ self.stdout.write(str(self.intro)+"\n")
+ stop = None
+ while not stop:
+ if self.cmdqueue:
+ line = self.cmdqueue.pop(0)
+ else:
+ self._ptcomp.ipy_completer.namespace = self.curframe_locals
+ self._ptcomp.ipy_completer.global_namespace = self.curframe.f_globals
+ try:
+ line = self.pt_cli.run(reset_current_buffer=True).text
+ except EOFError:
+ line = 'EOF'
+ line = self.precmd(line)
+ stop = self.onecmd(line)
+ stop = self.postcmd(stop, line)
+ self.postloop()
+ except Exception:
+ raise
+
+
def set_trace(frame=None):
"""
Start debugging from `frame`.
diff --git a/contrib/python/ipython/py2/IPython/terminal/embed.py b/contrib/python/ipython/py2/IPython/terminal/embed.py
index 5ad70431e4..9f8be00a77 100644
--- a/contrib/python/ipython/py2/IPython/terminal/embed.py
+++ b/contrib/python/ipython/py2/IPython/terminal/embed.py
@@ -14,7 +14,7 @@ import warnings
from IPython.core import ultratb, compilerop
from IPython.core import magic_arguments
from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.core.interactiveshell import DummyMod, InteractiveShell
+from IPython.core.interactiveshell import DummyMod, InteractiveShell
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from IPython.terminal.ipapp import load_default_config
@@ -117,33 +117,33 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
display_banner = CBool(True)
exit_msg = Unicode()
- # When embedding, by default we don't change the terminal title
- term_title = Bool(False,
- help="Automatically set the terminal title"
- ).tag(config=True)
-
- _inactive_locations = set()
-
- @property
- def embedded_active(self):
+ # When embedding, by default we don't change the terminal title
+ term_title = Bool(False,
+ help="Automatically set the terminal title"
+ ).tag(config=True)
+
+ _inactive_locations = set()
+
+ @property
+ def embedded_active(self):
return (self._call_location_id not in InteractiveShellEmbed._inactive_locations)\
and (self._init_location_id not in InteractiveShellEmbed._inactive_locations)
-
+
def _disable_init_location(self):
"""Disable the current Instance creation location"""
InteractiveShellEmbed._inactive_locations.add(self._init_location_id)
- @embedded_active.setter
- def embedded_active(self, value):
+ @embedded_active.setter
+ def embedded_active(self, value):
if value:
InteractiveShellEmbed._inactive_locations.discard(
self._call_location_id)
InteractiveShellEmbed._inactive_locations.discard(
self._init_location_id)
- else:
+ else:
InteractiveShellEmbed._inactive_locations.add(
self._call_location_id)
-
+
def __init__(self, **kw):
if kw.get('user_global_ns', None) is not None:
raise DeprecationWarning(
@@ -154,7 +154,7 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
frame = sys._getframe(1)
clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno)
self._init_location_id = clid
-
+
super(InteractiveShellEmbed,self).__init__(**kw)
# don't use the ipython crash handler so that user exceptions aren't
@@ -219,9 +219,9 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
else:
self.old_banner2 = ''
- if self.display_banner:
- self.show_banner()
-
+ if self.display_banner:
+ self.show_banner()
+
# Call the embedding code with a stack depth of 1 so it can skip over
# our call and get the original caller's namespaces.
self.mainloop(local_ns, module, stack_depth=stack_depth,
@@ -264,11 +264,11 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
"""
if (global_ns is not None) and (module is None):
- raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
-
- if (display_banner is not None):
- warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
+ raise DeprecationWarning("'global_ns' keyword argument is deprecated, and has been removed in IPython 5.0 use `module` keyword argument instead.")
+ if (display_banner is not None):
+ warnings.warn("The display_banner parameter is deprecated since IPython 4.0", DeprecationWarning)
+
# Get locals and globals from caller
if ((local_ns is None or module is None or compile_flags is None)
and self.default_user_namespaces):
@@ -278,14 +278,14 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
local_ns = call_frame.f_locals
if module is None:
global_ns = call_frame.f_globals
- try:
- module = sys.modules[global_ns['__name__']]
- except KeyError:
- warnings.warn("Failed to get module %s" % \
- global_ns.get('__name__', 'unknown module')
- )
- module = DummyMod()
- module.__dict__ = global_ns
+ try:
+ module = sys.modules[global_ns['__name__']]
+ except KeyError:
+ warnings.warn("Failed to get module %s" % \
+ global_ns.get('__name__', 'unknown module')
+ )
+ module = DummyMod()
+ module.__dict__ = global_ns
if compile_flags is None:
compile_flags = (call_frame.f_code.co_flags &
compilerop.PyCF_MASK)
@@ -320,7 +320,7 @@ class InteractiveShellEmbed(TerminalInteractiveShell):
self.set_completer_frame()
with self.builtin_trap, self.display_trap:
- self.interact()
+ self.interact()
# now, purge out the local namespace of IPython's hidden variables.
if local_ns is not None:
@@ -378,7 +378,7 @@ def embed(**kwargs):
if saved_shell_instance is not None:
cls = type(saved_shell_instance)
cls.clear_instance()
- frame = sys._getframe(1)
+ frame = sys._getframe(1)
shell = InteractiveShellEmbed.instance(_init_location_id='%s:%s' % (
frame.f_code.co_filename, frame.f_lineno), **kwargs)
shell(header=header, stack_depth=2, compile_flags=compile_flags,
diff --git a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
index f67cc6b502..c5b0d7d921 100644
--- a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
+++ b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py
@@ -1,68 +1,68 @@
-"""IPython terminal interface using prompt_toolkit"""
+"""IPython terminal interface using prompt_toolkit"""
from __future__ import print_function
import os
import sys
-import warnings
-from warnings import warn
+import warnings
+from warnings import warn
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
-from IPython.utils import io
+from IPython.utils import io
from IPython.utils.py3compat import PY3, cast_unicode_py2, input, string_types
from IPython.utils.terminal import toggle_set_term_title, set_term_title
from IPython.utils.process import abbrev_cwd
from traitlets import Bool, Unicode, Dict, Integer, observe, Instance, Type, default, Enum, Union
from prompt_toolkit.document import Document
-from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
-from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
-from prompt_toolkit.history import InMemoryHistory
-from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
-from prompt_toolkit.interface import CommandLineInterface
-from prompt_toolkit.key_binding.manager import KeyBindingManager
-from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
-from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
+from prompt_toolkit.enums import DEFAULT_BUFFER, EditingMode
+from prompt_toolkit.filters import (HasFocus, Condition, IsDone)
+from prompt_toolkit.history import InMemoryHistory
+from prompt_toolkit.shortcuts import create_prompt_application, create_eventloop, create_prompt_layout, create_output
+from prompt_toolkit.interface import CommandLineInterface
+from prompt_toolkit.key_binding.manager import KeyBindingManager
+from prompt_toolkit.layout.processors import ConditionalProcessor, HighlightMatchingBracketProcessor
+from prompt_toolkit.styles import PygmentsStyle, DynamicStyle
from pygments.styles import get_style_by_name
from pygments.style import Style
-from pygments.token import Token
-
-from .debugger import TerminalPdb, Pdb
-from .magics import TerminalMagics
+from pygments.token import Token
+
+from .debugger import TerminalPdb, Pdb
+from .magics import TerminalMagics
from .pt_inputhooks import get_inputhook_name_and_func
-from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
-from .ptutils import IPythonPTCompleter, IPythonPTLexer
-from .shortcuts import register_ipython_shortcuts
-
-DISPLAY_BANNER_DEPRECATED = object()
-
-
-from pygments.style import Style
-
-class _NoStyle(Style): pass
-
-
-
-_style_overrides_light_bg = {
- Token.Prompt: '#0000ff',
- Token.PromptNum: '#0000ee bold',
- Token.OutPrompt: '#cc0000',
- Token.OutPromptNum: '#bb0000 bold',
-}
-
-_style_overrides_linux = {
- Token.Prompt: '#00cc00',
- Token.PromptNum: '#00bb00 bold',
- Token.OutPrompt: '#cc0000',
- Token.OutPromptNum: '#bb0000 bold',
-}
-
-
-
+from .prompts import Prompts, ClassicPrompts, RichPromptDisplayHook
+from .ptutils import IPythonPTCompleter, IPythonPTLexer
+from .shortcuts import register_ipython_shortcuts
+
+DISPLAY_BANNER_DEPRECATED = object()
+
+
+from pygments.style import Style
+
+class _NoStyle(Style): pass
+
+
+
+_style_overrides_light_bg = {
+ Token.Prompt: '#0000ff',
+ Token.PromptNum: '#0000ee bold',
+ Token.OutPrompt: '#cc0000',
+ Token.OutPromptNum: '#bb0000 bold',
+}
+
+_style_overrides_linux = {
+ Token.Prompt: '#00cc00',
+ Token.PromptNum: '#00bb00 bold',
+ Token.OutPrompt: '#cc0000',
+ Token.OutPromptNum: '#bb0000 bold',
+}
+
+
+
def get_default_editor():
try:
ed = os.environ['EDITOR']
- if not PY3:
+ if not PY3:
ed = ed.decode()
return ed
except KeyError:
@@ -76,153 +76,153 @@ def get_default_editor():
else:
return 'notepad' # same in Windows!
-# conservatively check for tty
-# overridden streams can result in things like:
-# - sys.stdin = None
-# - no isatty method
-for _name in ('stdin', 'stdout', 'stderr'):
- _stream = getattr(sys, _name)
- if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
- _is_tty = False
- break
-else:
- _is_tty = True
+# conservatively check for tty
+# overridden streams can result in things like:
+# - sys.stdin = None
+# - no isatty method
+for _name in ('stdin', 'stdout', 'stderr'):
+ _stream = getattr(sys, _name)
+ if not _stream or not hasattr(_stream, 'isatty') or not _stream.isatty():
+ _is_tty = False
+ break
+else:
+ _is_tty = True
-_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
+_use_simple_prompt = ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or (not _is_tty)
-class TerminalInteractiveShell(InteractiveShell):
- space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
- 'to reserve for the completion menu'
- ).tag(config=True)
+class TerminalInteractiveShell(InteractiveShell):
+ space_for_menu = Integer(6, help='Number of line at the bottom of the screen '
+ 'to reserve for the completion menu'
+ ).tag(config=True)
- def _space_for_menu_changed(self, old, new):
- self._update_layout()
+ def _space_for_menu_changed(self, old, new):
+ self._update_layout()
- pt_cli = None
- debugger_history = None
- _pt_app = None
+ pt_cli = None
+ debugger_history = None
+ _pt_app = None
- simple_prompt = Bool(_use_simple_prompt,
+ simple_prompt = Bool(_use_simple_prompt,
help="""Use `raw_input` for the REPL, without completion and prompt colors.
- Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
- IPython own testing machinery, and emacs inferior-shell integration through elpy.
+ Useful when controlling IPython as a subprocess, and piping STDIN/OUT/ERR. Known usage are:
+ IPython own testing machinery, and emacs inferior-shell integration through elpy.
- This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
- environment variable is set, or the current terminal is not a tty.
+ This mode default to `True` if the `IPY_TEST_SIMPLE_PROMPT`
+ environment variable is set, or the current terminal is not a tty.
- """
- ).tag(config=True)
+ """
+ ).tag(config=True)
- @property
- def debugger_cls(self):
- return Pdb if self.simple_prompt else TerminalPdb
+ @property
+ def debugger_cls(self):
+ return Pdb if self.simple_prompt else TerminalPdb
- confirm_exit = Bool(True,
- help="""
- Set to confirm when you try to exit IPython with an EOF (Control-D
- in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
- you can force a direct exit without any confirmation.""",
- ).tag(config=True)
+ confirm_exit = Bool(True,
+ help="""
+ Set to confirm when you try to exit IPython with an EOF (Control-D
+ in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
+ you can force a direct exit without any confirmation.""",
+ ).tag(config=True)
- editing_mode = Unicode('emacs',
- help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
- ).tag(config=True)
+ editing_mode = Unicode('emacs',
+ help="Shortcut style to use at the prompt. 'vi' or 'emacs'.",
+ ).tag(config=True)
- mouse_support = Bool(False,
- help="Enable mouse support in the prompt"
- ).tag(config=True)
+ mouse_support = Bool(False,
+ help="Enable mouse support in the prompt"
+ ).tag(config=True)
# We don't load the list of styles for the help string, because loading
# Pygments plugins takes time and can cause unexpected errors.
highlighting_style = Union([Unicode('legacy'), Type(klass=Style)],
help="""The name or class of a Pygments style to use for syntax
highlighting. To see available styles, run `pygmentize -L styles`."""
- ).tag(config=True)
+ ).tag(config=True)
- @observe('highlighting_style')
- @observe('colors')
- def _highlighting_style_changed(self, change):
- self.refresh_style()
+ @observe('highlighting_style')
+ @observe('colors')
+ def _highlighting_style_changed(self, change):
+ self.refresh_style()
- def refresh_style(self):
+ def refresh_style(self):
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
- highlighting_style_overrides = Dict(
- help="Override highlighting format for specific tokens"
- ).tag(config=True)
+ highlighting_style_overrides = Dict(
+ help="Override highlighting format for specific tokens"
+ ).tag(config=True)
- true_color = Bool(False,
- help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
- "If your terminal supports true color, the following command "
- "should print 'TRUECOLOR' in orange: "
- "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
- ).tag(config=True)
+ true_color = Bool(False,
+ help=("Use 24bit colors instead of 256 colors in prompt highlighting. "
+ "If your terminal supports true color, the following command "
+ "should print 'TRUECOLOR' in orange: "
+ "printf \"\\x1b[38;2;255;100;0mTRUECOLOR\\x1b[0m\\n\"")
+ ).tag(config=True)
- editor = Unicode(get_default_editor(),
- help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
- ).tag(config=True)
+ editor = Unicode(get_default_editor(),
+ help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
+ ).tag(config=True)
- prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
+ prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True)
- prompts = Instance(Prompts)
+ prompts = Instance(Prompts)
- @default('prompts')
- def _prompts_default(self):
- return self.prompts_class(self)
+ @default('prompts')
+ def _prompts_default(self):
+ return self.prompts_class(self)
- @observe('prompts')
- def _(self, change):
- self._update_layout()
+ @observe('prompts')
+ def _(self, change):
+ self._update_layout()
- @default('displayhook_class')
- def _displayhook_class_default(self):
- return RichPromptDisplayHook
+ @default('displayhook_class')
+ def _displayhook_class_default(self):
+ return RichPromptDisplayHook
- term_title = Bool(True,
- help="Automatically set the terminal title"
- ).tag(config=True)
+ term_title = Bool(True,
+ help="Automatically set the terminal title"
+ ).tag(config=True)
display_completions = Enum(('column', 'multicolumn','readlinelike'),
- help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
- "'readlinelike'. These options are for `prompt_toolkit`, see "
- "`prompt_toolkit` documentation for more information."
- ),
- default_value='multicolumn').tag(config=True)
+ help= ( "Options for displaying tab completions, 'column', 'multicolumn', and "
+ "'readlinelike'. These options are for `prompt_toolkit`, see "
+ "`prompt_toolkit` documentation for more information."
+ ),
+ default_value='multicolumn').tag(config=True)
- highlight_matching_brackets = Bool(True,
+ highlight_matching_brackets = Bool(True,
help="Highlight matching brackets.",
- ).tag(config=True)
+ ).tag(config=True)
extra_open_editor_shortcuts = Bool(False,
help="Enable vi (v) or Emacs (C-X C-E) shortcuts to open an external editor. "
"This is in addition to the F2 binding, which is always enabled."
).tag(config=True)
- @observe('term_title')
- def init_term_title(self, change=None):
- # Enable or disable the terminal title.
- if self.term_title:
- toggle_set_term_title(True)
- set_term_title('IPython: ' + abbrev_cwd())
- else:
- toggle_set_term_title(False)
-
- def init_display_formatter(self):
- super(TerminalInteractiveShell, self).init_display_formatter()
- # terminal only supports plain text
- self.display_formatter.active_types = ['text/plain']
+ @observe('term_title')
+ def init_term_title(self, change=None):
+ # Enable or disable the terminal title.
+ if self.term_title:
+ toggle_set_term_title(True)
+ set_term_title('IPython: ' + abbrev_cwd())
+ else:
+ toggle_set_term_title(False)
+
+ def init_display_formatter(self):
+ super(TerminalInteractiveShell, self).init_display_formatter()
+ # terminal only supports plain text
+ self.display_formatter.active_types = ['text/plain']
# disable `_ipython_display_`
self.display_formatter.ipython_display_formatter.enabled = False
- def init_prompt_toolkit_cli(self):
- if self.simple_prompt:
- # Fall back to plain non-interactive output for tests.
- # This is very limited, and only accepts a single line.
- def prompt():
+ def init_prompt_toolkit_cli(self):
+ if self.simple_prompt:
+ # Fall back to plain non-interactive output for tests.
+ # This is very limited, and only accepts a single line.
+ def prompt():
isp = self.input_splitter
prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
@@ -231,82 +231,82 @@ class TerminalInteractiveShell(InteractiveShell):
isp.push(line)
prompt_text = prompt_continuation
return isp.source_reset()
- self.prompt_for_code = prompt
- return
+ self.prompt_for_code = prompt
+ return
- # Set up keyboard shortcuts
+ # Set up keyboard shortcuts
kbmanager = KeyBindingManager.for_prompt(
enable_open_in_editor=self.extra_open_editor_shortcuts,
)
- register_ipython_shortcuts(kbmanager.registry, self)
-
- # Pre-populate history from IPython's history database
- history = InMemoryHistory()
- last_cell = u""
- for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
- include_latest=True):
- # Ignore blank lines and consecutive duplicates
- cell = cell.rstrip()
- if cell and (cell != last_cell):
- history.append(cell)
+ register_ipython_shortcuts(kbmanager.registry, self)
+
+ # Pre-populate history from IPython's history database
+ history = InMemoryHistory()
+ last_cell = u""
+ for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
+ include_latest=True):
+ # Ignore blank lines and consecutive duplicates
+ cell = cell.rstrip()
+ if cell and (cell != last_cell):
+ history.append(cell)
last_cell = cell
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
self.style = DynamicStyle(lambda: self._style)
- editing_mode = getattr(EditingMode, self.editing_mode.upper())
+ editing_mode = getattr(EditingMode, self.editing_mode.upper())
def patch_stdout(**kwargs):
return self.pt_cli.patch_stdout_context(**kwargs)
- self._pt_app = create_prompt_application(
- editing_mode=editing_mode,
- key_bindings_registry=kbmanager.registry,
- history=history,
+ self._pt_app = create_prompt_application(
+ editing_mode=editing_mode,
+ key_bindings_registry=kbmanager.registry,
+ history=history,
completer=IPythonPTCompleter(shell=self,
patch_stdout=patch_stdout),
- enable_history_search=True,
+ enable_history_search=True,
style=self.style,
- mouse_support=self.mouse_support,
- **self._layout_options()
- )
- self._eventloop = create_eventloop(self.inputhook)
- self.pt_cli = CommandLineInterface(
- self._pt_app, eventloop=self._eventloop,
- output=create_output(true_color=self.true_color))
+ mouse_support=self.mouse_support,
+ **self._layout_options()
+ )
+ self._eventloop = create_eventloop(self.inputhook)
+ self.pt_cli = CommandLineInterface(
+ self._pt_app, eventloop=self._eventloop,
+ output=create_output(true_color=self.true_color))
def _make_style_from_name_or_cls(self, name_or_cls):
- """
- Small wrapper that make an IPython compatible style from a style name
+ """
+ Small wrapper that make an IPython compatible style from a style name
We need that to add style for prompt ... etc.
"""
- style_overrides = {}
+ style_overrides = {}
if name_or_cls == 'legacy':
- legacy = self.colors.lower()
- if legacy == 'linux':
- style_cls = get_style_by_name('monokai')
- style_overrides = _style_overrides_linux
- elif legacy == 'lightbg':
- style_overrides = _style_overrides_light_bg
- style_cls = get_style_by_name('pastie')
- elif legacy == 'neutral':
- # The default theme needs to be visible on both a dark background
- # and a light background, because we can't tell what the terminal
- # looks like. These tweaks to the default theme help with that.
- style_cls = get_style_by_name('default')
- style_overrides.update({
- Token.Number: '#007700',
- Token.Operator: 'noinherit',
- Token.String: '#BB6622',
- Token.Name.Function: '#2080D0',
- Token.Name.Class: 'bold #2080D0',
- Token.Name.Namespace: 'bold #2080D0',
- Token.Prompt: '#009900',
- Token.PromptNum: '#00ff00 bold',
- Token.OutPrompt: '#990000',
- Token.OutPromptNum: '#ff0000 bold',
- })
+ legacy = self.colors.lower()
+ if legacy == 'linux':
+ style_cls = get_style_by_name('monokai')
+ style_overrides = _style_overrides_linux
+ elif legacy == 'lightbg':
+ style_overrides = _style_overrides_light_bg
+ style_cls = get_style_by_name('pastie')
+ elif legacy == 'neutral':
+ # The default theme needs to be visible on both a dark background
+ # and a light background, because we can't tell what the terminal
+ # looks like. These tweaks to the default theme help with that.
+ style_cls = get_style_by_name('default')
+ style_overrides.update({
+ Token.Number: '#007700',
+ Token.Operator: 'noinherit',
+ Token.String: '#BB6622',
+ Token.Name.Function: '#2080D0',
+ Token.Name.Class: 'bold #2080D0',
+ Token.Name.Namespace: 'bold #2080D0',
+ Token.Prompt: '#009900',
+ Token.PromptNum: '#00ff00 bold',
+ Token.OutPrompt: '#990000',
+ Token.OutPromptNum: '#ff0000 bold',
+ })
# Hack: Due to limited color support on the Windows console
# the prompt colors will be wrong without this
@@ -317,111 +317,111 @@ class TerminalInteractiveShell(InteractiveShell):
Token.OutPrompt: '#ansidarkred',
Token.OutPromptNum: '#ansired bold',
})
- elif legacy =='nocolor':
- style_cls=_NoStyle
- style_overrides = {}
- else :
- raise ValueError('Got unknown colors: ', legacy)
- else :
+ elif legacy =='nocolor':
+ style_cls=_NoStyle
+ style_overrides = {}
+ else :
+ raise ValueError('Got unknown colors: ', legacy)
+ else :
if isinstance(name_or_cls, string_types):
style_cls = get_style_by_name(name_or_cls)
else:
style_cls = name_or_cls
- style_overrides = {
- Token.Prompt: '#009900',
- Token.PromptNum: '#00ff00 bold',
- Token.OutPrompt: '#990000',
- Token.OutPromptNum: '#ff0000 bold',
- }
- style_overrides.update(self.highlighting_style_overrides)
- style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
- style_dict=style_overrides)
-
- return style
-
- def _layout_options(self):
+ style_overrides = {
+ Token.Prompt: '#009900',
+ Token.PromptNum: '#00ff00 bold',
+ Token.OutPrompt: '#990000',
+ Token.OutPromptNum: '#ff0000 bold',
+ }
+ style_overrides.update(self.highlighting_style_overrides)
+ style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
+ style_dict=style_overrides)
+
+ return style
+
+ def _layout_options(self):
+ """
+ Return the current layout option for the current Terminal InteractiveShell
+ """
+ return {
+ 'lexer':IPythonPTLexer(),
+ 'reserve_space_for_menu':self.space_for_menu,
+ 'get_prompt_tokens':self.prompts.in_prompt_tokens,
+ 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
+ 'multiline':True,
+ 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
+
+ # Highlight matching brackets, but only when this setting is
+ # enabled, and only when the DEFAULT_BUFFER has the focus.
+ 'extra_input_processors': [ConditionalProcessor(
+ processor=HighlightMatchingBracketProcessor(chars='[](){}'),
+ filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
+ Condition(lambda cli: self.highlight_matching_brackets))],
+ }
+
+ def _update_layout(self):
"""
- Return the current layout option for the current Terminal InteractiveShell
- """
- return {
- 'lexer':IPythonPTLexer(),
- 'reserve_space_for_menu':self.space_for_menu,
- 'get_prompt_tokens':self.prompts.in_prompt_tokens,
- 'get_continuation_tokens':self.prompts.continuation_prompt_tokens,
- 'multiline':True,
- 'display_completions_in_columns': (self.display_completions == 'multicolumn'),
-
- # Highlight matching brackets, but only when this setting is
- # enabled, and only when the DEFAULT_BUFFER has the focus.
- 'extra_input_processors': [ConditionalProcessor(
- processor=HighlightMatchingBracketProcessor(chars='[](){}'),
- filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() &
- Condition(lambda cli: self.highlight_matching_brackets))],
- }
-
- def _update_layout(self):
- """
- Ask for a re computation of the application layout, if for example ,
- some configuration options have changed.
- """
- if self._pt_app:
- self._pt_app.layout = create_prompt_layout(**self._layout_options())
-
- def prompt_for_code(self):
- document = self.pt_cli.run(
- pre_run=self.pre_prompt, reset_current_buffer=True)
- return document.text
-
- def enable_win_unicode_console(self):
+ Ask for a re computation of the application layout, if for example ,
+ some configuration options have changed.
+ """
+ if self._pt_app:
+ self._pt_app.layout = create_prompt_layout(**self._layout_options())
+
+ def prompt_for_code(self):
+ document = self.pt_cli.run(
+ pre_run=self.pre_prompt, reset_current_buffer=True)
+ return document.text
+
+ def enable_win_unicode_console(self):
if sys.version_info >= (3, 6):
# Since PEP 528, Python uses the unicode APIs for the Windows
# console by default, so WUC shouldn't be needed.
return
- import win_unicode_console
+ import win_unicode_console
- if PY3:
- win_unicode_console.enable()
+ if PY3:
+ win_unicode_console.enable()
else:
- # https://github.com/ipython/ipython/issues/9768
- from win_unicode_console.streams import (TextStreamWrapper,
- stdout_text_transcoded, stderr_text_transcoded)
+ # https://github.com/ipython/ipython/issues/9768
+ from win_unicode_console.streams import (TextStreamWrapper,
+ stdout_text_transcoded, stderr_text_transcoded)
- class LenientStrStreamWrapper(TextStreamWrapper):
- def write(self, s):
- if isinstance(s, bytes):
- s = s.decode(self.encoding, 'replace')
+ class LenientStrStreamWrapper(TextStreamWrapper):
+ def write(self, s):
+ if isinstance(s, bytes):
+ s = s.decode(self.encoding, 'replace')
- self.base.write(s)
+ self.base.write(s)
- stdout_text_str = LenientStrStreamWrapper(stdout_text_transcoded)
- stderr_text_str = LenientStrStreamWrapper(stderr_text_transcoded)
+ stdout_text_str = LenientStrStreamWrapper(stdout_text_transcoded)
+ stderr_text_str = LenientStrStreamWrapper(stderr_text_transcoded)
- win_unicode_console.enable(stdout=stdout_text_str,
- stderr=stderr_text_str)
+ win_unicode_console.enable(stdout=stdout_text_str,
+ stderr=stderr_text_str)
- def init_io(self):
- if sys.platform not in {'win32', 'cli'}:
- return
+ def init_io(self):
+ if sys.platform not in {'win32', 'cli'}:
+ return
- self.enable_win_unicode_console()
+ self.enable_win_unicode_console()
- import colorama
- colorama.init()
+ import colorama
+ colorama.init()
- # For some reason we make these wrappers around stdout/stderr.
- # For now, we need to reset them so all output gets coloured.
- # https://github.com/ipython/ipython/issues/8669
- # 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)
+ # For some reason we make these wrappers around stdout/stderr.
+ # For now, we need to reset them so all output gets coloured.
+ # https://github.com/ipython/ipython/issues/8669
+ # 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)
- def init_magics(self):
- super(TerminalInteractiveShell, self).init_magics()
- self.register_magics(TerminalMagics)
+ def init_magics(self):
+ super(TerminalInteractiveShell, self).init_magics()
+ self.register_magics(TerminalMagics)
def init_alias(self):
# The parent class defines aliases that can be safely used with any
@@ -432,25 +432,25 @@ class TerminalInteractiveShell(InteractiveShell):
# 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']:
- self.alias_manager.soft_define_alias(cmd, cmd)
+ for cmd in ['clear', 'more', 'less', 'man']:
+ self.alias_manager.soft_define_alias(cmd, cmd)
- def __init__(self, *args, **kwargs):
- super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
- self.init_prompt_toolkit_cli()
- self.init_term_title()
- self.keep_running = True
+ def __init__(self, *args, **kwargs):
+ super(TerminalInteractiveShell, self).__init__(*args, **kwargs)
+ self.init_prompt_toolkit_cli()
+ self.init_term_title()
+ self.keep_running = True
- self.debugger_history = InMemoryHistory()
+ self.debugger_history = InMemoryHistory()
- def ask_exit(self):
- self.keep_running = False
+ def ask_exit(self):
+ self.keep_running = False
- rl_next_input = None
+ rl_next_input = None
- def pre_prompt(self):
- if self.rl_next_input:
+ def pre_prompt(self):
+ if self.rl_next_input:
# We can't set the buffer here, because it will be reset just after
# this. Adding a callable to pre_run_callables does what we need
# after the buffer is reset.
@@ -463,37 +463,37 @@ class TerminalInteractiveShell(InteractiveShell):
# Older version of prompt_toolkit; it's OK to set the document
# directly here.
set_doc()
- self.rl_next_input = None
+ self.rl_next_input = None
- def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
+ def interact(self, display_banner=DISPLAY_BANNER_DEPRECATED):
- if display_banner is not DISPLAY_BANNER_DEPRECATED:
- warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
+ if display_banner is not DISPLAY_BANNER_DEPRECATED:
+ warn('interact `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
- self.keep_running = True
- while self.keep_running:
- print(self.separate_in, end='')
+ self.keep_running = True
+ while self.keep_running:
+ print(self.separate_in, end='')
try:
- code = self.prompt_for_code()
- except EOFError:
- if (not self.confirm_exit) \
- or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
- self.ask_exit()
+ code = self.prompt_for_code()
+ except EOFError:
+ if (not self.confirm_exit) \
+ or self.ask_yes_no('Do you really want to exit ([y]/n)?','y','n'):
+ self.ask_exit()
else:
- if code:
- self.run_cell(code, store_history=True)
-
- def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
- # An extra layer of protection in case someone mashing Ctrl-C breaks
- # out of our internal code.
- if display_banner is not DISPLAY_BANNER_DEPRECATED:
- warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
- while True:
+ if code:
+ self.run_cell(code, store_history=True)
+
+ def mainloop(self, display_banner=DISPLAY_BANNER_DEPRECATED):
+ # An extra layer of protection in case someone mashing Ctrl-C breaks
+ # out of our internal code.
+ if display_banner is not DISPLAY_BANNER_DEPRECATED:
+ warn('mainloop `display_banner` argument is deprecated since IPython 5.0. Call `show_banner()` if needed.', DeprecationWarning, stacklevel=2)
+ while True:
try:
- self.interact()
- break
+ self.interact()
+ break
except KeyboardInterrupt as e:
print("\n%s escaped interact()\n" % type(e).__name__)
finally:
@@ -504,49 +504,49 @@ class TerminalInteractiveShell(InteractiveShell):
if hasattr(self, '_eventloop'):
self._eventloop.stop()
- _inputhook = None
- def inputhook(self, context):
- if self._inputhook is not None:
- self._inputhook(context)
+ _inputhook = None
+ def inputhook(self, context):
+ if self._inputhook is not None:
+ self._inputhook(context)
active_eventloop = None
- def enable_gui(self, gui=None):
- if gui:
+ def enable_gui(self, gui=None):
+ if gui:
self.active_eventloop, self._inputhook =\
get_inputhook_name_and_func(gui)
- else:
+ else:
self.active_eventloop = self._inputhook = None
- # Run !system commands directly, not through pipes, so terminal programs
- # work correctly.
- system = InteractiveShell.system_raw
+ # Run !system commands directly, not through pipes, so terminal programs
+ # work correctly.
+ system = InteractiveShell.system_raw
- def auto_rewrite_input(self, cmd):
- """Overridden from the parent class to use fancy rewriting prompt"""
- if not self.show_rewritten_input:
- return
+ def auto_rewrite_input(self, cmd):
+ """Overridden from the parent class to use fancy rewriting prompt"""
+ if not self.show_rewritten_input:
+ return
- tokens = self.prompts.rewrite_prompt_tokens()
- if self.pt_cli:
- self.pt_cli.print_tokens(tokens)
- print(cmd)
+ tokens = self.prompts.rewrite_prompt_tokens()
+ if self.pt_cli:
+ self.pt_cli.print_tokens(tokens)
+ print(cmd)
else:
- prompt = ''.join(s for t, s in tokens)
- print(prompt, cmd, sep='')
+ prompt = ''.join(s for t, s in tokens)
+ print(prompt, cmd, sep='')
- _prompts_before = None
- def switch_doctest_mode(self, mode):
- """Switch prompts to classic for %doctest_mode"""
- if mode:
- self._prompts_before = self.prompts
- self.prompts = ClassicPrompts(self)
- elif self._prompts_before:
- self.prompts = self._prompts_before
- self._prompts_before = None
- self._update_layout()
+ _prompts_before = None
+ def switch_doctest_mode(self, mode):
+ """Switch prompts to classic for %doctest_mode"""
+ if mode:
+ self._prompts_before = self.prompts
+ self.prompts = ClassicPrompts(self)
+ elif self._prompts_before:
+ self.prompts = self._prompts_before
+ self._prompts_before = None
+ self._update_layout()
-InteractiveShellABC.register(TerminalInteractiveShell)
+InteractiveShellABC.register(TerminalInteractiveShell)
-if __name__ == '__main__':
- TerminalInteractiveShell.instance().interact()
+if __name__ == '__main__':
+ TerminalInteractiveShell.instance().interact()
diff --git a/contrib/python/ipython/py2/IPython/terminal/ipapp.py b/contrib/python/ipython/py2/IPython/terminal/ipapp.py
index 6b25aaa3e3..a1181c1b0b 100755
--- a/contrib/python/ipython/py2/IPython/terminal/ipapp.py
+++ b/contrib/python/ipython/py2/IPython/terminal/ipapp.py
@@ -14,7 +14,7 @@ from __future__ import print_function
import logging
import os
import sys
-import warnings
+import warnings
from traitlets.config.loader import Config
from traitlets.config.application import boolean_flag, catch_config_error, Application
@@ -32,7 +32,7 @@ from IPython.core.shellapp import (
InteractiveShellApp, shell_flags, shell_aliases
)
from IPython.extensions.storemagic import StoreMagics
-from .interactiveshell import TerminalInteractiveShell
+from .interactiveshell import TerminalInteractiveShell
from IPython.paths import get_ipython_dir
from traitlets import (
Bool, List, Dict, default, observe, Type
@@ -101,11 +101,11 @@ addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax',
'Turn on auto editing of files with syntax errors.',
'Turn off auto editing of files with syntax errors.'
)
-addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
- "Force simple minimal prompt using `raw_input`",
- "Use a rich interactive prompt with prompt_toolkit",
-)
-
+addflag('simple-prompt', 'TerminalInteractiveShell.simple_prompt',
+ "Force simple minimal prompt using `raw_input`",
+ "Use a rich interactive prompt with prompt_toolkit",
+)
+
addflag('banner', 'TerminalIPythonApp.display_banner',
"Display a banner upon starting IPython.",
"Don't display a banner upon starting IPython."
@@ -123,7 +123,7 @@ addflag('term-title', 'TerminalInteractiveShell.term_title',
classic_config = Config()
classic_config.InteractiveShell.cache_size = 0
classic_config.PlainTextFormatter.pprint = False
-classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
+classic_config.TerminalInteractiveShell.prompts_class='IPython.terminal.prompts.ClassicPrompts'
classic_config.InteractiveShell.separate_in = ''
classic_config.InteractiveShell.separate_out = ''
classic_config.InteractiveShell.separate_out2 = ''
@@ -192,7 +192,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
help="Class to use to instantiate the TerminalInteractiveShell object. Useful for custom Frontends"
).tag(config=True)
- @default('classes')
+ @default('classes')
def _classes_default(self):
"""This has to be in a method, for TerminalIPythonApp to be available."""
return [
@@ -250,33 +250,33 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
# *do* autocreate requested profile, but don't create the config file.
auto_create=Bool(True)
# configurables
- quick = Bool(False,
+ quick = Bool(False,
help="""Start IPython quickly by skipping the loading of config files."""
- ).tag(config=True)
- @observe('quick')
- def _quick_changed(self, change):
- if change['new']:
+ ).tag(config=True)
+ @observe('quick')
+ def _quick_changed(self, change):
+ if change['new']:
self.load_config_file = lambda *a, **kw: None
- display_banner = Bool(True,
+ display_banner = Bool(True,
help="Whether to display a banner upon starting IPython."
- ).tag(config=True)
+ ).tag(config=True)
# if there is code of files to run from the cmd line, don't interact
# unless the --i flag (App.force_interact) is true.
- force_interact = Bool(False,
+ force_interact = Bool(False,
help="""If a command or file is given via the command-line,
e.g. 'ipython foo.py', start an interactive shell after executing the
file or command."""
- ).tag(config=True)
- @observe('force_interact')
- def _force_interact_changed(self, change):
- if change['new']:
+ ).tag(config=True)
+ @observe('force_interact')
+ def _force_interact_changed(self, change):
+ if change['new']:
self.interact = True
- @observe('file_to_run', 'code_to_run', 'module_to_run')
- def _file_to_run_changed(self, change):
- new = change['new']
+ @observe('file_to_run', 'code_to_run', 'module_to_run')
+ def _file_to_run_changed(self, change):
+ new = change['new']
if new:
self.something_to_run = True
if new and not self.force_interact:
@@ -295,7 +295,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
# warn and transform into current syntax
argv = argv[:] # copy, don't clobber
idx = argv.index('-pylab')
- warnings.warn("`-pylab` flag has been deprecated.\n"
+ warnings.warn("`-pylab` flag has been deprecated.\n"
" Use `--matplotlib <backend>` and import pylab manually.")
argv[idx] = '--pylab'
@@ -328,7 +328,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
# based app, because we call shell.show_banner() by hand below
# so the banner shows *before* all extension loading stuff.
self.shell = self.interactive_shell_class.instance(parent=self,
- profile_dir=self.profile_dir,
+ profile_dir=self.profile_dir,
ipython_dir=self.ipython_dir, user_ns=self.user_ns)
self.shell.configurables.append(self)
@@ -342,7 +342,7 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp):
def _pylab_changed(self, name, old, new):
"""Replace --pylab='inline' with --pylab='auto'"""
if new == 'inline':
- warnings.warn("'inline' not available as pylab backend, "
+ warnings.warn("'inline' not available as pylab backend, "
"using 'auto' instead.")
self.pylab = 'auto'
diff --git a/contrib/python/ipython/py2/IPython/terminal/magics.py b/contrib/python/ipython/py2/IPython/terminal/magics.py
index 3a844a0397..60f465b0dc 100644
--- a/contrib/python/ipython/py2/IPython/terminal/magics.py
+++ b/contrib/python/ipython/py2/IPython/terminal/magics.py
@@ -1,208 +1,208 @@
-"""Extra magics for terminal use."""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-from __future__ import print_function
-
-from logging import error
-import os
-import sys
-
-from IPython.core.error import TryNext, UsageError
-from IPython.core.inputsplitter import IPythonInputSplitter
-from IPython.core.magic import Magics, magics_class, line_magic
-from IPython.lib.clipboard import ClipboardEmpty
-from IPython.utils.text import SList, strip_email_quotes
-from IPython.utils import py3compat
-
-def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
- """ Yield pasted lines until the user enters the given sentinel value.
- """
- if not quiet:
- print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
- % sentinel)
- prompt = ":"
- else:
- prompt = ""
- while True:
- try:
- l = py3compat.str_to_unicode(l_input(prompt))
- if l == sentinel:
- return
- else:
- yield l
- except EOFError:
- print('<EOF>')
- return
-
-
-@magics_class
-class TerminalMagics(Magics):
- def __init__(self, shell):
- super(TerminalMagics, self).__init__(shell)
- self.input_splitter = IPythonInputSplitter()
-
- def store_or_execute(self, block, name):
- """ Execute a block, or store it in a variable, per the user's request.
- """
- if name:
- # If storing it for further editing
- self.shell.user_ns[name] = SList(block.splitlines())
- print("Block assigned to '%s'" % name)
- else:
- b = self.preclean_input(block)
- self.shell.user_ns['pasted_block'] = b
- self.shell.using_paste_magics = True
- try:
- self.shell.run_cell(b)
- finally:
- self.shell.using_paste_magics = False
-
- def preclean_input(self, block):
- lines = block.splitlines()
- while lines and not lines[0].strip():
- lines = lines[1:]
- return strip_email_quotes('\n'.join(lines))
-
- def rerun_pasted(self, name='pasted_block'):
- """ Rerun a previously pasted command.
- """
- b = self.shell.user_ns.get(name)
-
- # Sanity checks
- if b is None:
- raise UsageError('No previous pasted block available')
- if not isinstance(b, py3compat.string_types):
- raise UsageError(
- "Variable 'pasted_block' is not a string, can't execute")
-
- print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
- self.shell.run_cell(b)
-
- @line_magic
- def autoindent(self, parameter_s = ''):
+"""Extra magics for terminal use."""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+from __future__ import print_function
+
+from logging import error
+import os
+import sys
+
+from IPython.core.error import TryNext, UsageError
+from IPython.core.inputsplitter import IPythonInputSplitter
+from IPython.core.magic import Magics, magics_class, line_magic
+from IPython.lib.clipboard import ClipboardEmpty
+from IPython.utils.text import SList, strip_email_quotes
+from IPython.utils import py3compat
+
+def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False):
+ """ Yield pasted lines until the user enters the given sentinel value.
+ """
+ if not quiet:
+ print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
+ % sentinel)
+ prompt = ":"
+ else:
+ prompt = ""
+ while True:
+ try:
+ l = py3compat.str_to_unicode(l_input(prompt))
+ if l == sentinel:
+ return
+ else:
+ yield l
+ except EOFError:
+ print('<EOF>')
+ return
+
+
+@magics_class
+class TerminalMagics(Magics):
+ def __init__(self, shell):
+ super(TerminalMagics, self).__init__(shell)
+ self.input_splitter = IPythonInputSplitter()
+
+ def store_or_execute(self, block, name):
+ """ Execute a block, or store it in a variable, per the user's request.
+ """
+ if name:
+ # If storing it for further editing
+ self.shell.user_ns[name] = SList(block.splitlines())
+ print("Block assigned to '%s'" % name)
+ else:
+ b = self.preclean_input(block)
+ self.shell.user_ns['pasted_block'] = b
+ self.shell.using_paste_magics = True
+ try:
+ self.shell.run_cell(b)
+ finally:
+ self.shell.using_paste_magics = False
+
+ def preclean_input(self, block):
+ lines = block.splitlines()
+ while lines and not lines[0].strip():
+ lines = lines[1:]
+ return strip_email_quotes('\n'.join(lines))
+
+ def rerun_pasted(self, name='pasted_block'):
+ """ Rerun a previously pasted command.
+ """
+ b = self.shell.user_ns.get(name)
+
+ # Sanity checks
+ if b is None:
+ raise UsageError('No previous pasted block available')
+ if not isinstance(b, py3compat.string_types):
+ raise UsageError(
+ "Variable 'pasted_block' is not a string, can't execute")
+
+ print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)))
+ self.shell.run_cell(b)
+
+ @line_magic
+ def autoindent(self, parameter_s = ''):
"""Toggle autoindent on/off (deprecated)"""
print("%autoindent is deprecated since IPython 5: you can now paste "
"multiple lines without turning autoindentation off.")
- self.shell.set_autoindent()
- print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
-
- @line_magic
- def cpaste(self, parameter_s=''):
- """Paste & execute a pre-formatted code block from clipboard.
-
- You must terminate the block with '--' (two minus-signs) or Ctrl-D
- alone on the line. You can also provide your own sentinel with '%paste
- -s %%' ('%%' is the new sentinel for this operation).
-
- The block is dedented prior to execution to enable execution of method
- definitions. '>' and '+' characters at the beginning of a line are
- ignored, to allow pasting directly from e-mails, diff files and
- doctests (the '...' continuation prompt is also stripped). The
- executed block is also assigned to variable named 'pasted_block' for
- later editing with '%edit pasted_block'.
-
- You can also pass a variable name as an argument, e.g. '%cpaste foo'.
- This assigns the pasted block to variable 'foo' as string, without
- dedenting or executing it (preceding >>> and + is still stripped)
-
- '%cpaste -r' re-executes the block previously entered by cpaste.
- '%cpaste -q' suppresses any additional output messages.
-
- Do not be alarmed by garbled output on Windows (it's a readline bug).
- Just press enter and type -- (and press enter again) and the block
- will be what was just pasted.
-
- IPython statements (magics, shell escapes) are not supported (yet).
-
- See also
- --------
- paste: automatically pull code from clipboard.
-
- Examples
- --------
- ::
-
- In [8]: %cpaste
- Pasting code; enter '--' alone on the line to stop.
- :>>> a = ["world!", "Hello"]
- :>>> print " ".join(sorted(a))
- :--
- Hello world!
- """
- opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
- if 'r' in opts:
- self.rerun_pasted()
- return
-
- quiet = ('q' in opts)
-
- sentinel = opts.get('s', u'--')
- block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
- self.store_or_execute(block, name)
-
- @line_magic
- def paste(self, parameter_s=''):
- """Paste & execute a pre-formatted code block from clipboard.
-
- The text is pulled directly from the clipboard without user
- intervention and printed back on the screen before execution (unless
- the -q flag is given to force quiet mode).
-
- The block is dedented prior to execution to enable execution of method
- definitions. '>' and '+' characters at the beginning of a line are
- ignored, to allow pasting directly from e-mails, diff files and
- doctests (the '...' continuation prompt is also stripped). The
- executed block is also assigned to variable named 'pasted_block' for
- later editing with '%edit pasted_block'.
-
- You can also pass a variable name as an argument, e.g. '%paste foo'.
- This assigns the pasted block to variable 'foo' as string, without
- executing it (preceding >>> and + is still stripped).
-
- Options:
-
- -r: re-executes the block previously entered by cpaste.
-
- -q: quiet mode: do not echo the pasted text back to the terminal.
-
- IPython statements (magics, shell escapes) are not supported (yet).
-
- See also
- --------
- cpaste: manually paste code into terminal until you mark its end.
- """
- opts, name = self.parse_options(parameter_s, 'rq', mode='string')
- if 'r' in opts:
- self.rerun_pasted()
- return
- try:
- block = self.shell.hooks.clipboard_get()
- except TryNext as clipboard_exc:
- message = getattr(clipboard_exc, 'args')
- if message:
- error(message[0])
- else:
- error('Could not get text from the clipboard.')
- return
- except ClipboardEmpty:
- raise UsageError("The clipboard appears to be empty")
-
- # By default, echo back to terminal unless quiet mode is requested
- if 'q' not in opts:
- write = self.shell.write
- write(self.shell.pycolorize(block))
- if not block.endswith('\n'):
- write('\n')
- write("## -- End pasted text --\n")
-
- self.store_or_execute(block, name)
-
- # Class-level: add a '%cls' magic only on Windows
- if sys.platform == 'win32':
- @line_magic
- def cls(self, s):
- """Clear screen.
- """
- os.system("cls")
+ self.shell.set_autoindent()
+ print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
+
+ @line_magic
+ def cpaste(self, parameter_s=''):
+ """Paste & execute a pre-formatted code block from clipboard.
+
+ You must terminate the block with '--' (two minus-signs) or Ctrl-D
+ alone on the line. You can also provide your own sentinel with '%paste
+ -s %%' ('%%' is the new sentinel for this operation).
+
+ The block is dedented prior to execution to enable execution of method
+ definitions. '>' and '+' characters at the beginning of a line are
+ ignored, to allow pasting directly from e-mails, diff files and
+ doctests (the '...' continuation prompt is also stripped). The
+ executed block is also assigned to variable named 'pasted_block' for
+ later editing with '%edit pasted_block'.
+
+ You can also pass a variable name as an argument, e.g. '%cpaste foo'.
+ This assigns the pasted block to variable 'foo' as string, without
+ dedenting or executing it (preceding >>> and + is still stripped)
+
+ '%cpaste -r' re-executes the block previously entered by cpaste.
+ '%cpaste -q' suppresses any additional output messages.
+
+ Do not be alarmed by garbled output on Windows (it's a readline bug).
+ Just press enter and type -- (and press enter again) and the block
+ will be what was just pasted.
+
+ IPython statements (magics, shell escapes) are not supported (yet).
+
+ See also
+ --------
+ paste: automatically pull code from clipboard.
+
+ Examples
+ --------
+ ::
+
+ In [8]: %cpaste
+ Pasting code; enter '--' alone on the line to stop.
+ :>>> a = ["world!", "Hello"]
+ :>>> print " ".join(sorted(a))
+ :--
+ Hello world!
+ """
+ opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
+ if 'r' in opts:
+ self.rerun_pasted()
+ return
+
+ quiet = ('q' in opts)
+
+ sentinel = opts.get('s', u'--')
+ block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
+ self.store_or_execute(block, name)
+
+ @line_magic
+ def paste(self, parameter_s=''):
+ """Paste & execute a pre-formatted code block from clipboard.
+
+ The text is pulled directly from the clipboard without user
+ intervention and printed back on the screen before execution (unless
+ the -q flag is given to force quiet mode).
+
+ The block is dedented prior to execution to enable execution of method
+ definitions. '>' and '+' characters at the beginning of a line are
+ ignored, to allow pasting directly from e-mails, diff files and
+ doctests (the '...' continuation prompt is also stripped). The
+ executed block is also assigned to variable named 'pasted_block' for
+ later editing with '%edit pasted_block'.
+
+ You can also pass a variable name as an argument, e.g. '%paste foo'.
+ This assigns the pasted block to variable 'foo' as string, without
+ executing it (preceding >>> and + is still stripped).
+
+ Options:
+
+ -r: re-executes the block previously entered by cpaste.
+
+ -q: quiet mode: do not echo the pasted text back to the terminal.
+
+ IPython statements (magics, shell escapes) are not supported (yet).
+
+ See also
+ --------
+ cpaste: manually paste code into terminal until you mark its end.
+ """
+ opts, name = self.parse_options(parameter_s, 'rq', mode='string')
+ if 'r' in opts:
+ self.rerun_pasted()
+ return
+ try:
+ block = self.shell.hooks.clipboard_get()
+ except TryNext as clipboard_exc:
+ message = getattr(clipboard_exc, 'args')
+ if message:
+ error(message[0])
+ else:
+ error('Could not get text from the clipboard.')
+ return
+ except ClipboardEmpty:
+ raise UsageError("The clipboard appears to be empty")
+
+ # By default, echo back to terminal unless quiet mode is requested
+ if 'q' not in opts:
+ write = self.shell.write
+ write(self.shell.pycolorize(block))
+ if not block.endswith('\n'):
+ write('\n')
+ write("## -- End pasted text --\n")
+
+ self.store_or_execute(block, name)
+
+ # Class-level: add a '%cls' magic only on Windows
+ if sys.platform == 'win32':
+ @line_magic
+ def cls(self, s):
+ """Clear screen.
+ """
+ os.system("cls")
diff --git a/contrib/python/ipython/py2/IPython/terminal/prompts.py b/contrib/python/ipython/py2/IPython/terminal/prompts.py
index 43c2170503..a2203fe417 100644
--- a/contrib/python/ipython/py2/IPython/terminal/prompts.py
+++ b/contrib/python/ipython/py2/IPython/terminal/prompts.py
@@ -1,80 +1,80 @@
-"""Terminal input and output prompts."""
-from __future__ import print_function
-
-from pygments.token import Token
-import sys
-
-from IPython.core.displayhook import DisplayHook
-
-from prompt_toolkit.layout.utils import token_list_width
-
-class Prompts(object):
- def __init__(self, shell):
- self.shell = shell
-
- def in_prompt_tokens(self, cli=None):
- return [
- (Token.Prompt, 'In ['),
- (Token.PromptNum, str(self.shell.execution_count)),
- (Token.Prompt, ']: '),
- ]
-
- def _width(self):
- return token_list_width(self.in_prompt_tokens())
-
- def continuation_prompt_tokens(self, cli=None, width=None):
- if width is None:
- width = self._width()
- return [
- (Token.Prompt, (' ' * (width - 5)) + '...: '),
- ]
-
- def rewrite_prompt_tokens(self):
- width = self._width()
- return [
- (Token.Prompt, ('-' * (width - 2)) + '> '),
- ]
-
- def out_prompt_tokens(self):
- return [
- (Token.OutPrompt, 'Out['),
- (Token.OutPromptNum, str(self.shell.execution_count)),
- (Token.OutPrompt, ']: '),
- ]
-
-class ClassicPrompts(Prompts):
- def in_prompt_tokens(self, cli=None):
- return [
- (Token.Prompt, '>>> '),
- ]
-
- def continuation_prompt_tokens(self, cli=None, width=None):
- return [
- (Token.Prompt, '... ')
- ]
-
- def rewrite_prompt_tokens(self):
- return []
-
- def out_prompt_tokens(self):
- return []
-
-class RichPromptDisplayHook(DisplayHook):
- """Subclass of base display hook using coloured prompt"""
- def write_output_prompt(self):
- sys.stdout.write(self.shell.separate_out)
+"""Terminal input and output prompts."""
+from __future__ import print_function
+
+from pygments.token import Token
+import sys
+
+from IPython.core.displayhook import DisplayHook
+
+from prompt_toolkit.layout.utils import token_list_width
+
+class Prompts(object):
+ def __init__(self, shell):
+ self.shell = shell
+
+ def in_prompt_tokens(self, cli=None):
+ return [
+ (Token.Prompt, 'In ['),
+ (Token.PromptNum, str(self.shell.execution_count)),
+ (Token.Prompt, ']: '),
+ ]
+
+ def _width(self):
+ return token_list_width(self.in_prompt_tokens())
+
+ def continuation_prompt_tokens(self, cli=None, width=None):
+ if width is None:
+ width = self._width()
+ return [
+ (Token.Prompt, (' ' * (width - 5)) + '...: '),
+ ]
+
+ def rewrite_prompt_tokens(self):
+ width = self._width()
+ return [
+ (Token.Prompt, ('-' * (width - 2)) + '> '),
+ ]
+
+ def out_prompt_tokens(self):
+ return [
+ (Token.OutPrompt, 'Out['),
+ (Token.OutPromptNum, str(self.shell.execution_count)),
+ (Token.OutPrompt, ']: '),
+ ]
+
+class ClassicPrompts(Prompts):
+ def in_prompt_tokens(self, cli=None):
+ return [
+ (Token.Prompt, '>>> '),
+ ]
+
+ def continuation_prompt_tokens(self, cli=None, width=None):
+ return [
+ (Token.Prompt, '... ')
+ ]
+
+ def rewrite_prompt_tokens(self):
+ return []
+
+ def out_prompt_tokens(self):
+ return []
+
+class RichPromptDisplayHook(DisplayHook):
+ """Subclass of base display hook using coloured prompt"""
+ def write_output_prompt(self):
+ sys.stdout.write(self.shell.separate_out)
# If we're not displaying a prompt, it effectively ends with a newline,
# because the output will be left-aligned.
self.prompt_end_newline = True
- if self.do_full_cache:
- tokens = self.shell.prompts.out_prompt_tokens()
+ if self.do_full_cache:
+ tokens = self.shell.prompts.out_prompt_tokens()
prompt_txt = ''.join(s for t, s in tokens)
if prompt_txt and not prompt_txt.endswith('\n'):
# Ask for a newline before multiline output
self.prompt_end_newline = False
- if self.shell.pt_cli:
- self.shell.pt_cli.print_tokens(tokens)
- else:
+ if self.shell.pt_cli:
+ self.shell.pt_cli.print_tokens(tokens)
+ else:
sys.stdout.write(prompt_txt)
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py
index 3766973e82..95fdad0b59 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/__init__.py
@@ -1,49 +1,49 @@
-import importlib
-import os
-
-aliases = {
- 'qt4': 'qt',
- 'gtk2': 'gtk',
-}
-
-backends = [
- 'qt', 'qt4', 'qt5',
- 'gtk', 'gtk2', 'gtk3',
- 'tk',
- 'wx',
- 'pyglet', 'glut',
- 'osx',
-]
-
-registered = {}
-
-def register(name, inputhook):
- """Register the function *inputhook* as an event loop integration."""
- registered[name] = inputhook
-
-class UnknownBackend(KeyError):
- def __init__(self, name):
- self.name = name
-
- def __str__(self):
- return ("No event loop integration for {!r}. "
- "Supported event loops are: {}").format(self.name,
- ', '.join(backends + sorted(registered)))
-
+import importlib
+import os
+
+aliases = {
+ 'qt4': 'qt',
+ 'gtk2': 'gtk',
+}
+
+backends = [
+ 'qt', 'qt4', 'qt5',
+ 'gtk', 'gtk2', 'gtk3',
+ 'tk',
+ 'wx',
+ 'pyglet', 'glut',
+ 'osx',
+]
+
+registered = {}
+
+def register(name, inputhook):
+ """Register the function *inputhook* as an event loop integration."""
+ registered[name] = inputhook
+
+class UnknownBackend(KeyError):
+ def __init__(self, name):
+ self.name = name
+
+ def __str__(self):
+ return ("No event loop integration for {!r}. "
+ "Supported event loops are: {}").format(self.name,
+ ', '.join(backends + sorted(registered)))
+
def get_inputhook_name_and_func(gui):
- if gui in registered:
+ if gui in registered:
return gui, registered[gui]
-
- if gui not in backends:
- raise UnknownBackend(gui)
-
- if gui in aliases:
+
+ if gui not in backends:
+ raise UnknownBackend(gui)
+
+ if gui in aliases:
return get_inputhook_name_and_func(aliases[gui])
-
+
gui_mod = gui
- if gui == 'qt5':
- os.environ['QT_API'] = 'pyqt5'
+ if gui == 'qt5':
+ os.environ['QT_API'] = 'pyqt5'
gui_mod = 'qt'
-
+
mod = importlib.import_module('IPython.terminal.pt_inputhooks.'+gui_mod)
return gui, mod.inputhook
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py
index f336e6830f..d6b1387649 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/glut.py
@@ -1,141 +1,141 @@
-"""GLUT Input hook for interactive use with prompt_toolkit
-"""
-from __future__ import print_function
-
-
-# GLUT is quite an old library and it is difficult to ensure proper
-# integration within IPython since original GLUT does not allow to handle
-# events one by one. Instead, it requires for the mainloop to be entered
-# and never returned (there is not even a function to exit he
-# mainloop). Fortunately, there are alternatives such as freeglut
-# (available for linux and windows) and the OSX implementation gives
-# access to a glutCheckLoop() function that blocks itself until a new
-# event is received. This means we have to setup the idle callback to
-# ensure we got at least one event that will unblock the function.
-#
-# Furthermore, it is not possible to install these handlers without a window
-# being first created. We choose to make this window invisible. This means that
-# display mode options are set at this level and user won't be able to change
-# them later without modifying the code. This should probably be made available
-# via IPython options system.
-
-import sys
-import time
-import signal
-import OpenGL.GLUT as glut
-import OpenGL.platform as platform
-from timeit import default_timer as clock
-
-# Frame per second : 60
-# Should probably be an IPython option
-glut_fps = 60
-
-# Display mode : double buffeed + rgba + depth
-# Should probably be an IPython option
-glut_display_mode = (glut.GLUT_DOUBLE |
- glut.GLUT_RGBA |
- glut.GLUT_DEPTH)
-
-glutMainLoopEvent = None
-if sys.platform == 'darwin':
- try:
- glutCheckLoop = platform.createBaseFunction(
- 'glutCheckLoop', dll=platform.GLUT, resultType=None,
- argTypes=[],
- doc='glutCheckLoop( ) -> None',
- argNames=(),
- )
- except AttributeError:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions'''
- '''Consider installing freeglut.''')
- glutMainLoopEvent = glutCheckLoop
-elif glut.HAVE_FREEGLUT:
- glutMainLoopEvent = glut.glutMainLoopEvent
-else:
- raise RuntimeError(
- '''Your glut implementation does not allow interactive sessions. '''
- '''Consider installing freeglut.''')
-
-
-def glut_display():
- # Dummy display function
- pass
-
-def glut_idle():
- # Dummy idle function
- pass
-
-def glut_close():
- # Close function only hides the current window
- glut.glutHideWindow()
- glutMainLoopEvent()
-
-def glut_int_handler(signum, frame):
- # Catch sigint and print the defaultipyt message
- signal.signal(signal.SIGINT, signal.default_int_handler)
- print('\nKeyboardInterrupt')
- # Need to reprint the prompt at this stage
-
-# Initialisation code
-glut.glutInit( sys.argv )
-glut.glutInitDisplayMode( glut_display_mode )
-# This is specific to freeglut
-if bool(glut.glutSetOption):
- glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
- glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
-glut.glutCreateWindow( b'ipython' )
-glut.glutReshapeWindow( 1, 1 )
-glut.glutHideWindow( )
-glut.glutWMCloseFunc( glut_close )
-glut.glutDisplayFunc( glut_display )
-glut.glutIdleFunc( glut_idle )
-
-
-def inputhook(context):
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
-
- signal.signal(signal.SIGINT, glut_int_handler)
-
- try:
- t = clock()
-
- # Make sure the default window is set after a window has been closed
- if glut.glutGetWindow() == 0:
- glut.glutSetWindow( 1 )
- glutMainLoopEvent()
- return 0
-
- while not context.input_is_ready():
- glutMainLoopEvent()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
+"""GLUT Input hook for interactive use with prompt_toolkit
+"""
+from __future__ import print_function
+
+
+# GLUT is quite an old library and it is difficult to ensure proper
+# integration within IPython since original GLUT does not allow to handle
+# events one by one. Instead, it requires for the mainloop to be entered
+# and never returned (there is not even a function to exit he
+# mainloop). Fortunately, there are alternatives such as freeglut
+# (available for linux and windows) and the OSX implementation gives
+# access to a glutCheckLoop() function that blocks itself until a new
+# event is received. This means we have to setup the idle callback to
+# ensure we got at least one event that will unblock the function.
+#
+# Furthermore, it is not possible to install these handlers without a window
+# being first created. We choose to make this window invisible. This means that
+# display mode options are set at this level and user won't be able to change
+# them later without modifying the code. This should probably be made available
+# via IPython options system.
+
+import sys
+import time
+import signal
+import OpenGL.GLUT as glut
+import OpenGL.platform as platform
+from timeit import default_timer as clock
+
+# Frame per second : 60
+# Should probably be an IPython option
+glut_fps = 60
+
+# Display mode : double buffeed + rgba + depth
+# Should probably be an IPython option
+glut_display_mode = (glut.GLUT_DOUBLE |
+ glut.GLUT_RGBA |
+ glut.GLUT_DEPTH)
+
+glutMainLoopEvent = None
+if sys.platform == 'darwin':
+ try:
+ glutCheckLoop = platform.createBaseFunction(
+ 'glutCheckLoop', dll=platform.GLUT, resultType=None,
+ argTypes=[],
+ doc='glutCheckLoop( ) -> None',
+ argNames=(),
+ )
+ except AttributeError:
+ raise RuntimeError(
+ '''Your glut implementation does not allow interactive sessions'''
+ '''Consider installing freeglut.''')
+ glutMainLoopEvent = glutCheckLoop
+elif glut.HAVE_FREEGLUT:
+ glutMainLoopEvent = glut.glutMainLoopEvent
+else:
+ raise RuntimeError(
+ '''Your glut implementation does not allow interactive sessions. '''
+ '''Consider installing freeglut.''')
+
+
+def glut_display():
+ # Dummy display function
+ pass
+
+def glut_idle():
+ # Dummy idle function
+ pass
+
+def glut_close():
+ # Close function only hides the current window
+ glut.glutHideWindow()
+ glutMainLoopEvent()
+
+def glut_int_handler(signum, frame):
+ # Catch sigint and print the defaultipyt message
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+ print('\nKeyboardInterrupt')
+ # Need to reprint the prompt at this stage
+
+# Initialisation code
+glut.glutInit( sys.argv )
+glut.glutInitDisplayMode( glut_display_mode )
+# This is specific to freeglut
+if bool(glut.glutSetOption):
+ glut.glutSetOption( glut.GLUT_ACTION_ON_WINDOW_CLOSE,
+ glut.GLUT_ACTION_GLUTMAINLOOP_RETURNS )
+glut.glutCreateWindow( b'ipython' )
+glut.glutReshapeWindow( 1, 1 )
+glut.glutHideWindow( )
+glut.glutWMCloseFunc( glut_close )
+glut.glutDisplayFunc( glut_display )
+glut.glutIdleFunc( glut_idle )
+
+
+def inputhook(context):
+ """Run the pyglet event loop by processing pending events only.
+
+ This keeps processing pending events until stdin is ready. After
+ processing all pending events, a call to time.sleep is inserted. This is
+ needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
+ though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+
+ signal.signal(signal.SIGINT, glut_int_handler)
+
+ try:
+ t = clock()
+
+ # Make sure the default window is set after a window has been closed
+ if glut.glutGetWindow() == 0:
+ glut.glutSetWindow( 1 )
+ glutMainLoopEvent()
+ return 0
+
+ while not context.input_is_ready():
+ glutMainLoopEvent()
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ except KeyboardInterrupt:
+ pass
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py
index 8f27e12c46..ac7529ca00 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk.py
@@ -1,59 +1,59 @@
-# Code borrowed from python-prompt-toolkit examples
-# https://github.com/jonathanslenders/python-prompt-toolkit/blob/77cdcfbc7f4b4c34a9d2f9a34d422d7152f16209/examples/inputhook.py
-
-# Copyright (c) 2014, Jonathan Slenders
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without modification,
-# are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright notice, this
-# list of conditions and the following disclaimer in the documentation and/or
-# other materials provided with the distribution.
-#
-# * Neither the name of the {organization} nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
-# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""
-PyGTK input hook for prompt_toolkit.
-
-Listens on the pipe prompt_toolkit sets up for a notification that it should
-return control to the terminal event loop.
-"""
-from __future__ import absolute_import
-
-import gtk, gobject
-
-# Enable threading in GTK. (Otherwise, GTK will keep the GIL.)
-gtk.gdk.threads_init()
-
-def inputhook(context):
- """
- When the eventloop of prompt-toolkit is idle, call this inputhook.
-
- This will run the GTK main loop until the file descriptor
- `context.fileno()` becomes ready.
-
- :param context: An `InputHookContext` instance.
- """
- def _main_quit(*a, **kw):
- gtk.main_quit()
- return False
-
- gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit)
- gtk.main()
+# Code borrowed from python-prompt-toolkit examples
+# https://github.com/jonathanslenders/python-prompt-toolkit/blob/77cdcfbc7f4b4c34a9d2f9a34d422d7152f16209/examples/inputhook.py
+
+# Copyright (c) 2014, Jonathan Slenders
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright notice, this
+# list of conditions and the following disclaimer in the documentation and/or
+# other materials provided with the distribution.
+#
+# * Neither the name of the {organization} nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""
+PyGTK input hook for prompt_toolkit.
+
+Listens on the pipe prompt_toolkit sets up for a notification that it should
+return control to the terminal event loop.
+"""
+from __future__ import absolute_import
+
+import gtk, gobject
+
+# Enable threading in GTK. (Otherwise, GTK will keep the GIL.)
+gtk.gdk.threads_init()
+
+def inputhook(context):
+ """
+ When the eventloop of prompt-toolkit is idle, call this inputhook.
+
+ This will run the GTK main loop until the file descriptor
+ `context.fileno()` becomes ready.
+
+ :param context: An `InputHookContext` instance.
+ """
+ def _main_quit(*a, **kw):
+ gtk.main_quit()
+ return False
+
+ gobject.io_add_watch(context.fileno(), gobject.IO_IN, _main_quit)
+ gtk.main()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py
index 5c6c545457..40d6673359 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/gtk3.py
@@ -1,12 +1,12 @@
-"""prompt_toolkit input hook for GTK 3
-"""
-
-from gi.repository import Gtk, GLib
-
-def _main_quit(*args, **kwargs):
- Gtk.main_quit()
- return False
-
-def inputhook(context):
- GLib.io_add_watch(context.fileno(), GLib.IO_IN, _main_quit)
- Gtk.main()
+"""prompt_toolkit input hook for GTK 3
+"""
+
+from gi.repository import Gtk, GLib
+
+def _main_quit(*args, **kwargs):
+ Gtk.main_quit()
+ return False
+
+def inputhook(context):
+ GLib.io_add_watch(context.fileno(), GLib.IO_IN, _main_quit)
+ Gtk.main()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py
index 53f4e3838b..b916ee0540 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/osx.py
@@ -1,137 +1,137 @@
-"""Inputhook for OS X
-
-Calls NSApp / CoreFoundation APIs via ctypes.
-"""
-
-# obj-c boilerplate from appnope, used under BSD 2-clause
-
-import ctypes
-import ctypes.util
-from threading import Event
-
-objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
-
-void_p = ctypes.c_void_p
-
-objc.objc_getClass.restype = void_p
-objc.sel_registerName.restype = void_p
-objc.objc_msgSend.restype = void_p
-objc.objc_msgSend.argtypes = [void_p, void_p]
-
-msg = objc.objc_msgSend
-
-def _utf8(s):
- """ensure utf8 bytes"""
- if not isinstance(s, bytes):
- s = s.encode('utf8')
- return s
-
-def n(name):
- """create a selector name (for ObjC methods)"""
- return objc.sel_registerName(_utf8(name))
-
-def C(classname):
- """get an ObjC Class by name"""
- return objc.objc_getClass(_utf8(classname))
-
-# end obj-c boilerplate from appnope
-
-# CoreFoundation C-API calls we will use:
-CoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))
-
-CFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate
-CFFileDescriptorCreate.restype = void_p
-CFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p]
-
-CFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor
-CFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int
-CFFileDescriptorGetNativeDescriptor.argtypes = [void_p]
-
-CFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks
-CFFileDescriptorEnableCallBacks.restype = None
-CFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]
-
-CFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource
-CFFileDescriptorCreateRunLoopSource.restype = void_p
-CFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]
-
-CFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent
-CFRunLoopGetCurrent.restype = void_p
-
-CFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource
-CFRunLoopAddSource.restype = None
-CFRunLoopAddSource.argtypes = [void_p, void_p, void_p]
-
-CFRelease = CoreFoundation.CFRelease
-CFRelease.restype = None
-CFRelease.argtypes = [void_p]
-
-CFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate
-CFFileDescriptorInvalidate.restype = None
-CFFileDescriptorInvalidate.argtypes = [void_p]
-
-# From CFFileDescriptor.h
-kCFFileDescriptorReadCallBack = 1
-kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')
-
-
-def _NSApp():
- """Return the global NSApplication instance (NSApp)"""
- return msg(C('NSApplication'), n('sharedApplication'))
-
-
-def _wake(NSApp):
- """Wake the Application"""
- event = msg(C('NSEvent'),
- n('otherEventWithType:location:modifierFlags:'
- 'timestamp:windowNumber:context:subtype:data1:data2:'),
- 15, # Type
- 0, # location
- 0, # flags
- 0, # timestamp
- 0, # window
- None, # context
- 0, # subtype
- 0, # data1
- 0, # data2
- )
- msg(NSApp, n('postEvent:atStart:'), void_p(event), True)
-
-
-_triggered = Event()
-
-def _input_callback(fdref, flags, info):
- """Callback to fire when there's input to be read"""
- _triggered.set()
- CFFileDescriptorInvalidate(fdref)
- CFRelease(fdref)
- NSApp = _NSApp()
- msg(NSApp, n('stop:'), NSApp)
- _wake(NSApp)
-
-_c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)
-_c_input_callback = _c_callback_func_type(_input_callback)
-
-
-def _stop_on_read(fd):
- """Register callback to stop eventloop when there's data on fd"""
- _triggered.clear()
- fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)
- CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)
- source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)
- loop = CFRunLoopGetCurrent()
- CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)
- CFRelease(source)
-
-
-def inputhook(context):
- """Inputhook for Cocoa (NSApp)"""
- NSApp = _NSApp()
- _stop_on_read(context.fileno())
- msg(NSApp, n('run'))
- if not _triggered.is_set():
- # app closed without firing callback,
- # probably due to last window being closed.
- # Run the loop manually in this case,
- # since there may be events still to process (#9734)
- CoreFoundation.CFRunLoopRun()
+"""Inputhook for OS X
+
+Calls NSApp / CoreFoundation APIs via ctypes.
+"""
+
+# obj-c boilerplate from appnope, used under BSD 2-clause
+
+import ctypes
+import ctypes.util
+from threading import Event
+
+objc = ctypes.cdll.LoadLibrary(ctypes.util.find_library('objc'))
+
+void_p = ctypes.c_void_p
+
+objc.objc_getClass.restype = void_p
+objc.sel_registerName.restype = void_p
+objc.objc_msgSend.restype = void_p
+objc.objc_msgSend.argtypes = [void_p, void_p]
+
+msg = objc.objc_msgSend
+
+def _utf8(s):
+ """ensure utf8 bytes"""
+ if not isinstance(s, bytes):
+ s = s.encode('utf8')
+ return s
+
+def n(name):
+ """create a selector name (for ObjC methods)"""
+ return objc.sel_registerName(_utf8(name))
+
+def C(classname):
+ """get an ObjC Class by name"""
+ return objc.objc_getClass(_utf8(classname))
+
+# end obj-c boilerplate from appnope
+
+# CoreFoundation C-API calls we will use:
+CoreFoundation = ctypes.cdll.LoadLibrary(ctypes.util.find_library('CoreFoundation'))
+
+CFFileDescriptorCreate = CoreFoundation.CFFileDescriptorCreate
+CFFileDescriptorCreate.restype = void_p
+CFFileDescriptorCreate.argtypes = [void_p, ctypes.c_int, ctypes.c_bool, void_p]
+
+CFFileDescriptorGetNativeDescriptor = CoreFoundation.CFFileDescriptorGetNativeDescriptor
+CFFileDescriptorGetNativeDescriptor.restype = ctypes.c_int
+CFFileDescriptorGetNativeDescriptor.argtypes = [void_p]
+
+CFFileDescriptorEnableCallBacks = CoreFoundation.CFFileDescriptorEnableCallBacks
+CFFileDescriptorEnableCallBacks.restype = None
+CFFileDescriptorEnableCallBacks.argtypes = [void_p, ctypes.c_ulong]
+
+CFFileDescriptorCreateRunLoopSource = CoreFoundation.CFFileDescriptorCreateRunLoopSource
+CFFileDescriptorCreateRunLoopSource.restype = void_p
+CFFileDescriptorCreateRunLoopSource.argtypes = [void_p, void_p, void_p]
+
+CFRunLoopGetCurrent = CoreFoundation.CFRunLoopGetCurrent
+CFRunLoopGetCurrent.restype = void_p
+
+CFRunLoopAddSource = CoreFoundation.CFRunLoopAddSource
+CFRunLoopAddSource.restype = None
+CFRunLoopAddSource.argtypes = [void_p, void_p, void_p]
+
+CFRelease = CoreFoundation.CFRelease
+CFRelease.restype = None
+CFRelease.argtypes = [void_p]
+
+CFFileDescriptorInvalidate = CoreFoundation.CFFileDescriptorInvalidate
+CFFileDescriptorInvalidate.restype = None
+CFFileDescriptorInvalidate.argtypes = [void_p]
+
+# From CFFileDescriptor.h
+kCFFileDescriptorReadCallBack = 1
+kCFRunLoopCommonModes = void_p.in_dll(CoreFoundation, 'kCFRunLoopCommonModes')
+
+
+def _NSApp():
+ """Return the global NSApplication instance (NSApp)"""
+ return msg(C('NSApplication'), n('sharedApplication'))
+
+
+def _wake(NSApp):
+ """Wake the Application"""
+ event = msg(C('NSEvent'),
+ n('otherEventWithType:location:modifierFlags:'
+ 'timestamp:windowNumber:context:subtype:data1:data2:'),
+ 15, # Type
+ 0, # location
+ 0, # flags
+ 0, # timestamp
+ 0, # window
+ None, # context
+ 0, # subtype
+ 0, # data1
+ 0, # data2
+ )
+ msg(NSApp, n('postEvent:atStart:'), void_p(event), True)
+
+
+_triggered = Event()
+
+def _input_callback(fdref, flags, info):
+ """Callback to fire when there's input to be read"""
+ _triggered.set()
+ CFFileDescriptorInvalidate(fdref)
+ CFRelease(fdref)
+ NSApp = _NSApp()
+ msg(NSApp, n('stop:'), NSApp)
+ _wake(NSApp)
+
+_c_callback_func_type = ctypes.CFUNCTYPE(None, void_p, void_p, void_p)
+_c_input_callback = _c_callback_func_type(_input_callback)
+
+
+def _stop_on_read(fd):
+ """Register callback to stop eventloop when there's data on fd"""
+ _triggered.clear()
+ fdref = CFFileDescriptorCreate(None, fd, False, _c_input_callback, None)
+ CFFileDescriptorEnableCallBacks(fdref, kCFFileDescriptorReadCallBack)
+ source = CFFileDescriptorCreateRunLoopSource(None, fdref, 0)
+ loop = CFRunLoopGetCurrent()
+ CFRunLoopAddSource(loop, source, kCFRunLoopCommonModes)
+ CFRelease(source)
+
+
+def inputhook(context):
+ """Inputhook for Cocoa (NSApp)"""
+ NSApp = _NSApp()
+ _stop_on_read(context.fileno())
+ msg(NSApp, n('run'))
+ if not _triggered.is_set():
+ # app closed without firing callback,
+ # probably due to last window being closed.
+ # Run the loop manually in this case,
+ # since there may be events still to process (#9734)
+ CoreFoundation.CFRunLoopRun()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py
index 1c5ec44250..4fbf790b57 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/pyglet.py
@@ -1,68 +1,68 @@
-"""Enable pyglet to be used interacively with prompt_toolkit
-"""
-from __future__ import absolute_import
-
-import os
-import sys
-import time
-from timeit import default_timer as clock
-import pyglet
-
-# On linux only, window.flip() has a bug that causes an AttributeError on
-# window close. For details, see:
-# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
-
-if sys.platform.startswith('linux'):
- def flip(window):
- try:
- window.flip()
- except AttributeError:
- pass
-else:
- def flip(window):
- window.flip()
-
-
-def inputhook(context):
- """Run the pyglet event loop by processing pending events only.
-
- This keeps processing pending events until stdin is ready. After
- processing all pending events, a call to time.sleep is inserted. This is
- needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
- though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- t = clock()
- while not context.input_is_ready():
- pyglet.clock.tick()
- for window in pyglet.app.windows:
- window.switch_to()
- window.dispatch_events()
- window.dispatch_event('on_draw')
- flip(window)
-
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- except KeyboardInterrupt:
- pass
+"""Enable pyglet to be used interacively with prompt_toolkit
+"""
+from __future__ import absolute_import
+
+import os
+import sys
+import time
+from timeit import default_timer as clock
+import pyglet
+
+# On linux only, window.flip() has a bug that causes an AttributeError on
+# window close. For details, see:
+# http://groups.google.com/group/pyglet-users/browse_thread/thread/47c1aab9aa4a3d23/c22f9e819826799e?#c22f9e819826799e
+
+if sys.platform.startswith('linux'):
+ def flip(window):
+ try:
+ window.flip()
+ except AttributeError:
+ pass
+else:
+ def flip(window):
+ window.flip()
+
+
+def inputhook(context):
+ """Run the pyglet event loop by processing pending events only.
+
+ This keeps processing pending events until stdin is ready. After
+ processing all pending events, a call to time.sleep is inserted. This is
+ needed, otherwise, CPU usage is at 100%. This sleep time should be tuned
+ though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+ try:
+ t = clock()
+ while not context.input_is_ready():
+ pyglet.clock.tick()
+ for window in pyglet.app.windows:
+ window.switch_to()
+ window.dispatch_events()
+ window.dispatch_event('on_draw')
+ flip(window)
+
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ except KeyboardInterrupt:
+ pass
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py
index 7395ac39eb..5667cd8478 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/qt.py
@@ -1,16 +1,16 @@
-import sys
+import sys
import os
-from IPython.external.qt_for_kernel import QtCore, QtGui
-
-# If we create a QApplication, keep a reference to it so that it doesn't get
-# garbage collected.
-_appref = None
+from IPython.external.qt_for_kernel import QtCore, QtGui
+
+# If we create a QApplication, keep a reference to it so that it doesn't get
+# garbage collected.
+_appref = None
_already_warned = False
-
-def inputhook(context):
- global _appref
- app = QtCore.QCoreApplication.instance()
- if not app:
+
+def inputhook(context):
+ global _appref
+ app = QtCore.QCoreApplication.instance()
+ if not app:
if sys.platform == 'linux':
if not os.environ.get('DISPLAY') \
and not os.environ.get('WAYLAND_DISPLAY'):
@@ -24,26 +24,26 @@ def inputhook(context):
'variable. Deactivate Qt5 code.'
)
return
- _appref = app = QtGui.QApplication([" "])
- event_loop = QtCore.QEventLoop(app)
-
- if sys.platform == 'win32':
- # The QSocketNotifier method doesn't appear to work on Windows.
- # Use polling instead.
- timer = QtCore.QTimer()
- timer.timeout.connect(event_loop.quit)
- while not context.input_is_ready():
- timer.start(50) # 50 ms
- event_loop.exec_()
- timer.stop()
- else:
- # On POSIX platforms, we can use a file descriptor to quit the event
- # loop when there is input ready to read.
+ _appref = app = QtGui.QApplication([" "])
+ event_loop = QtCore.QEventLoop(app)
+
+ if sys.platform == 'win32':
+ # The QSocketNotifier method doesn't appear to work on Windows.
+ # Use polling instead.
+ timer = QtCore.QTimer()
+ timer.timeout.connect(event_loop.quit)
+ while not context.input_is_ready():
+ timer.start(50) # 50 ms
+ event_loop.exec_()
+ timer.stop()
+ else:
+ # On POSIX platforms, we can use a file descriptor to quit the event
+ # loop when there is input ready to read.
notifier = QtCore.QSocketNotifier(context.fileno(),
QtCore.QSocketNotifier.Read)
# connect the callback we care about before we turn it on
notifier.activated.connect(event_loop.exit)
- notifier.setEnabled(True)
+ notifier.setEnabled(True)
# only start the event loop we are not already flipped
if not context.input_is_ready():
event_loop.exec_()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py
index db205b0d2c..7d13001a65 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/tk.py
@@ -1,95 +1,95 @@
-# Code borrowed from ptpython
-# https://github.com/jonathanslenders/ptpython/blob/86b71a89626114b18898a0af463978bdb32eeb70/ptpython/eventloop.py
-
-# Copyright (c) 2015, Jonathan Slenders
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without modification,
-# are permitted provided that the following conditions are met:
-#
-# * Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# * Redistributions in binary form must reproduce the above copyright notice, this
-# list of conditions and the following disclaimer in the documentation and/or
-# other materials provided with the distribution.
-#
-# * Neither the name of the {organization} nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
-# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
-# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-"""
-Wrapper around the eventloop that gives some time to the Tkinter GUI to process
-events when it's loaded and while we are waiting for input at the REPL. This
-way we don't block the UI of for instance ``turtle`` and other Tk libraries.
-
-(Normally Tkinter registeres it's callbacks in ``PyOS_InputHook`` to integrate
-in readline. ``prompt-toolkit`` doesn't understand that input hook, but this
-will fix it for Tk.)
-"""
-import time
-
-from IPython.utils.py3compat import PY3
-
-import _tkinter
-if PY3:
- import tkinter
-else:
- import Tkinter as tkinter # Python 2
-
-def inputhook(inputhook_context):
- """
- Inputhook for Tk.
- Run the Tk eventloop until prompt-toolkit needs to process the next input.
- """
- # Get the current TK application.
- root = tkinter._default_root
-
- def wait_using_filehandler():
- """
- Run the TK eventloop until the file handler that we got from the
- inputhook becomes readable.
- """
- # Add a handler that sets the stop flag when `prompt-toolkit` has input
- # to process.
- stop = [False]
- def done(*a):
- stop[0] = True
-
- root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)
-
- # Run the TK event loop as long as we don't receive input.
- while root.dooneevent(_tkinter.ALL_EVENTS):
- if stop[0]:
- break
-
- root.deletefilehandler(inputhook_context.fileno())
-
- def wait_using_polling():
- """
- Windows TK doesn't support 'createfilehandler'.
- So, run the TK eventloop and poll until input is ready.
- """
- while not inputhook_context.input_is_ready():
- while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
- pass
- # Sleep to make the CPU idle, but not too long, so that the UI
- # stays responsive.
- time.sleep(.01)
-
- if root is not None:
- if hasattr(root, 'createfilehandler'):
- wait_using_filehandler()
- else:
- wait_using_polling()
+# Code borrowed from ptpython
+# https://github.com/jonathanslenders/ptpython/blob/86b71a89626114b18898a0af463978bdb32eeb70/ptpython/eventloop.py
+
+# Copyright (c) 2015, Jonathan Slenders
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright notice, this
+# list of conditions and the following disclaimer in the documentation and/or
+# other materials provided with the distribution.
+#
+# * Neither the name of the {organization} nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+"""
+Wrapper around the eventloop that gives some time to the Tkinter GUI to process
+events when it's loaded and while we are waiting for input at the REPL. This
+way we don't block the UI of for instance ``turtle`` and other Tk libraries.
+
+(Normally Tkinter registeres it's callbacks in ``PyOS_InputHook`` to integrate
+in readline. ``prompt-toolkit`` doesn't understand that input hook, but this
+will fix it for Tk.)
+"""
+import time
+
+from IPython.utils.py3compat import PY3
+
+import _tkinter
+if PY3:
+ import tkinter
+else:
+ import Tkinter as tkinter # Python 2
+
+def inputhook(inputhook_context):
+ """
+ Inputhook for Tk.
+ Run the Tk eventloop until prompt-toolkit needs to process the next input.
+ """
+ # Get the current TK application.
+ root = tkinter._default_root
+
+ def wait_using_filehandler():
+ """
+ Run the TK eventloop until the file handler that we got from the
+ inputhook becomes readable.
+ """
+ # Add a handler that sets the stop flag when `prompt-toolkit` has input
+ # to process.
+ stop = [False]
+ def done(*a):
+ stop[0] = True
+
+ root.createfilehandler(inputhook_context.fileno(), _tkinter.READABLE, done)
+
+ # Run the TK event loop as long as we don't receive input.
+ while root.dooneevent(_tkinter.ALL_EVENTS):
+ if stop[0]:
+ break
+
+ root.deletefilehandler(inputhook_context.fileno())
+
+ def wait_using_polling():
+ """
+ Windows TK doesn't support 'createfilehandler'.
+ So, run the TK eventloop and poll until input is ready.
+ """
+ while not inputhook_context.input_is_ready():
+ while root.dooneevent(_tkinter.ALL_EVENTS | _tkinter.DONT_WAIT):
+ pass
+ # Sleep to make the CPU idle, but not too long, so that the UI
+ # stays responsive.
+ time.sleep(.01)
+
+ if root is not None:
+ if hasattr(root, 'createfilehandler'):
+ wait_using_filehandler()
+ else:
+ wait_using_polling()
diff --git a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py
index 4371b21cb4..6dde092500 100644
--- a/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py
+++ b/contrib/python/ipython/py2/IPython/terminal/pt_inputhooks/wx.py
@@ -1,148 +1,148 @@
-"""Enable wxPython to be used interacively in prompt_toolkit
-"""
-from __future__ import absolute_import
-
-import sys
-import signal
-import time
-from timeit import default_timer as clock
-import wx
-
-
-def inputhook_wx1(context):
- """Run the wx event loop by processing pending events only.
-
- This approach seems to work, but its performance is not great as it
- relies on having PyOS_InputHook called regularly.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # Make a temporary event loop and process system events until
- # there are no more waiting, then allow idle events (which
- # will also deal with pending or posted wx events.)
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- while evtloop.Pending():
- evtloop.Dispatch()
- app.ProcessIdle()
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-class EventLoopTimer(wx.Timer):
-
- def __init__(self, func):
- self.func = func
- wx.Timer.__init__(self)
-
- def Notify(self):
- self.func()
-
-class EventLoopRunner(object):
-
- def Run(self, time, input_is_ready):
- self.input_is_ready = input_is_ready
- self.evtloop = wx.EventLoop()
- self.timer = EventLoopTimer(self.check_stdin)
- self.timer.Start(time)
- self.evtloop.Run()
-
- def check_stdin(self):
- if self.input_is_ready():
- self.timer.Stop()
- self.evtloop.Exit()
-
-def inputhook_wx2(context):
- """Run the wx event loop, polling for stdin.
-
- This version runs the wx eventloop for an undetermined amount of time,
- during which it periodically checks to see if anything is ready on
- stdin. If anything is ready on stdin, the event loop exits.
-
- The argument to elr.Run controls how often the event loop looks at stdin.
- This determines the responsiveness at the keyboard. A setting of 1000
- enables a user to type at most 1 char per second. I have found that a
- setting of 10 gives good keyboard response. We can shorten it further,
- but eventually performance would suffer from calling select/kbhit too
- often.
- """
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
- elr = EventLoopRunner()
- # As this time is made shorter, keyboard response improves, but idle
- # CPU load goes up. 10 ms seems like a good compromise.
- elr.Run(time=10, # CHANGE time here to control polling interval
- input_is_ready=context.input_is_ready)
- except KeyboardInterrupt:
- pass
- return 0
-
-def inputhook_wx3(context):
- """Run the wx event loop by processing pending events only.
-
- This is like inputhook_wx1, but it keeps processing pending events
- until stdin is ready. After processing all pending events, a call to
- time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
- This sleep time should be tuned though for best performance.
- """
- # We need to protect against a user pressing Control-C when IPython is
- # idle and this is running. We trap KeyboardInterrupt and pass.
- try:
- app = wx.GetApp()
- if app is not None:
- assert wx.Thread_IsMain()
-
- # The import of wx on Linux sets the handler for signal.SIGINT
- # to 0. This is a bug in wx or gtk. We fix by just setting it
- # back to the Python default.
- if not callable(signal.getsignal(signal.SIGINT)):
- signal.signal(signal.SIGINT, signal.default_int_handler)
-
- evtloop = wx.EventLoop()
- ea = wx.EventLoopActivator(evtloop)
- t = clock()
- while not context.input_is_ready():
- while evtloop.Pending():
- t = clock()
- evtloop.Dispatch()
- app.ProcessIdle()
- # We need to sleep at this point to keep the idle CPU load
- # low. However, if sleep to long, GUI response is poor. As
- # a compromise, we watch how often GUI events are being processed
- # and switch between a short and long sleep time. Here are some
- # stats useful in helping to tune this.
- # time CPU load
- # 0.001 13%
- # 0.005 3%
- # 0.01 1.5%
- # 0.05 0.5%
- used_time = clock() - t
- if used_time > 10.0:
- # print 'Sleep for 1 s' # dbg
- time.sleep(1.0)
- elif used_time > 0.1:
- # Few GUI events coming in, so we can sleep longer
- # print 'Sleep for 0.05 s' # dbg
- time.sleep(0.05)
- else:
- # Many GUI events coming in, so sleep only very little
- time.sleep(0.001)
- del ea
- except KeyboardInterrupt:
- pass
- return 0
-
-if sys.platform == 'darwin':
- # On OSX, evtloop.Pending() always returns True, regardless of there being
- # any events pending. As such we can't use implementations 1 or 3 of the
- # inputhook as those depend on a pending/dispatch loop.
- inputhook = inputhook_wx2
-else:
- # This is our default implementation
- inputhook = inputhook_wx3
+"""Enable wxPython to be used interacively in prompt_toolkit
+"""
+from __future__ import absolute_import
+
+import sys
+import signal
+import time
+from timeit import default_timer as clock
+import wx
+
+
+def inputhook_wx1(context):
+ """Run the wx event loop by processing pending events only.
+
+ This approach seems to work, but its performance is not great as it
+ relies on having PyOS_InputHook called regularly.
+ """
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+
+ # Make a temporary event loop and process system events until
+ # there are no more waiting, then allow idle events (which
+ # will also deal with pending or posted wx events.)
+ evtloop = wx.EventLoop()
+ ea = wx.EventLoopActivator(evtloop)
+ while evtloop.Pending():
+ evtloop.Dispatch()
+ app.ProcessIdle()
+ del ea
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+class EventLoopTimer(wx.Timer):
+
+ def __init__(self, func):
+ self.func = func
+ wx.Timer.__init__(self)
+
+ def Notify(self):
+ self.func()
+
+class EventLoopRunner(object):
+
+ def Run(self, time, input_is_ready):
+ self.input_is_ready = input_is_ready
+ self.evtloop = wx.EventLoop()
+ self.timer = EventLoopTimer(self.check_stdin)
+ self.timer.Start(time)
+ self.evtloop.Run()
+
+ def check_stdin(self):
+ if self.input_is_ready():
+ self.timer.Stop()
+ self.evtloop.Exit()
+
+def inputhook_wx2(context):
+ """Run the wx event loop, polling for stdin.
+
+ This version runs the wx eventloop for an undetermined amount of time,
+ during which it periodically checks to see if anything is ready on
+ stdin. If anything is ready on stdin, the event loop exits.
+
+ The argument to elr.Run controls how often the event loop looks at stdin.
+ This determines the responsiveness at the keyboard. A setting of 1000
+ enables a user to type at most 1 char per second. I have found that a
+ setting of 10 gives good keyboard response. We can shorten it further,
+ but eventually performance would suffer from calling select/kbhit too
+ often.
+ """
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+ elr = EventLoopRunner()
+ # As this time is made shorter, keyboard response improves, but idle
+ # CPU load goes up. 10 ms seems like a good compromise.
+ elr.Run(time=10, # CHANGE time here to control polling interval
+ input_is_ready=context.input_is_ready)
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+def inputhook_wx3(context):
+ """Run the wx event loop by processing pending events only.
+
+ This is like inputhook_wx1, but it keeps processing pending events
+ until stdin is ready. After processing all pending events, a call to
+ time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
+ This sleep time should be tuned though for best performance.
+ """
+ # We need to protect against a user pressing Control-C when IPython is
+ # idle and this is running. We trap KeyboardInterrupt and pass.
+ try:
+ app = wx.GetApp()
+ if app is not None:
+ assert wx.Thread_IsMain()
+
+ # The import of wx on Linux sets the handler for signal.SIGINT
+ # to 0. This is a bug in wx or gtk. We fix by just setting it
+ # back to the Python default.
+ if not callable(signal.getsignal(signal.SIGINT)):
+ signal.signal(signal.SIGINT, signal.default_int_handler)
+
+ evtloop = wx.EventLoop()
+ ea = wx.EventLoopActivator(evtloop)
+ t = clock()
+ while not context.input_is_ready():
+ while evtloop.Pending():
+ t = clock()
+ evtloop.Dispatch()
+ app.ProcessIdle()
+ # We need to sleep at this point to keep the idle CPU load
+ # low. However, if sleep to long, GUI response is poor. As
+ # a compromise, we watch how often GUI events are being processed
+ # and switch between a short and long sleep time. Here are some
+ # stats useful in helping to tune this.
+ # time CPU load
+ # 0.001 13%
+ # 0.005 3%
+ # 0.01 1.5%
+ # 0.05 0.5%
+ used_time = clock() - t
+ if used_time > 10.0:
+ # print 'Sleep for 1 s' # dbg
+ time.sleep(1.0)
+ elif used_time > 0.1:
+ # Few GUI events coming in, so we can sleep longer
+ # print 'Sleep for 0.05 s' # dbg
+ time.sleep(0.05)
+ else:
+ # Many GUI events coming in, so sleep only very little
+ time.sleep(0.001)
+ del ea
+ except KeyboardInterrupt:
+ pass
+ return 0
+
+if sys.platform == 'darwin':
+ # On OSX, evtloop.Pending() always returns True, regardless of there being
+ # any events pending. As such we can't use implementations 1 or 3 of the
+ # inputhook as those depend on a pending/dispatch loop.
+ inputhook = inputhook_wx2
+else:
+ # This is our default implementation
+ inputhook = inputhook_wx3
diff --git a/contrib/python/ipython/py2/IPython/terminal/ptshell.py b/contrib/python/ipython/py2/IPython/terminal/ptshell.py
index 666d3c5b51..aad111b041 100644
--- a/contrib/python/ipython/py2/IPython/terminal/ptshell.py
+++ b/contrib/python/ipython/py2/IPython/terminal/ptshell.py
@@ -1,8 +1,8 @@
-raise DeprecationWarning("""DEPRECATED:
-
-After Popular request and decision from the BDFL:
-`IPython.terminal.ptshell` has been moved back to `IPython.terminal.interactiveshell`
-during the beta cycle (after IPython 5.0.beta3) Sorry about that.
-
-This file will be removed in 5.0 rc or final.
-""")
+raise DeprecationWarning("""DEPRECATED:
+
+After Popular request and decision from the BDFL:
+`IPython.terminal.ptshell` has been moved back to `IPython.terminal.interactiveshell`
+during the beta cycle (after IPython 5.0.beta3) Sorry about that.
+
+This file will be removed in 5.0 rc or final.
+""")
diff --git a/contrib/python/ipython/py2/IPython/terminal/ptutils.py b/contrib/python/ipython/py2/IPython/terminal/ptutils.py
index c9ff705642..90def9d209 100644
--- a/contrib/python/ipython/py2/IPython/terminal/ptutils.py
+++ b/contrib/python/ipython/py2/IPython/terminal/ptutils.py
@@ -1,47 +1,47 @@
-"""prompt-toolkit utilities
-
-Everything in this module is a private API,
-not to be used outside IPython.
-"""
-
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
-
-import unicodedata
-from wcwidth import wcwidth
-
-from IPython.utils.py3compat import PY3
-
-from IPython.core.completer import IPCompleter
-from prompt_toolkit.completion import Completer, Completion
-from prompt_toolkit.layout.lexers import Lexer
-from prompt_toolkit.layout.lexers import PygmentsLexer
-
-import pygments.lexers as pygments_lexers
-
-
-class IPythonPTCompleter(Completer):
- """Adaptor to provide IPython completions to prompt_toolkit"""
+"""prompt-toolkit utilities
+
+Everything in this module is a private API,
+not to be used outside IPython.
+"""
+
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
+
+import unicodedata
+from wcwidth import wcwidth
+
+from IPython.utils.py3compat import PY3
+
+from IPython.core.completer import IPCompleter
+from prompt_toolkit.completion import Completer, Completion
+from prompt_toolkit.layout.lexers import Lexer
+from prompt_toolkit.layout.lexers import PygmentsLexer
+
+import pygments.lexers as pygments_lexers
+
+
+class IPythonPTCompleter(Completer):
+ """Adaptor to provide IPython completions to prompt_toolkit"""
def __init__(self, ipy_completer=None, shell=None, patch_stdout=None):
- if shell is None and ipy_completer is None:
- raise TypeError("Please pass shell=an InteractiveShell instance.")
- self._ipy_completer = ipy_completer
- self.shell = shell
+ if shell is None and ipy_completer is None:
+ raise TypeError("Please pass shell=an InteractiveShell instance.")
+ self._ipy_completer = ipy_completer
+ self.shell = shell
if patch_stdout is None:
raise TypeError("Please pass patch_stdout")
self.patch_stdout = patch_stdout
-
- @property
- def ipy_completer(self):
- if self._ipy_completer:
- return self._ipy_completer
- else:
- return self.shell.Completer
-
- def get_completions(self, document, complete_event):
- if not document.current_line.strip():
- return
-
+
+ @property
+ def ipy_completer(self):
+ if self._ipy_completer:
+ return self._ipy_completer
+ else:
+ return self.shell.Completer
+
+ def get_completions(self, document, complete_event):
+ if not document.current_line.strip():
+ return
+
# Some bits of our completion system may print stuff (e.g. if a module
# is imported). This context manager ensures that doesn't interfere with
# the prompt.
@@ -50,66 +50,66 @@ class IPythonPTCompleter(Completer):
line_buffer=document.current_line,
cursor_pos=document.cursor_position_col
)
- start_pos = -len(used)
- for m in matches:
- if not m:
- # Guard against completion machinery giving us an empty string.
- continue
-
- m = unicodedata.normalize('NFC', m)
-
- # When the first character of the completion has a zero length,
- # then it's probably a decomposed unicode character. E.g. caused by
- # the "\dot" completion. Try to compose again with the previous
- # character.
- if wcwidth(m[0]) == 0:
- if document.cursor_position + start_pos > 0:
- char_before = document.text[document.cursor_position + start_pos - 1]
- m = unicodedata.normalize('NFC', char_before + m)
-
- # Yield the modified completion instead, if this worked.
- if wcwidth(m[0:1]) == 1:
- yield Completion(m, start_position=start_pos - 1)
- continue
-
- # TODO: Use Jedi to determine meta_text
- # (Jedi currently has a bug that results in incorrect information.)
- # meta_text = ''
- # yield Completion(m, start_position=start_pos,
- # display_meta=meta_text)
- yield Completion(m, start_position=start_pos)
-
-class IPythonPTLexer(Lexer):
- """
- Wrapper around PythonLexer and BashLexer.
- """
- def __init__(self):
- l = pygments_lexers
- self.python_lexer = PygmentsLexer(l.Python3Lexer if PY3 else l.PythonLexer)
- self.shell_lexer = PygmentsLexer(l.BashLexer)
-
- self.magic_lexers = {
- 'HTML': PygmentsLexer(l.HtmlLexer),
- 'html': PygmentsLexer(l.HtmlLexer),
- 'javascript': PygmentsLexer(l.JavascriptLexer),
- 'js': PygmentsLexer(l.JavascriptLexer),
- 'perl': PygmentsLexer(l.PerlLexer),
- 'ruby': PygmentsLexer(l.RubyLexer),
- 'latex': PygmentsLexer(l.TexLexer),
- }
-
- def lex_document(self, cli, document):
- text = document.text.lstrip()
-
- lexer = self.python_lexer
-
- if text.startswith('!') or text.startswith('%%bash'):
- lexer = self.shell_lexer
-
- elif text.startswith('%%'):
- for magic, l in self.magic_lexers.items():
- if text.startswith('%%' + magic):
- lexer = l
- break
-
- return lexer.lex_document(cli, document)
+ start_pos = -len(used)
+ for m in matches:
+ if not m:
+ # Guard against completion machinery giving us an empty string.
+ continue
+
+ m = unicodedata.normalize('NFC', m)
+
+ # When the first character of the completion has a zero length,
+ # then it's probably a decomposed unicode character. E.g. caused by
+ # the "\dot" completion. Try to compose again with the previous
+ # character.
+ if wcwidth(m[0]) == 0:
+ if document.cursor_position + start_pos > 0:
+ char_before = document.text[document.cursor_position + start_pos - 1]
+ m = unicodedata.normalize('NFC', char_before + m)
+
+ # Yield the modified completion instead, if this worked.
+ if wcwidth(m[0:1]) == 1:
+ yield Completion(m, start_position=start_pos - 1)
+ continue
+
+ # TODO: Use Jedi to determine meta_text
+ # (Jedi currently has a bug that results in incorrect information.)
+ # meta_text = ''
+ # yield Completion(m, start_position=start_pos,
+ # display_meta=meta_text)
+ yield Completion(m, start_position=start_pos)
+
+class IPythonPTLexer(Lexer):
+ """
+ Wrapper around PythonLexer and BashLexer.
+ """
+ def __init__(self):
+ l = pygments_lexers
+ self.python_lexer = PygmentsLexer(l.Python3Lexer if PY3 else l.PythonLexer)
+ self.shell_lexer = PygmentsLexer(l.BashLexer)
+
+ self.magic_lexers = {
+ 'HTML': PygmentsLexer(l.HtmlLexer),
+ 'html': PygmentsLexer(l.HtmlLexer),
+ 'javascript': PygmentsLexer(l.JavascriptLexer),
+ 'js': PygmentsLexer(l.JavascriptLexer),
+ 'perl': PygmentsLexer(l.PerlLexer),
+ 'ruby': PygmentsLexer(l.RubyLexer),
+ 'latex': PygmentsLexer(l.TexLexer),
+ }
+
+ def lex_document(self, cli, document):
+ text = document.text.lstrip()
+
+ lexer = self.python_lexer
+
+ if text.startswith('!') or text.startswith('%%bash'):
+ lexer = self.shell_lexer
+
+ elif text.startswith('%%'):
+ for magic, l in self.magic_lexers.items():
+ if text.startswith('%%' + magic):
+ lexer = l
+ break
+
+ return lexer.lex_document(cli, document)
diff --git a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py
index 8f0ae43e84..2769cf8e8e 100644
--- a/contrib/python/ipython/py2/IPython/terminal/shortcuts.py
+++ b/contrib/python/ipython/py2/IPython/terminal/shortcuts.py
@@ -1,101 +1,101 @@
-import signal
-import sys
-
-from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
-from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
- ViInsertMode, EmacsInsertMode, HasCompletions)
-from prompt_toolkit.filters.cli import ViMode
-from prompt_toolkit.keys import Keys
-from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
-
-from IPython.utils.decorators import undoc
-
-@Condition
-def cursor_in_leading_ws(cli):
- before = cli.application.buffer.document.current_line_before_cursor
- return (not before) or before.isspace()
-
-def register_ipython_shortcuts(registry, shell):
- """Set up the prompt_toolkit keyboard shortcuts for IPython"""
- insert_mode = ViInsertMode() | EmacsInsertMode()
-
- # Ctrl+J == Enter, seemingly
- registry.add_binding(Keys.ControlJ,
- filter=(HasFocus(DEFAULT_BUFFER)
- & ~HasSelection()
- & insert_mode
- ))(newline_or_execute_outer(shell))
-
- registry.add_binding(Keys.ControlBackslash)(force_exit)
-
- registry.add_binding(Keys.ControlP,
- filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
- ))(previous_history_or_previous_completion)
-
- registry.add_binding(Keys.ControlN,
- filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
- ))(next_history_or_next_completion)
-
- registry.add_binding(Keys.ControlG,
- filter=(HasFocus(DEFAULT_BUFFER) & HasCompletions()
- ))(dismiss_completion)
-
- registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)
- )(reset_buffer)
-
- registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)
- )(reset_search_buffer)
-
- supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
- registry.add_binding(Keys.ControlZ, filter=supports_suspend
- )(suspend_to_bg)
-
- # Ctrl+I == Tab
- registry.add_binding(Keys.ControlI,
- filter=(HasFocus(DEFAULT_BUFFER)
- & ~HasSelection()
- & insert_mode
- & cursor_in_leading_ws
- ))(indent_buffer)
-
- registry.add_binding(Keys.ControlO,
- filter=(HasFocus(DEFAULT_BUFFER)
- & EmacsInsertMode()))(newline_with_copy_margin)
-
+import signal
+import sys
+
+from prompt_toolkit.enums import DEFAULT_BUFFER, SEARCH_BUFFER
+from prompt_toolkit.filters import (HasFocus, HasSelection, Condition,
+ ViInsertMode, EmacsInsertMode, HasCompletions)
+from prompt_toolkit.filters.cli import ViMode
+from prompt_toolkit.keys import Keys
+from prompt_toolkit.key_binding.bindings.completion import display_completions_like_readline
+
+from IPython.utils.decorators import undoc
+
+@Condition
+def cursor_in_leading_ws(cli):
+ before = cli.application.buffer.document.current_line_before_cursor
+ return (not before) or before.isspace()
+
+def register_ipython_shortcuts(registry, shell):
+ """Set up the prompt_toolkit keyboard shortcuts for IPython"""
+ insert_mode = ViInsertMode() | EmacsInsertMode()
+
+ # Ctrl+J == Enter, seemingly
+ registry.add_binding(Keys.ControlJ,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & ~HasSelection()
+ & insert_mode
+ ))(newline_or_execute_outer(shell))
+
+ registry.add_binding(Keys.ControlBackslash)(force_exit)
+
+ registry.add_binding(Keys.ControlP,
+ filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
+ ))(previous_history_or_previous_completion)
+
+ registry.add_binding(Keys.ControlN,
+ filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)
+ ))(next_history_or_next_completion)
+
+ registry.add_binding(Keys.ControlG,
+ filter=(HasFocus(DEFAULT_BUFFER) & HasCompletions()
+ ))(dismiss_completion)
+
+ registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)
+ )(reset_buffer)
+
+ registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)
+ )(reset_search_buffer)
+
+ supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
+ registry.add_binding(Keys.ControlZ, filter=supports_suspend
+ )(suspend_to_bg)
+
+ # Ctrl+I == Tab
+ registry.add_binding(Keys.ControlI,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & ~HasSelection()
+ & insert_mode
+ & cursor_in_leading_ws
+ ))(indent_buffer)
+
+ registry.add_binding(Keys.ControlO,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & EmacsInsertMode()))(newline_with_copy_margin)
+
registry.add_binding(Keys.F2,
filter=HasFocus(DEFAULT_BUFFER)
)(open_input_in_editor)
- if shell.display_completions == 'readlinelike':
- registry.add_binding(Keys.ControlI,
- filter=(HasFocus(DEFAULT_BUFFER)
- & ~HasSelection()
- & insert_mode
- & ~cursor_in_leading_ws
- ))(display_completions_like_readline)
-
- if sys.platform == 'win32':
- registry.add_binding(Keys.ControlV,
- filter=(
- HasFocus(
- DEFAULT_BUFFER) & ~ViMode()
- ))(win_paste)
-
-
-def newline_or_execute_outer(shell):
- def newline_or_execute(event):
- """When the user presses return, insert a newline or execute the code."""
- b = event.current_buffer
- d = b.document
-
- if b.complete_state:
- cc = b.complete_state.current_completion
- if cc:
- b.apply_completion(cc)
- else:
- b.cancel_completion()
- return
-
+ if shell.display_completions == 'readlinelike':
+ registry.add_binding(Keys.ControlI,
+ filter=(HasFocus(DEFAULT_BUFFER)
+ & ~HasSelection()
+ & insert_mode
+ & ~cursor_in_leading_ws
+ ))(display_completions_like_readline)
+
+ if sys.platform == 'win32':
+ registry.add_binding(Keys.ControlV,
+ filter=(
+ HasFocus(
+ DEFAULT_BUFFER) & ~ViMode()
+ ))(win_paste)
+
+
+def newline_or_execute_outer(shell):
+ def newline_or_execute(event):
+ """When the user presses return, insert a newline or execute the code."""
+ b = event.current_buffer
+ d = b.document
+
+ if b.complete_state:
+ cc = b.complete_state.current_completion
+ if cc:
+ b.apply_completion(cc)
+ else:
+ b.cancel_completion()
+ return
+
# If there's only one line, treat it as if the cursor is at the end.
# See https://github.com/ipython/ipython/issues/10425
if d.line_count == 1:
@@ -108,99 +108,99 @@ def newline_or_execute_outer(shell):
d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()
):
b.insert_text('\n' + (' ' * (indent or 0)))
- return
-
- if (status != 'incomplete') and b.accept_action.is_returnable:
- b.accept_action.validate_and_handle(event.cli, b)
- else:
- b.insert_text('\n' + (' ' * (indent or 0)))
- return newline_or_execute
-
-
-def previous_history_or_previous_completion(event):
- """
- Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
-
- If completer is open this still select previous completion.
- """
- event.current_buffer.auto_up()
-
-
-def next_history_or_next_completion(event):
- """
- Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
-
- If completer is open this still select next completion.
- """
- event.current_buffer.auto_down()
-
-
-def dismiss_completion(event):
- b = event.current_buffer
- if b.complete_state:
- b.cancel_completion()
-
-
-def reset_buffer(event):
- b = event.current_buffer
- if b.complete_state:
- b.cancel_completion()
- else:
- b.reset()
-
-
-def reset_search_buffer(event):
- if event.current_buffer.document.text:
- event.current_buffer.reset()
- else:
- event.cli.push_focus(DEFAULT_BUFFER)
-
-def suspend_to_bg(event):
- event.cli.suspend_to_background()
-
-def force_exit(event):
- """
- Force exit (with a non-zero return value)
- """
- sys.exit("Quit")
-
-def indent_buffer(event):
- event.current_buffer.insert_text(' ' * 4)
-
-def newline_with_copy_margin(event):
- """
- Preserve margin and cursor position when using
- Control-O to insert a newline in EMACS mode
- """
- b = event.current_buffer
- cursor_start_pos = b.document.cursor_position_col
- b.newline(copy_margin=True)
- b.cursor_up(count=1)
- cursor_end_pos = b.document.cursor_position_col
- if cursor_start_pos != cursor_end_pos:
- pos_diff = cursor_start_pos - cursor_end_pos
- b.cursor_right(count=pos_diff)
-
+ return
+
+ if (status != 'incomplete') and b.accept_action.is_returnable:
+ b.accept_action.validate_and_handle(event.cli, b)
+ else:
+ b.insert_text('\n' + (' ' * (indent or 0)))
+ return newline_or_execute
+
+
+def previous_history_or_previous_completion(event):
+ """
+ Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
+
+ If completer is open this still select previous completion.
+ """
+ event.current_buffer.auto_up()
+
+
+def next_history_or_next_completion(event):
+ """
+ Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
+
+ If completer is open this still select next completion.
+ """
+ event.current_buffer.auto_down()
+
+
+def dismiss_completion(event):
+ b = event.current_buffer
+ if b.complete_state:
+ b.cancel_completion()
+
+
+def reset_buffer(event):
+ b = event.current_buffer
+ if b.complete_state:
+ b.cancel_completion()
+ else:
+ b.reset()
+
+
+def reset_search_buffer(event):
+ if event.current_buffer.document.text:
+ event.current_buffer.reset()
+ else:
+ event.cli.push_focus(DEFAULT_BUFFER)
+
+def suspend_to_bg(event):
+ event.cli.suspend_to_background()
+
+def force_exit(event):
+ """
+ Force exit (with a non-zero return value)
+ """
+ sys.exit("Quit")
+
+def indent_buffer(event):
+ event.current_buffer.insert_text(' ' * 4)
+
+def newline_with_copy_margin(event):
+ """
+ Preserve margin and cursor position when using
+ Control-O to insert a newline in EMACS mode
+ """
+ b = event.current_buffer
+ cursor_start_pos = b.document.cursor_position_col
+ b.newline(copy_margin=True)
+ b.cursor_up(count=1)
+ cursor_end_pos = b.document.cursor_position_col
+ if cursor_start_pos != cursor_end_pos:
+ pos_diff = cursor_start_pos - cursor_end_pos
+ b.cursor_right(count=pos_diff)
+
def open_input_in_editor(event):
event.cli.current_buffer.tempfile_suffix = ".py"
event.cli.current_buffer.open_in_editor(event.cli)
-
-
-if sys.platform == 'win32':
- from IPython.core.error import TryNext
- from IPython.lib.clipboard import (ClipboardEmpty,
- win32_clipboard_get,
- tkinter_clipboard_get)
-
- @undoc
- def win_paste(event):
- try:
- text = win32_clipboard_get()
- except TryNext:
- try:
- text = tkinter_clipboard_get()
- except (TryNext, ClipboardEmpty):
- return
- except ClipboardEmpty:
- return
- event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
+
+
+if sys.platform == 'win32':
+ from IPython.core.error import TryNext
+ from IPython.lib.clipboard import (ClipboardEmpty,
+ win32_clipboard_get,
+ tkinter_clipboard_get)
+
+ @undoc
+ def win_paste(event):
+ try:
+ text = win32_clipboard_get()
+ except TryNext:
+ try:
+ text = tkinter_clipboard_get()
+ except (TryNext, ClipboardEmpty):
+ return
+ except ClipboardEmpty:
+ return
+ event.current_buffer.insert_text(text.replace('\t', ' ' * 4))
diff --git a/contrib/python/ipython/py2/IPython/testing/decorators.py b/contrib/python/ipython/py2/IPython/testing/decorators.py
index c9807ce70e..26c6478f9e 100644
--- a/contrib/python/ipython/py2/IPython/testing/decorators.py
+++ b/contrib/python/ipython/py2/IPython/testing/decorators.py
@@ -48,7 +48,7 @@ from .ipunittest import ipdoctest, ipdocstring
from IPython.external.decorators import *
# For onlyif_cmd_exists decorator
-from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY
+from IPython.utils.py3compat import string_types, which, PY2, PY3, PYPY
#-----------------------------------------------------------------------------
# Classes and functions
@@ -339,7 +339,7 @@ skip_known_failure = knownfailureif(True,'This test is known to fail')
known_failure_py3 = knownfailureif(sys.version_info[0] >= 3,
'This test is known to fail on Python 3.')
-cpython2_only = skipif(PY3 or PYPY, "This test only runs on CPython 2.")
+cpython2_only = skipif(PY3 or PYPY, "This test only runs on CPython 2.")
py2_only = skipif(PY3, "This test only runs on Python 2.")
py3_only = skipif(PY2, "This test only runs on Python 3.")
diff --git a/contrib/python/ipython/py2/IPython/testing/globalipapp.py b/contrib/python/ipython/py2/IPython/testing/globalipapp.py
index 3983393112..adcb1dd587 100644
--- a/contrib/python/ipython/py2/IPython/testing/globalipapp.py
+++ b/contrib/python/ipython/py2/IPython/testing/globalipapp.py
@@ -8,11 +8,11 @@ done.
from __future__ import absolute_import
from __future__ import print_function
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import sys
-import warnings
+import warnings
from . import tools
@@ -34,9 +34,9 @@ class StreamProxy(io.IOStream):
"""
def __init__(self, name):
- warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning,
- stacklevel=2,
- )
+ warnings.warn("StreamProxy is deprecated and unused as of IPython 5", DeprecationWarning,
+ stacklevel=2,
+ )
self.name=name
@property
@@ -88,7 +88,7 @@ def start_ipython():
# Create custom argv and namespaces for our IPython to be test-friendly
config = tools.default_config()
- config.TerminalInteractiveShell.simple_prompt = True
+ config.TerminalInteractiveShell.simple_prompt = True
# Create and initialize our test-friendly IPython instance.
shell = TerminalInteractiveShell.instance(config=config,
@@ -128,8 +128,8 @@ def start_ipython():
# Override paging, so we don't require user interaction during the tests.
def nopage(strng, start=0, screen_lines=0, pager_cmd=None):
- if isinstance(strng, dict):
- strng = strng.get('text/plain', '')
+ if isinstance(strng, dict):
+ strng = strng.get('text/plain', '')
print(strng)
page.orig_page = page.pager_page
diff --git a/contrib/python/ipython/py2/IPython/testing/iptest.py b/contrib/python/ipython/py2/IPython/testing/iptest.py
index 4018264125..10d08b9e5a 100644
--- a/contrib/python/ipython/py2/IPython/testing/iptest.py
+++ b/contrib/python/ipython/py2/IPython/testing/iptest.py
@@ -44,10 +44,10 @@ pjoin = path.join
# Enable printing all warnings raise by IPython's modules
-warnings.filterwarnings('ignore', message='.*Matplotlib is building the font cache.*', category=UserWarning, module='.*')
-if sys.version_info > (3,0):
- warnings.filterwarnings('error', message='.*', category=ResourceWarning, module='.*')
-warnings.filterwarnings('error', message=".*{'config': True}.*", category=DeprecationWarning, module='IPy.*')
+warnings.filterwarnings('ignore', message='.*Matplotlib is building the font cache.*', category=UserWarning, module='.*')
+if sys.version_info > (3,0):
+ warnings.filterwarnings('error', message='.*', category=ResourceWarning, module='.*')
+warnings.filterwarnings('error', message=".*{'config': True}.*", category=DeprecationWarning, module='IPy.*')
warnings.filterwarnings('default', message='.*', category=Warning, module='IPy.*')
warnings.filterwarnings('error', message='.*apply_wrapper.*', category=DeprecationWarning, module='.*')
@@ -217,7 +217,7 @@ test_group_names.append('autoreload')
def check_exclusions_exist():
from IPython.paths import get_ipython_package_dir
- from warnings import warn
+ from warnings import warn
parent = os.path.dirname(get_ipython_package_dir())
for sec in test_sections:
for pattern in sec.exclusions:
diff --git a/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py b/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
index bc750e0efd..8eec1231a9 100644
--- a/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
+++ b/contrib/python/ipython/py2/IPython/testing/plugin/ipdoctest.py
@@ -26,8 +26,8 @@ import os
import re
import sys
-from testpath import modified_env
-
+from testpath import modified_env
+
from inspect import getmodule
# We are overriding the default doctest runner, so we need to import a few
@@ -41,7 +41,7 @@ from doctest import (REPORTING_FLAGS, REPORT_ONLY_FIRST_FAILURE,
# Third-party modules
from nose.plugins import doctests, Plugin
-from nose.util import anyp, tolist
+from nose.util import anyp, tolist
# Our own imports
from IPython.utils.py3compat import builtin_mod, PY3, getcwd
@@ -140,7 +140,7 @@ class DocTestFinder(doctest.DocTestFinder):
# doctests in extension modules.
# Local shorthands
- from inspect import isroutine, isclass
+ from inspect import isroutine, isclass
# Look for tests in a module's contained objects.
if inspect.ismodule(obj) and self._recurse:
@@ -586,10 +586,10 @@ class IPDocTestRunner(doctest.DocTestRunner,object):
test.globs.update(_ip.user_ns)
- # Override terminal size to standardise traceback format
- with modified_env({'COLUMNS': '80', 'LINES': '24'}):
- return super(IPDocTestRunner,self).run(test,
- compileflags,out,clear_globs)
+ # Override terminal size to standardise traceback format
+ with modified_env({'COLUMNS': '80', 'LINES': '24'}):
+ return super(IPDocTestRunner,self).run(test,
+ compileflags,out,clear_globs)
class DocFileCase(doctest.DocFileCase):
diff --git a/contrib/python/ipython/py2/IPython/testing/skipdoctest.py b/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
index 564ca54027..499ce28e07 100644
--- a/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
+++ b/contrib/python/ipython/py2/IPython/testing/skipdoctest.py
@@ -36,8 +36,8 @@ def skip_doctest_py3(f):
"""Decorator - skip the doctest under Python 3."""
f.skip_doctest = (sys.version_info[0] >= 3)
return f
-
-def skip_doctest_py2(f):
- """Decorator - skip the doctest under Python 3."""
- f.skip_doctest = (sys.version_info[0] < 3)
- return f
+
+def skip_doctest_py2(f):
+ """Decorator - skip the doctest under Python 3."""
+ f.skip_doctest = (sys.version_info[0] < 3)
+ return f
diff --git a/contrib/python/ipython/py2/IPython/testing/tools.py b/contrib/python/ipython/py2/IPython/testing/tools.py
index 23bf6a68cb..fbe91abcca 100644
--- a/contrib/python/ipython/py2/IPython/testing/tools.py
+++ b/contrib/python/ipython/py2/IPython/testing/tools.py
@@ -196,7 +196,7 @@ def ipexec(fname, options=None, commands=()):
"""
if options is None: options = []
- cmdargs = default_argv() + options
+ cmdargs = default_argv() + options
test_dir = os.path.dirname(__file__)
@@ -291,13 +291,13 @@ class TempFileMixin(object):
# delete it. I have no clue why
pass
- def __enter__(self):
- return self
-
- def __exit__(self, exc_type, exc_value, traceback):
- self.tearDown()
-
-
+ def __enter__(self):
+ return self
+
+ def __exit__(self, exc_type, exc_value, traceback):
+ self.tearDown()
+
+
pair_fail_msg = ("Testing {0}\n\n"
"In:\n"
" {1!r}\n"
diff --git a/contrib/python/ipython/py2/IPython/utils/PyColorize.py b/contrib/python/ipython/py2/IPython/utils/PyColorize.py
index 124eb2d4e3..66d52f34dd 100644
--- a/contrib/python/ipython/py2/IPython/utils/PyColorize.py
+++ b/contrib/python/ipython/py2/IPython/utils/PyColorize.py
@@ -54,8 +54,8 @@ except AttributeError:
from IPython.utils.coloransi import TermColors, InputTermColors ,ColorScheme, ColorSchemeTable
from IPython.utils.py3compat import PY3
-from .colorable import Colorable
-
+from .colorable import Colorable
+
if PY3:
from io import StringIO
else:
@@ -122,40 +122,40 @@ LinuxColors = ColorScheme(
'normal' : Colors.Normal # color off (usu. Colors.Normal)
} )
-NeutralColors = ColorScheme(
- 'Neutral',{
- 'header' : Colors.Red,
- token.NUMBER : Colors.Cyan,
- token.OP : Colors.Blue,
- token.STRING : Colors.Blue,
- tokenize.COMMENT : Colors.Red,
- token.NAME : Colors.Normal,
- token.ERRORTOKEN : Colors.Red,
-
- _KEYWORD : Colors.Green,
- _TEXT : Colors.Blue,
-
- 'in_prompt' : InputTermColors.Blue,
- 'in_number' : InputTermColors.LightBlue,
- 'in_prompt2' : InputTermColors.Blue,
- 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
-
- 'out_prompt' : Colors.Red,
- 'out_number' : Colors.LightRed,
-
- 'normal' : Colors.Normal # color off (usu. Colors.Normal)
- } )
-
-# Hack: the 'neutral' colours are not very visible on a dark background on
-# Windows. Since Windows command prompts have a dark background by default, and
-# relatively few users are likely to alter that, we will use the 'Linux' colours,
-# designed for a dark background, as the default on Windows. Changing it here
-# avoids affecting the prompt colours rendered by prompt_toolkit, where the
-# neutral defaults do work OK.
-
-if os.name == 'nt':
- NeutralColors = LinuxColors.copy(name='Neutral')
-
+NeutralColors = ColorScheme(
+ 'Neutral',{
+ 'header' : Colors.Red,
+ token.NUMBER : Colors.Cyan,
+ token.OP : Colors.Blue,
+ token.STRING : Colors.Blue,
+ tokenize.COMMENT : Colors.Red,
+ token.NAME : Colors.Normal,
+ token.ERRORTOKEN : Colors.Red,
+
+ _KEYWORD : Colors.Green,
+ _TEXT : Colors.Blue,
+
+ 'in_prompt' : InputTermColors.Blue,
+ 'in_number' : InputTermColors.LightBlue,
+ 'in_prompt2' : InputTermColors.Blue,
+ 'in_normal' : InputTermColors.Normal, # color off (usu. Colors.Normal)
+
+ 'out_prompt' : Colors.Red,
+ 'out_number' : Colors.LightRed,
+
+ 'normal' : Colors.Normal # color off (usu. Colors.Normal)
+ } )
+
+# Hack: the 'neutral' colours are not very visible on a dark background on
+# Windows. Since Windows command prompts have a dark background by default, and
+# relatively few users are likely to alter that, we will use the 'Linux' colours,
+# designed for a dark background, as the default on Windows. Changing it here
+# avoids affecting the prompt colours rendered by prompt_toolkit, where the
+# neutral defaults do work OK.
+
+if os.name == 'nt':
+ NeutralColors = LinuxColors.copy(name='Neutral')
+
LightBGColors = ColorScheme(
'LightBG',{
'header' : Colors.Red,
@@ -166,7 +166,7 @@ LightBGColors = ColorScheme(
token.NAME : Colors.Normal,
token.ERRORTOKEN : Colors.Red,
-
+
_KEYWORD : Colors.Green,
_TEXT : Colors.Blue,
@@ -182,21 +182,21 @@ LightBGColors = ColorScheme(
} )
# Build table of color schemes (needed by the parser)
-ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
+ANSICodeColors = ColorSchemeTable([NoColor,LinuxColors,LightBGColors, NeutralColors],
_scheme_default)
-class Parser(Colorable):
+class Parser(Colorable):
""" Format colored Python source.
"""
- def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
+ def __init__(self, color_table=None, out = sys.stdout, parent=None, style=None):
""" Create a parser with a specified color table and output channel.
Call format() to process code.
"""
-
- super(Parser, self).__init__(parent=parent)
-
+
+ super(Parser, self).__init__(parent=parent)
+
self.color_table = color_table and color_table or ANSICodeColors
self.out = out
diff --git a/contrib/python/ipython/py2/IPython/utils/_process_common.py b/contrib/python/ipython/py2/IPython/utils/_process_common.py
index 9ede30d3f8..e1b305f734 100644
--- a/contrib/python/ipython/py2/IPython/utils/_process_common.py
+++ b/contrib/python/ipython/py2/IPython/utils/_process_common.py
@@ -17,7 +17,7 @@ of subprocess utilities, and it contains tools that are common to all of them.
import subprocess
import shlex
import sys
-import os
+import os
from IPython.utils import py3compat
@@ -70,14 +70,14 @@ def process_handler(cmd, callback, stderr=subprocess.PIPE):
sys.stderr.flush()
# On win32, close_fds can't be true when using pipes for stdin/out/err
close_fds = sys.platform != 'win32'
- # Determine if cmd should be run with system shell.
- shell = isinstance(cmd, py3compat.string_types)
- # On POSIX systems run shell commands with user-preferred shell.
- executable = None
- if shell and os.name == 'posix' and 'SHELL' in os.environ:
- executable = os.environ['SHELL']
- p = subprocess.Popen(cmd, shell=shell,
- executable=executable,
+ # Determine if cmd should be run with system shell.
+ shell = isinstance(cmd, py3compat.string_types)
+ # On POSIX systems run shell commands with user-preferred shell.
+ executable = None
+ if shell and os.name == 'posix' and 'SHELL' in os.environ:
+ executable = os.environ['SHELL']
+ p = subprocess.Popen(cmd, shell=shell,
+ executable=executable,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=stderr,
diff --git a/contrib/python/ipython/py2/IPython/utils/colorable.py b/contrib/python/ipython/py2/IPython/utils/colorable.py
index 9f7c5ac213..1d5b6b4abe 100644
--- a/contrib/python/ipython/py2/IPython/utils/colorable.py
+++ b/contrib/python/ipython/py2/IPython/utils/colorable.py
@@ -1,26 +1,26 @@
-#*****************************************************************************
-# Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
-#
-# Distributed under the terms of the BSD License. The full license is in
-# the file COPYING, distributed as part of this software.
-#*****************************************************************************
-from __future__ import absolute_import
-
-"""
-Color managing related utilities
-"""
-
-import pygments
-
-from traitlets.config import Configurable
-from traitlets import Unicode
-
-
-available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral']
-
-class Colorable(Configurable):
- """
- A subclass of configurable for all the classes that have a `default_scheme`
- """
- default_style=Unicode('lightbg').tag(config=True)
-
+#*****************************************************************************
+# Copyright (C) 2016 The IPython Team <ipython-dev@scipy.org>
+#
+# Distributed under the terms of the BSD License. The full license is in
+# the file COPYING, distributed as part of this software.
+#*****************************************************************************
+from __future__ import absolute_import
+
+"""
+Color managing related utilities
+"""
+
+import pygments
+
+from traitlets.config import Configurable
+from traitlets import Unicode
+
+
+available_themes = lambda : [s for s in pygments.styles.get_all_styles()]+['NoColor','LightBG','Linux', 'Neutral']
+
+class Colorable(Configurable):
+ """
+ A subclass of configurable for all the classes that have a `default_scheme`
+ """
+ default_style=Unicode('lightbg').tag(config=True)
+
diff --git a/contrib/python/ipython/py2/IPython/utils/contexts.py b/contrib/python/ipython/py2/IPython/utils/contexts.py
index 4d379b0eda..14f4b47ba6 100644
--- a/contrib/python/ipython/py2/IPython/utils/contexts.py
+++ b/contrib/python/ipython/py2/IPython/utils/contexts.py
@@ -2,8 +2,8 @@
"""Miscellaneous context managers.
"""
-import warnings
-
+import warnings
+
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
@@ -61,14 +61,14 @@ class preserve_keys(object):
class NoOpContext(object):
- """
- Deprecated
-
- Context manager that does nothing."""
-
- def __init__(self):
- warnings.warn("""NoOpContext is deprecated since IPython 5.0 """,
- DeprecationWarning, stacklevel=2)
-
+ """
+ Deprecated
+
+ Context manager that does nothing."""
+
+ def __init__(self):
+ warnings.warn("""NoOpContext is deprecated since IPython 5.0 """,
+ DeprecationWarning, stacklevel=2)
+
def __enter__(self): pass
def __exit__(self, type, value, traceback): pass
diff --git a/contrib/python/ipython/py2/IPython/utils/dir2.py b/contrib/python/ipython/py2/IPython/utils/dir2.py
index f6f164f9b1..352c079178 100644
--- a/contrib/python/ipython/py2/IPython/utils/dir2.py
+++ b/contrib/python/ipython/py2/IPython/utils/dir2.py
@@ -2,10 +2,10 @@
"""A fancy version of Python's builtin :func:`dir` function.
"""
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
-import inspect
+import inspect
from .py3compat import string_types
@@ -46,36 +46,36 @@ def dir2(obj):
words = [w for w in words if isinstance(w, string_types)]
return sorted(words)
-
-
-def get_real_method(obj, name):
- """Like getattr, but with a few extra sanity checks:
-
- - If obj is a class, ignore its methods
- - Check if obj is a proxy that claims to have all attributes
- - Catch attribute access failing with any exception
- - Check that the attribute is a callable object
-
- Returns the method or None.
- """
- if inspect.isclass(obj):
- return None
-
- try:
- canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
- except Exception:
- return None
-
- if canary is not None:
- # It claimed to have an attribute it should never have
- return None
-
- try:
- m = getattr(obj, name, None)
- except Exception:
- return None
-
- if callable(m):
- return m
-
- return None
+
+
+def get_real_method(obj, name):
+ """Like getattr, but with a few extra sanity checks:
+
+ - If obj is a class, ignore its methods
+ - Check if obj is a proxy that claims to have all attributes
+ - Catch attribute access failing with any exception
+ - Check that the attribute is a callable object
+
+ Returns the method or None.
+ """
+ if inspect.isclass(obj):
+ return None
+
+ try:
+ canary = getattr(obj, '_ipython_canary_method_should_not_exist_', None)
+ except Exception:
+ return None
+
+ if canary is not None:
+ # It claimed to have an attribute it should never have
+ return None
+
+ try:
+ m = getattr(obj, name, None)
+ except Exception:
+ return None
+
+ if callable(m):
+ return m
+
+ return None
diff --git a/contrib/python/ipython/py2/IPython/utils/io.py b/contrib/python/ipython/py2/IPython/utils/io.py
index 036d6e3926..817ecff278 100644
--- a/contrib/python/ipython/py2/IPython/utils/io.py
+++ b/contrib/python/ipython/py2/IPython/utils/io.py
@@ -14,19 +14,19 @@ import atexit
import os
import sys
import tempfile
-import warnings
+import warnings
from warnings import warn
-
-from IPython.utils.decorators import undoc
+
+from IPython.utils.decorators import undoc
from .capture import CapturedIO, capture_output
from .py3compat import string_types, input, PY3
-@undoc
+@undoc
class IOStream:
- def __init__(self, stream, fallback=None):
- warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
- DeprecationWarning, stacklevel=2)
+ def __init__(self, stream, fallback=None):
+ warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
+ DeprecationWarning, stacklevel=2)
if not hasattr(stream,'write') or not hasattr(stream,'flush'):
if fallback is not None:
stream = fallback
@@ -52,8 +52,8 @@ class IOStream:
return tpl.format(mod=cls.__module__, cls=cls.__name__, args=self.stream)
def write(self,data):
- warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
- DeprecationWarning, stacklevel=2)
+ warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
+ DeprecationWarning, stacklevel=2)
try:
self._swrite(data)
except:
@@ -68,8 +68,8 @@ class IOStream:
file=sys.stderr)
def writelines(self, lines):
- warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
- DeprecationWarning, stacklevel=2)
+ warn('IOStream is deprecated since IPython 5.0, use sys.{stdin,stdout,stderr} instead',
+ DeprecationWarning, stacklevel=2)
if isinstance(lines, string_types):
lines = [lines]
for line in lines:
@@ -87,17 +87,17 @@ class IOStream:
pass
# setup stdin/stdout/stderr to sys.stdin/sys.stdout/sys.stderr
-devnull = open(os.devnull, 'w')
+devnull = open(os.devnull, 'w')
atexit.register(devnull.close)
-# 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)
- stdin = IOStream(sys.stdin, fallback=devnull)
- stdout = IOStream(sys.stdout, fallback=devnull)
- stderr = IOStream(sys.stderr, fallback=devnull)
-
+# 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)
+ stdin = IOStream(sys.stdin, fallback=devnull)
+ stdout = IOStream(sys.stdout, fallback=devnull)
+ stderr = IOStream(sys.stderr, fallback=devnull)
+
class Tee(object):
"""A class to duplicate an output stream to stdout/err.
diff --git a/contrib/python/ipython/py2/IPython/utils/path.py b/contrib/python/ipython/py2/IPython/utils/path.py
index fa850812c7..f7b7666642 100644
--- a/contrib/python/ipython/py2/IPython/utils/path.py
+++ b/contrib/python/ipython/py2/IPython/utils/path.py
@@ -72,21 +72,21 @@ def get_long_path_name(path):
def unquote_filename(name, win32=(sys.platform=='win32')):
""" On Windows, remove leading and trailing quotes from filenames.
-
- This function has been deprecated and should not be used any more:
- unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
+
+ This function has been deprecated and should not be used any more:
+ unquoting is now taken care of by :func:`IPython.utils.process.arg_split`.
"""
- warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
+ warn("'unquote_filename' is deprecated since IPython 5.0 and should not "
"be used anymore", DeprecationWarning, stacklevel=2)
if win32:
if name.startswith(("'", '"')) and name.endswith(("'", '"')):
name = name[1:-1]
return name
-
+
def compress_user(path):
"""Reverse of :func:`os.path.expanduser`
- """
+ """
path = py3compat.unicode_to_str(path, sys.getfilesystemencoding())
home = os.path.expanduser('~')
if path.startswith(home):
@@ -101,9 +101,9 @@ def get_py_filename(name, force_win32=None):
"""
name = os.path.expanduser(name)
- if force_win32 is not None:
- warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
- "since IPython 5.0 and should not be used anymore",
+ if force_win32 is not None:
+ warn("The 'force_win32' argument to 'get_py_filename' is deprecated "
+ "since IPython 5.0 and should not be used anymore",
DeprecationWarning, stacklevel=2)
if not os.path.isfile(name) and not name.endswith('.py'):
name += '.py'
diff --git a/contrib/python/ipython/py2/IPython/utils/py3compat.py b/contrib/python/ipython/py2/IPython/utils/py3compat.py
index 88602e5342..4d37054559 100644
--- a/contrib/python/ipython/py2/IPython/utils/py3compat.py
+++ b/contrib/python/ipython/py2/IPython/utils/py3compat.py
@@ -6,7 +6,7 @@ import sys
import re
import shutil
import types
-import platform
+import platform
from .encoding import DEFAULT_ENCODING
@@ -293,7 +293,7 @@ else:
PY2 = not PY3
-PYPY = platform.python_implementation() == "PyPy"
+PYPY = platform.python_implementation() == "PyPy"
def annotate(**kwargs):
diff --git a/contrib/python/ipython/py2/IPython/utils/terminal.py b/contrib/python/ipython/py2/IPython/utils/terminal.py
index e92c410c79..397a3e86fb 100644
--- a/contrib/python/ipython/py2/IPython/utils/terminal.py
+++ b/contrib/python/ipython/py2/IPython/utils/terminal.py
@@ -11,16 +11,16 @@ Authors:
from __future__ import absolute_import
-# Copyright (c) IPython Development Team.
-# Distributed under the terms of the Modified BSD License.
+# Copyright (c) IPython Development Team.
+# Distributed under the terms of the Modified BSD License.
import os
import sys
import warnings
-try:
- from shutil import get_terminal_size as _get_terminal_size
-except ImportError:
- # use backport on Python 2
+try:
+ from shutil import get_terminal_size as _get_terminal_size
+except ImportError:
+ # use backport on Python 2
try:
from backports.shutil_get_terminal_size import get_terminal_size as _get_terminal_size
except ImportError:
@@ -121,5 +121,5 @@ def freeze_term_title():
ignore_termtitle = True
-def get_terminal_size(defaultx=80, defaulty=25):
- return _get_terminal_size((defaultx, defaulty))
+def get_terminal_size(defaultx=80, defaulty=25):
+ return _get_terminal_size((defaultx, defaulty))
diff --git a/contrib/python/ipython/py2/IPython/utils/text.py b/contrib/python/ipython/py2/IPython/utils/text.py
index 5ed1a845e3..63588fb322 100644
--- a/contrib/python/ipython/py2/IPython/utils/text.py
+++ b/contrib/python/ipython/py2/IPython/utils/text.py
@@ -14,11 +14,11 @@ import re
import sys
import textwrap
from string import Formatter
-try:
- from pathlib import Path
-except ImportError:
- # Python 2 backport
- from pathlib2 import Path
+try:
+ from pathlib import Path
+except ImportError:
+ # Python 2 backport
+ from pathlib2 import Path
from IPython.testing.skipdoctest import skip_doctest_py3, skip_doctest
from IPython.utils import py3compat
@@ -72,7 +72,7 @@ class LSString(str):
try:
return self.__paths
except AttributeError:
- self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
+ self.__paths = [Path(p) for p in self.split('\n') if os.path.exists(p)]
return self.__paths
p = paths = property(get_paths)
@@ -130,7 +130,7 @@ class SList(list):
try:
return self.__paths
except AttributeError:
- self.__paths = [Path(p) for p in self if os.path.exists(p)]
+ self.__paths = [Path(p) for p in self if os.path.exists(p)]
return self.__paths
p = paths = property(get_paths)
diff --git a/contrib/python/ipython/py2/IPython/utils/tokenutil.py b/contrib/python/ipython/py2/IPython/utils/tokenutil.py
index f52d3b7658..e01f5e7b32 100644
--- a/contrib/python/ipython/py2/IPython/utils/tokenutil.py
+++ b/contrib/python/ipython/py2/IPython/utils/tokenutil.py
@@ -31,7 +31,7 @@ def line_at_cursor(cell, cursor_pos=0):
Parameters
----------
- cell: str
+ cell: str
multiline block of text
cursor_pos: integer
the cursor position
diff --git a/contrib/python/ipython/py2/IPython/utils/warn.py b/contrib/python/ipython/py2/IPython/utils/warn.py
index dd4852227b..ae5424a038 100644
--- a/contrib/python/ipython/py2/IPython/utils/warn.py
+++ b/contrib/python/ipython/py2/IPython/utils/warn.py
@@ -9,17 +9,17 @@ Utilities for warnings. Shoudn't we just use the built in warnings module.
from __future__ import print_function
import sys
-import warnings
+import warnings
-warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
+warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
def warn(msg,level=2,exit_val=1):
- """Deprecated
-
- Standard warning printer. Gives formatting consistency.
+ """Deprecated
- Output is sent to sys.stderr.
+ Standard warning printer. Gives formatting consistency.
+ Output is sent to sys.stderr.
+
Options:
-level(2): allows finer control:
@@ -31,35 +31,35 @@ def warn(msg,level=2,exit_val=1):
-exit_val (1): exit value returned by sys.exit() for a level 4
warning. Ignored for all other levels."""
-
- warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
+
+ warnings.warn("The module IPython.utils.warn is deprecated since IPython 4.0, use the standard warnings module instead", DeprecationWarning)
if level>0:
header = ['','','WARNING: ','ERROR: ','FATAL ERROR: ']
- print(header[level], msg, sep='', file=sys.stderr)
+ print(header[level], msg, sep='', file=sys.stderr)
if level == 4:
- print('Exiting.\n', file=sys.stderr)
+ print('Exiting.\n', file=sys.stderr)
sys.exit(exit_val)
def info(msg):
- """Deprecated
-
- Equivalent to warn(msg,level=1)."""
+ """Deprecated
+
+ Equivalent to warn(msg,level=1)."""
warn(msg,level=1)
def error(msg):
- """Deprecated
-
- Equivalent to warn(msg,level=3)."""
+ """Deprecated
+
+ Equivalent to warn(msg,level=3)."""
warn(msg,level=3)
def fatal(msg,exit_val=1):
- """Deprecated
-
- Equivalent to warn(msg,exit_val=exit_val,level=4)."""
+ """Deprecated
+
+ Equivalent to warn(msg,exit_val=exit_val,level=4)."""
warn(msg,exit_val=exit_val,level=4)