diff options
author | Mikhail Borisov <borisov.mikhail@gmail.com> | 2022-02-10 16:45:40 +0300 |
---|---|---|
committer | Daniil Cherednik <dcherednik@yandex-team.ru> | 2022-02-10 16:45:40 +0300 |
commit | 5d50718e66d9c037dc587a0211110b7d25a66185 (patch) | |
tree | e98df59de24d2ef7c77baed9f41e4875a2fef972 /contrib/python/ipython/py2/IPython/terminal | |
parent | a6a92afe03e02795227d2641b49819b687f088f8 (diff) | |
download | ydb-5d50718e66d9c037dc587a0211110b7d25a66185.tar.gz |
Restoring authorship annotation for Mikhail Borisov <borisov.mikhail@gmail.com>. Commit 2 of 2.
Diffstat (limited to 'contrib/python/ipython/py2/IPython/terminal')
4 files changed, 741 insertions, 741 deletions
diff --git a/contrib/python/ipython/py2/IPython/terminal/console.py b/contrib/python/ipython/py2/IPython/terminal/console.py index 981ee46b17..65571a7572 100644 --- a/contrib/python/ipython/py2/IPython/terminal/console.py +++ b/contrib/python/ipython/py2/IPython/terminal/console.py @@ -1,19 +1,19 @@ -""" -Shim to maintain backwards compatibility with old IPython.terminal.console imports. -""" -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -import sys -from warnings import warn - -from IPython.utils.shimmodule import ShimModule, ShimWarning - +""" +Shim to maintain backwards compatibility with old IPython.terminal.console imports. +""" +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +import sys +from warnings import warn + +from IPython.utils.shimmodule import ShimModule, ShimWarning + warn("The `IPython.terminal.console` package has been deprecated since IPython 4.0. " - "You should import from jupyter_console instead.", ShimWarning) - -# Unconditionally insert the shim into sys.modules so that further import calls -# trigger the custom attribute access above - -sys.modules['IPython.terminal.console'] = ShimModule( - src='IPython.terminal.console', mirror='jupyter_console') + "You should import from jupyter_console instead.", ShimWarning) + +# Unconditionally insert the shim into sys.modules so that further import calls +# trigger the custom attribute access above + +sys.modules['IPython.terminal.console'] = ShimModule( + src='IPython.terminal.console', mirror='jupyter_console') diff --git a/contrib/python/ipython/py2/IPython/terminal/embed.py b/contrib/python/ipython/py2/IPython/terminal/embed.py index 8ff15313dd..5ad70431e4 100644 --- a/contrib/python/ipython/py2/IPython/terminal/embed.py +++ b/contrib/python/ipython/py2/IPython/terminal/embed.py @@ -1,33 +1,33 @@ -# encoding: utf-8 -""" -An embedded IPython shell. -""" -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -from __future__ import with_statement -from __future__ import print_function - -import sys -import warnings - -from IPython.core import ultratb, compilerop +# encoding: utf-8 +""" +An embedded IPython shell. +""" +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +from __future__ import with_statement +from __future__ import print_function + +import sys +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.magic import Magics, magics_class, line_magic from IPython.core.interactiveshell import DummyMod, InteractiveShell -from IPython.terminal.interactiveshell import TerminalInteractiveShell -from IPython.terminal.ipapp import load_default_config - -from traitlets import Bool, CBool, Unicode -from IPython.utils.io import ask_yes_no - -class KillEmbeded(Exception):pass - -# This is an additional magic that is exposed in embedded shells. -@magics_class -class EmbeddedMagics(Magics): - - @line_magic +from IPython.terminal.interactiveshell import TerminalInteractiveShell +from IPython.terminal.ipapp import load_default_config + +from traitlets import Bool, CBool, Unicode +from IPython.utils.io import ask_yes_no + +class KillEmbeded(Exception):pass + +# This is an additional magic that is exposed in embedded shells. +@magics_class +class EmbeddedMagics(Magics): + + @line_magic @magic_arguments.magic_arguments() @magic_arguments.argument('-i', '--instance', action='store_true', help='Kill instance instead of call location') @@ -35,10 +35,10 @@ class EmbeddedMagics(Magics): help='Also exit the current session') @magic_arguments.argument('-y', '--yes', action='store_true', help='Do not ask confirmation') - def kill_embedded(self, parameter_s=''): + def kill_embedded(self, parameter_s=''): """%kill_embedded : deactivate for good the current embedded IPython - - This function (after asking for confirmation) sets an internal flag so + + This function (after asking for confirmation) sets an internal flag so that an embedded IPython will never activate again for the given call location. This is useful to permanently disable a shell that is being called inside a loop: once you've figured out what you needed from it, @@ -60,8 +60,8 @@ class EmbeddedMagics(Magics): This was the default behavior before IPython 5.2 - """ - + """ + args = magic_arguments.parse_argstring(self.kill_embedded, parameter_s) print(args) if args.instance: @@ -85,38 +85,38 @@ class EmbeddedMagics(Magics): self.shell.embedded_active = False print("This embedded IPython call location will not reactivate anymore " "once you exit.") - + if args.exit: # Ask-exit does not really ask, it just set internals flags to exit # on next loop. self.shell.ask_exit() - - - @line_magic - def exit_raise(self, parameter_s=''): - """%exit_raise Make the current embedded kernel exit and raise and exception. - - This function sets an internal flag so that an embedded IPython will - raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is - useful to permanently exit a loop that create IPython embed instance. - """ - - self.shell.should_raise = True - self.shell.ask_exit() - - - -class InteractiveShellEmbed(TerminalInteractiveShell): - - dummy_mode = Bool(False) - exit_msg = Unicode('') - embedded = CBool(True) - should_raise = CBool(False) - # Like the base class display_banner is not configurable, but here it - # is True by default. - display_banner = CBool(True) - exit_msg = Unicode() - + + + @line_magic + def exit_raise(self, parameter_s=''): + """%exit_raise Make the current embedded kernel exit and raise and exception. + + This function sets an internal flag so that an embedded IPython will + raise a `IPython.terminal.embed.KillEmbeded` Exception on exit, and then exit the current I. This is + useful to permanently exit a loop that create IPython embed instance. + """ + + self.shell.should_raise = True + self.shell.ask_exit() + + + +class InteractiveShellEmbed(TerminalInteractiveShell): + + dummy_mode = Bool(False) + exit_msg = Unicode('') + embedded = CBool(True) + should_raise = CBool(False) + # Like the base class display_banner is not configurable, but here it + # is True by default. + 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" @@ -144,140 +144,140 @@ class InteractiveShellEmbed(TerminalInteractiveShell): InteractiveShellEmbed._inactive_locations.add( self._call_location_id) - def __init__(self, **kw): - if kw.get('user_global_ns', None) is not None: + def __init__(self, **kw): + if kw.get('user_global_ns', None) is not None: raise DeprecationWarning( "Key word argument `user_global_ns` has been replaced by `user_module` since IPython 4.0.") - + clid = kw.pop('_init_location_id', None) if not clid: 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 - # trapped - sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, - mode=self.xmode, - call_pdb=self.pdb) - - def init_sys_modules(self): + super(InteractiveShellEmbed,self).__init__(**kw) + + # don't use the ipython crash handler so that user exceptions aren't + # trapped + sys.excepthook = ultratb.FormattedTB(color_scheme=self.colors, + mode=self.xmode, + call_pdb=self.pdb) + + def init_sys_modules(self): """ Explicitly overwrite :mod:`IPython.core.interactiveshell` to do nothing. """ - pass - - def init_magics(self): - super(InteractiveShellEmbed, self).init_magics() - self.register_magics(EmbeddedMagics) - - def __call__(self, header='', local_ns=None, module=None, dummy=None, + pass + + def init_magics(self): + super(InteractiveShellEmbed, self).init_magics() + self.register_magics(EmbeddedMagics) + + def __call__(self, header='', local_ns=None, module=None, dummy=None, stack_depth=1, global_ns=None, compile_flags=None, **kw): - """Activate the interactive interpreter. - - __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start - the interpreter shell with the given local and global namespaces, and - optionally print a header string at startup. - - The shell can be globally activated/deactivated using the - dummy_mode attribute. This allows you to turn off a shell used - for debugging globally. - - However, *each* time you call the shell you can override the current - state of dummy_mode with the optional keyword parameter 'dummy'. For - example, if you set dummy mode on with IPShell.dummy_mode = True, you - can still have a specific call work by making it as IPShell(dummy=False). - """ - + """Activate the interactive interpreter. + + __call__(self,header='',local_ns=None,module=None,dummy=None) -> Start + the interpreter shell with the given local and global namespaces, and + optionally print a header string at startup. + + The shell can be globally activated/deactivated using the + dummy_mode attribute. This allows you to turn off a shell used + for debugging globally. + + However, *each* time you call the shell you can override the current + state of dummy_mode with the optional keyword parameter 'dummy'. For + example, if you set dummy mode on with IPShell.dummy_mode = True, you + can still have a specific call work by making it as IPShell(dummy=False). + """ + # we are called, set the underlying interactiveshell not to exit. self.keep_running = True - # If the user has turned it off, go away + # If the user has turned it off, go away clid = kw.pop('_call_location_id', None) if not clid: frame = sys._getframe(1) clid = '%s:%s' % (frame.f_code.co_filename, frame.f_lineno) self._call_location_id = clid - if not self.embedded_active: - return - - # Normal exits from interactive mode set this flag, so the shell can't - # re-enter (it checks this variable at the start of interactive mode). - self.exit_now = False - - # Allow the dummy parameter to override the global __dummy_mode - if dummy or (dummy != 0 and self.dummy_mode): - return - - # self.banner is auto computed - if header: - self.old_banner2 = self.banner2 - self.banner2 = self.banner2 + '\n' + header + '\n' - else: - self.old_banner2 = '' - + if not self.embedded_active: + return + + # Normal exits from interactive mode set this flag, so the shell can't + # re-enter (it checks this variable at the start of interactive mode). + self.exit_now = False + + # Allow the dummy parameter to override the global __dummy_mode + if dummy or (dummy != 0 and self.dummy_mode): + return + + # self.banner is auto computed + if header: + self.old_banner2 = self.banner2 + self.banner2 = self.banner2 + '\n' + header + '\n' + else: + self.old_banner2 = '' + 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, - global_ns=global_ns, compile_flags=compile_flags) - - self.banner2 = self.old_banner2 - - if self.exit_msg is not None: - print(self.exit_msg) - - if self.should_raise: - raise KillEmbeded('Embedded IPython raising error, as user requested.') - - - def mainloop(self, local_ns=None, module=None, stack_depth=0, - display_banner=None, global_ns=None, compile_flags=None): - """Embeds IPython into a running python program. - - Parameters - ---------- - - local_ns, module - Working local namespace (a dict) and module (a module or similar - object). If given as None, they are automatically taken from the scope - where the shell was called, so that program variables become visible. - - stack_depth : int - How many levels in the stack to go to looking for namespaces (when - local_ns or module is None). This allows an intermediate caller to - make sure that this function gets the namespace from the intended - level in the stack. By default (0) it will get its locals and globals - from the immediate caller. - - compile_flags - A bit field identifying the __future__ features - that are enabled, as passed to the builtin :func:`compile` function. - If given as None, they are automatically taken from the scope where - the shell was called. - - """ - - if (global_ns is not None) and (module is None): + # 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, + global_ns=global_ns, compile_flags=compile_flags) + + self.banner2 = self.old_banner2 + + if self.exit_msg is not None: + print(self.exit_msg) + + if self.should_raise: + raise KillEmbeded('Embedded IPython raising error, as user requested.') + + + def mainloop(self, local_ns=None, module=None, stack_depth=0, + display_banner=None, global_ns=None, compile_flags=None): + """Embeds IPython into a running python program. + + Parameters + ---------- + + local_ns, module + Working local namespace (a dict) and module (a module or similar + object). If given as None, they are automatically taken from the scope + where the shell was called, so that program variables become visible. + + stack_depth : int + How many levels in the stack to go to looking for namespaces (when + local_ns or module is None). This allows an intermediate caller to + make sure that this function gets the namespace from the intended + level in the stack. By default (0) it will get its locals and globals + from the immediate caller. + + compile_flags + A bit field identifying the __future__ features + that are enabled, as passed to the builtin :func:`compile` function. + If given as None, they are automatically taken from the scope where + the shell was called. + + """ + + 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) - # 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): - call_frame = sys._getframe(stack_depth).f_back - - if local_ns is None: - local_ns = call_frame.f_locals - if module is None: - global_ns = call_frame.f_globals + # 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): + call_frame = sys._getframe(stack_depth).f_back + + if local_ns is None: + 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: @@ -286,110 +286,110 @@ class InteractiveShellEmbed(TerminalInteractiveShell): ) module = DummyMod() module.__dict__ = global_ns - if compile_flags is None: - compile_flags = (call_frame.f_code.co_flags & - compilerop.PyCF_MASK) - - # Save original namespace and module so we can restore them after - # embedding; otherwise the shell doesn't shut down correctly. - orig_user_module = self.user_module - orig_user_ns = self.user_ns - orig_compile_flags = self.compile.flags - - # Update namespaces and fire up interpreter - - # The global one is easy, we can just throw it in - if module is not None: - self.user_module = module - - # But the user/local one is tricky: ipython needs it to store internal - # data, but we also need the locals. We'll throw our hidden variables - # like _ih and get_ipython() into the local namespace, but delete them - # later. - if local_ns is not None: - reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} - self.user_ns = reentrant_local_ns - self.init_user_ns() - - # Compiler flags - if compile_flags is not None: - self.compile.flags = compile_flags - - # make sure the tab-completer has the correct frame information, so it - # actually completes using the frame's locals/globals - self.set_completer_frame() - - with self.builtin_trap, self.display_trap: + if compile_flags is None: + compile_flags = (call_frame.f_code.co_flags & + compilerop.PyCF_MASK) + + # Save original namespace and module so we can restore them after + # embedding; otherwise the shell doesn't shut down correctly. + orig_user_module = self.user_module + orig_user_ns = self.user_ns + orig_compile_flags = self.compile.flags + + # Update namespaces and fire up interpreter + + # The global one is easy, we can just throw it in + if module is not None: + self.user_module = module + + # But the user/local one is tricky: ipython needs it to store internal + # data, but we also need the locals. We'll throw our hidden variables + # like _ih and get_ipython() into the local namespace, but delete them + # later. + if local_ns is not None: + reentrant_local_ns = {k: v for (k, v) in local_ns.items() if k not in self.user_ns_hidden.keys()} + self.user_ns = reentrant_local_ns + self.init_user_ns() + + # Compiler flags + if compile_flags is not None: + self.compile.flags = compile_flags + + # make sure the tab-completer has the correct frame information, so it + # actually completes using the frame's locals/globals + self.set_completer_frame() + + with self.builtin_trap, self.display_trap: self.interact() - - # now, purge out the local namespace of IPython's hidden variables. - if local_ns is not None: - local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) - - - # Restore original namespace so shell can shut down when we exit. - self.user_module = orig_user_module - self.user_ns = orig_user_ns - self.compile.flags = orig_compile_flags - - -def embed(**kwargs): - """Call this to embed IPython at the current point in your program. - - The first invocation of this will create an :class:`InteractiveShellEmbed` - instance and then call it. Consecutive calls just call the already - created instance. - - If you don't want the kernel to initialize the namespace - from the scope of the surrounding function, - and/or you want to load full IPython configuration, - you probably want `IPython.start_ipython()` instead. - - Here is a simple example:: - - from IPython import embed - a = 10 - b = 20 - embed(header='First time') - c = 30 - d = 40 - embed() - - Full customization can be done by passing a :class:`Config` in as the - config argument. - """ - config = kwargs.get('config') - header = kwargs.pop('header', u'') - compile_flags = kwargs.pop('compile_flags', None) - if config is None: - config = load_default_config() - config.InteractiveShellEmbed = config.TerminalInteractiveShell - kwargs['config'] = config - #save ps1/ps2 if defined - ps1 = None - ps2 = None - try: - ps1 = sys.ps1 - ps2 = sys.ps2 - except AttributeError: - pass - #save previous instance - saved_shell_instance = InteractiveShell._instance - if saved_shell_instance is not None: - cls = type(saved_shell_instance) - cls.clear_instance() + + # now, purge out the local namespace of IPython's hidden variables. + if local_ns is not None: + local_ns.update({k: v for (k, v) in self.user_ns.items() if k not in self.user_ns_hidden.keys()}) + + + # Restore original namespace so shell can shut down when we exit. + self.user_module = orig_user_module + self.user_ns = orig_user_ns + self.compile.flags = orig_compile_flags + + +def embed(**kwargs): + """Call this to embed IPython at the current point in your program. + + The first invocation of this will create an :class:`InteractiveShellEmbed` + instance and then call it. Consecutive calls just call the already + created instance. + + If you don't want the kernel to initialize the namespace + from the scope of the surrounding function, + and/or you want to load full IPython configuration, + you probably want `IPython.start_ipython()` instead. + + Here is a simple example:: + + from IPython import embed + a = 10 + b = 20 + embed(header='First time') + c = 30 + d = 40 + embed() + + Full customization can be done by passing a :class:`Config` in as the + config argument. + """ + config = kwargs.get('config') + header = kwargs.pop('header', u'') + compile_flags = kwargs.pop('compile_flags', None) + if config is None: + config = load_default_config() + config.InteractiveShellEmbed = config.TerminalInteractiveShell + kwargs['config'] = config + #save ps1/ps2 if defined + ps1 = None + ps2 = None + try: + ps1 = sys.ps1 + ps2 = sys.ps2 + except AttributeError: + pass + #save previous instance + saved_shell_instance = InteractiveShell._instance + if saved_shell_instance is not None: + cls = type(saved_shell_instance) + cls.clear_instance() 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, _call_location_id='%s:%s' % (frame.f_code.co_filename, frame.f_lineno)) - InteractiveShellEmbed.clear_instance() - #restore previous instance - if saved_shell_instance is not None: - cls = type(saved_shell_instance) - cls.clear_instance() - for subclass in cls._walk_mro(): - subclass._instance = saved_shell_instance - if ps1 is not None: - sys.ps1 = ps1 - sys.ps2 = ps2 + InteractiveShellEmbed.clear_instance() + #restore previous instance + if saved_shell_instance is not None: + cls = type(saved_shell_instance) + cls.clear_instance() + for subclass in cls._walk_mro(): + subclass._instance = saved_shell_instance + if ps1 is not None: + sys.ps1 = ps1 + sys.ps2 = ps2 diff --git a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py index e80f8c1503..f67cc6b502 100644 --- a/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py +++ b/contrib/python/ipython/py2/IPython/terminal/interactiveshell.py @@ -1,18 +1,18 @@ """IPython terminal interface using prompt_toolkit""" -from __future__ import print_function - -import os -import sys +from __future__ import print_function + +import os +import sys import warnings from warnings import warn - -from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC + +from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC 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 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) @@ -22,7 +22,7 @@ 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 @@ -59,23 +59,23 @@ _style_overrides_linux = { -def get_default_editor(): - try: - ed = os.environ['EDITOR'] +def get_default_editor(): + try: + ed = os.environ['EDITOR'] if not PY3: - ed = ed.decode() - return ed - except KeyError: - pass - except UnicodeError: - warn("$EDITOR environment variable is not pure ASCII. Using platform " - "default editor.") - - if os.name == 'posix': - return 'vi' # the only one guaranteed to be there! - else: - return 'notepad' # same in Windows! - + ed = ed.decode() + return ed + except KeyError: + pass + except UnicodeError: + warn("$EDITOR environment variable is not pure ASCII. Using platform " + "default editor.") + + if os.name == 'posix': + return 'vi' # the only one guaranteed to be there! + else: + return 'notepad' # same in Windows! + # conservatively check for tty # overridden streams can result in things like: # - sys.stdin = None @@ -87,116 +87,116 @@ for _name in ('stdin', 'stdout', 'stderr'): break else: _is_tty = True - - + + _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) - + def _space_for_menu_changed(self, old, new): self._update_layout() - + pt_cli = None debugger_history = None _pt_app = None - + 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. - + 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) - + @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) - + 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) - + # 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) - + @observe('highlighting_style') @observe('colors') def _highlighting_style_changed(self, change): self.refresh_style() - + 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) - + 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) - + prompts_class = Type(Prompts, help='Class used to generate Prompt token for prompt_toolkit').tag(config=True) - + prompts = Instance(Prompts) - + @default('prompts') def _prompts_default(self): return self.prompts_class(self) - + @observe('prompts') def _(self, change): self._update_layout() - + @default('displayhook_class') def _displayhook_class_default(self): return RichPromptDisplayHook - + 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) - + highlight_matching_brackets = Bool(True, help="Highlight matching brackets.", ).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." @@ -210,14 +210,14 @@ class TerminalInteractiveShell(InteractiveShell): 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. @@ -233,13 +233,13 @@ class TerminalInteractiveShell(InteractiveShell): return isp.source_reset() self.prompt_for_code = prompt return - + # 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"" @@ -250,12 +250,12 @@ class TerminalInteractiveShell(InteractiveShell): 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()) - + def patch_stdout(**kwargs): return self.pt_cli.patch_stdout_context(**kwargs) @@ -274,13 +274,13 @@ class TerminalInteractiveShell(InteractiveShell): 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 - + We need that to add style for prompt ... etc. - """ + """ style_overrides = {} if name_or_cls == 'legacy': legacy = self.colors.lower() @@ -336,9 +336,9 @@ class TerminalInteractiveShell(InteractiveShell): 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 @@ -350,7 +350,7 @@ class TerminalInteractiveShell(InteractiveShell): '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( @@ -358,20 +358,20 @@ class TerminalInteractiveShell(InteractiveShell): 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): if sys.version_info >= (3, 6): # Since PEP 528, Python uses the unicode APIs for the Windows @@ -379,36 +379,36 @@ class TerminalInteractiveShell(InteractiveShell): return import win_unicode_console - + if PY3: win_unicode_console.enable() - else: + else: # 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') - + self.base.write(s) - + 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) - + def init_io(self): if sys.platform not in {'win32', 'cli'}: return - + self.enable_win_unicode_console() - + 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 @@ -418,37 +418,37 @@ class TerminalInteractiveShell(InteractiveShell): 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_alias(self): - # The parent class defines aliases that can be safely used with any - # frontend. - super(TerminalInteractiveShell, self).init_alias() - - # Now define aliases that only make sense on the terminal, because they - # need direct access to the console in a way that we can't emulate in - # GUI or web frontend - if os.name == 'posix': + + def init_alias(self): + # The parent class defines aliases that can be safely used with any + # frontend. + super(TerminalInteractiveShell, self).init_alias() + + # Now define aliases that only make sense on the terminal, because they + # need direct access to the console in a way that we can't emulate in + # GUI or web frontend + if os.name == 'posix': for cmd in ['clear', 'more', 'less', 'man']: 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 - + self.debugger_history = InMemoryHistory() - + def ask_exit(self): self.keep_running = False - + rl_next_input = None - + def pre_prompt(self): if self.rl_next_input: # We can't set the buffer here, because it will be reset just after @@ -464,34 +464,34 @@ class TerminalInteractiveShell(InteractiveShell): # directly here. set_doc() self.rl_next_input = None - + 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) - + self.keep_running = True while self.keep_running: print(self.separate_in, end='') - - try: + + 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() - - else: + + 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: - try: + try: self.interact() break except KeyboardInterrupt as e: @@ -503,12 +503,12 @@ class TerminalInteractiveShell(InteractiveShell): # https://github.com/ipython/ipython/pull/9867 if hasattr(self, '_eventloop'): self._eventloop.stop() - + _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: @@ -516,24 +516,24 @@ class TerminalInteractiveShell(InteractiveShell): get_inputhook_name_and_func(gui) else: self.active_eventloop = self._inputhook = None - + # 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 - + tokens = self.prompts.rewrite_prompt_tokens() if self.pt_cli: self.pt_cli.print_tokens(tokens) print(cmd) - else: + else: 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""" @@ -544,9 +544,9 @@ class TerminalInteractiveShell(InteractiveShell): self.prompts = self._prompts_before self._prompts_before = None self._update_layout() - - + + InteractiveShellABC.register(TerminalInteractiveShell) - + 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 f8136ef0b6..6b25aaa3e3 100755 --- a/contrib/python/ipython/py2/IPython/terminal/ipapp.py +++ b/contrib/python/ipython/py2/IPython/terminal/ipapp.py @@ -1,190 +1,190 @@ -#!/usr/bin/env python -# encoding: utf-8 -""" -The :class:`~IPython.core.application.Application` object for the command -line :command:`ipython` program. -""" - -# Copyright (c) IPython Development Team. -# Distributed under the terms of the Modified BSD License. - -from __future__ import absolute_import -from __future__ import print_function - -import logging -import os -import sys +#!/usr/bin/env python +# encoding: utf-8 +""" +The :class:`~IPython.core.application.Application` object for the command +line :command:`ipython` program. +""" + +# Copyright (c) IPython Development Team. +# Distributed under the terms of the Modified BSD License. + +from __future__ import absolute_import +from __future__ import print_function + +import logging +import os +import sys import warnings - -from traitlets.config.loader import Config -from traitlets.config.application import boolean_flag, catch_config_error, Application -from IPython.core import release -from IPython.core import usage -from IPython.core.completer import IPCompleter -from IPython.core.crashhandler import CrashHandler -from IPython.core.formatters import PlainTextFormatter -from IPython.core.history import HistoryManager -from IPython.core.application import ( - ProfileDir, BaseIPythonApplication, base_flags, base_aliases -) -from IPython.core.magics import ScriptMagics -from IPython.core.shellapp import ( - InteractiveShellApp, shell_flags, shell_aliases -) -from IPython.extensions.storemagic import StoreMagics + +from traitlets.config.loader import Config +from traitlets.config.application import boolean_flag, catch_config_error, Application +from IPython.core import release +from IPython.core import usage +from IPython.core.completer import IPCompleter +from IPython.core.crashhandler import CrashHandler +from IPython.core.formatters import PlainTextFormatter +from IPython.core.history import HistoryManager +from IPython.core.application import ( + ProfileDir, BaseIPythonApplication, base_flags, base_aliases +) +from IPython.core.magics import ScriptMagics +from IPython.core.shellapp import ( + InteractiveShellApp, shell_flags, shell_aliases +) +from IPython.extensions.storemagic import StoreMagics from .interactiveshell import TerminalInteractiveShell -from IPython.paths import get_ipython_dir -from traitlets import ( +from IPython.paths import get_ipython_dir +from traitlets import ( Bool, List, Dict, default, observe, Type -) - -#----------------------------------------------------------------------------- -# Globals, utilities and helpers -#----------------------------------------------------------------------------- - -_examples = """ -ipython --matplotlib # enable matplotlib integration -ipython --matplotlib=qt # enable matplotlib integration with qt4 backend - -ipython --log-level=DEBUG # set logging to DEBUG -ipython --profile=foo # start with profile foo - -ipython profile create foo # create profile foo w/ default config files -ipython help profile # show the help for the profile subcmd - -ipython locate # print the path to the IPython directory -ipython locate profile foo # print the path to the directory for profile `foo` -""" - -#----------------------------------------------------------------------------- -# Crash handler for this application -#----------------------------------------------------------------------------- - -class IPAppCrashHandler(CrashHandler): - """sys.excepthook for IPython itself, leaves a detailed report on disk.""" - - def __init__(self, app): - contact_name = release.author - contact_email = release.author_email - bug_tracker = 'https://github.com/ipython/ipython/issues' - super(IPAppCrashHandler,self).__init__( - app, contact_name, contact_email, bug_tracker - ) - - def make_report(self,traceback): - """Return a string containing a crash report.""" - - sec_sep = self.section_sep - # Start with parent report - report = [super(IPAppCrashHandler, self).make_report(traceback)] - # Add interactive-specific info we may have - rpt_add = report.append - try: - rpt_add(sec_sep+"History of session input:") - for line in self.app.shell.user_ns['_ih']: - rpt_add(line) - rpt_add('\n*** Last line of input (may not be in above history):\n') - rpt_add(self.app.shell._last_input_line+'\n') - except: - pass - - return ''.join(report) - -#----------------------------------------------------------------------------- -# Aliases and Flags -#----------------------------------------------------------------------------- -flags = dict(base_flags) -flags.update(shell_flags) -frontend_flags = {} -addflag = lambda *args: frontend_flags.update(boolean_flag(*args)) -addflag('autoedit-syntax', 'TerminalInteractiveShell.autoedit_syntax', - 'Turn on auto editing of files with syntax errors.', - 'Turn off auto editing of files with syntax errors.' -) +) + +#----------------------------------------------------------------------------- +# Globals, utilities and helpers +#----------------------------------------------------------------------------- + +_examples = """ +ipython --matplotlib # enable matplotlib integration +ipython --matplotlib=qt # enable matplotlib integration with qt4 backend + +ipython --log-level=DEBUG # set logging to DEBUG +ipython --profile=foo # start with profile foo + +ipython profile create foo # create profile foo w/ default config files +ipython help profile # show the help for the profile subcmd + +ipython locate # print the path to the IPython directory +ipython locate profile foo # print the path to the directory for profile `foo` +""" + +#----------------------------------------------------------------------------- +# Crash handler for this application +#----------------------------------------------------------------------------- + +class IPAppCrashHandler(CrashHandler): + """sys.excepthook for IPython itself, leaves a detailed report on disk.""" + + def __init__(self, app): + contact_name = release.author + contact_email = release.author_email + bug_tracker = 'https://github.com/ipython/ipython/issues' + super(IPAppCrashHandler,self).__init__( + app, contact_name, contact_email, bug_tracker + ) + + def make_report(self,traceback): + """Return a string containing a crash report.""" + + sec_sep = self.section_sep + # Start with parent report + report = [super(IPAppCrashHandler, self).make_report(traceback)] + # Add interactive-specific info we may have + rpt_add = report.append + try: + rpt_add(sec_sep+"History of session input:") + for line in self.app.shell.user_ns['_ih']: + rpt_add(line) + rpt_add('\n*** Last line of input (may not be in above history):\n') + rpt_add(self.app.shell._last_input_line+'\n') + except: + pass + + return ''.join(report) + +#----------------------------------------------------------------------------- +# Aliases and Flags +#----------------------------------------------------------------------------- +flags = dict(base_flags) +flags.update(shell_flags) +frontend_flags = {} +addflag = lambda *args: frontend_flags.update(boolean_flag(*args)) +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('banner', 'TerminalIPythonApp.display_banner', - "Display a banner upon starting IPython.", - "Don't display a banner upon starting IPython." -) -addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', - """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.""", - "Don't prompt the user when exiting." -) -addflag('term-title', 'TerminalInteractiveShell.term_title', - "Enable auto setting the terminal title.", - "Disable auto setting the terminal title." -) -classic_config = Config() -classic_config.InteractiveShell.cache_size = 0 -classic_config.PlainTextFormatter.pprint = False +addflag('banner', 'TerminalIPythonApp.display_banner', + "Display a banner upon starting IPython.", + "Don't display a banner upon starting IPython." +) +addflag('confirm-exit', 'TerminalInteractiveShell.confirm_exit', + """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.""", + "Don't prompt the user when exiting." +) +addflag('term-title', 'TerminalInteractiveShell.term_title', + "Enable auto setting the terminal title.", + "Disable auto setting the terminal 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.InteractiveShell.separate_in = '' -classic_config.InteractiveShell.separate_out = '' -classic_config.InteractiveShell.separate_out2 = '' -classic_config.InteractiveShell.colors = 'NoColor' -classic_config.InteractiveShell.xmode = 'Plain' - -frontend_flags['classic']=( - classic_config, - "Gives IPython a similar feel to the classic Python prompt." -) -# # log doesn't make so much sense this way anymore -# paa('--log','-l', -# action='store_true', dest='InteractiveShell.logstart', -# help="Start logging to the default log file (./ipython_log.py).") -# -# # quick is harder to implement -frontend_flags['quick']=( - {'TerminalIPythonApp' : {'quick' : True}}, - "Enable quick startup with no config files." -) - -frontend_flags['i'] = ( - {'TerminalIPythonApp' : {'force_interact' : True}}, - """If running code from the command line, become interactive afterwards. - It is often useful to follow this with `--` to treat remaining flags as - script arguments. - """ -) -flags.update(frontend_flags) - -aliases = dict(base_aliases) -aliases.update(shell_aliases) - -#----------------------------------------------------------------------------- -# Main classes and functions -#----------------------------------------------------------------------------- - - -class LocateIPythonApp(BaseIPythonApplication): - description = """print the path to the IPython dir""" - subcommands = Dict(dict( - profile=('IPython.core.profileapp.ProfileLocate', - "print the path to an IPython profile directory", - ), - )) - def start(self): - if self.subapp is not None: - return self.subapp.start() - else: - print(self.ipython_dir) - - -class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): - name = u'ipython' - description = usage.cl_usage - crash_handler_class = IPAppCrashHandler - examples = _examples - - flags = Dict(flags) - aliases = Dict(aliases) - classes = List() +classic_config.InteractiveShell.separate_in = '' +classic_config.InteractiveShell.separate_out = '' +classic_config.InteractiveShell.separate_out2 = '' +classic_config.InteractiveShell.colors = 'NoColor' +classic_config.InteractiveShell.xmode = 'Plain' + +frontend_flags['classic']=( + classic_config, + "Gives IPython a similar feel to the classic Python prompt." +) +# # log doesn't make so much sense this way anymore +# paa('--log','-l', +# action='store_true', dest='InteractiveShell.logstart', +# help="Start logging to the default log file (./ipython_log.py).") +# +# # quick is harder to implement +frontend_flags['quick']=( + {'TerminalIPythonApp' : {'quick' : True}}, + "Enable quick startup with no config files." +) + +frontend_flags['i'] = ( + {'TerminalIPythonApp' : {'force_interact' : True}}, + """If running code from the command line, become interactive afterwards. + It is often useful to follow this with `--` to treat remaining flags as + script arguments. + """ +) +flags.update(frontend_flags) + +aliases = dict(base_aliases) +aliases.update(shell_aliases) + +#----------------------------------------------------------------------------- +# Main classes and functions +#----------------------------------------------------------------------------- + + +class LocateIPythonApp(BaseIPythonApplication): + description = """print the path to the IPython dir""" + subcommands = Dict(dict( + profile=('IPython.core.profileapp.ProfileLocate', + "print the path to an IPython profile directory", + ), + )) + def start(self): + if self.subapp is not None: + return self.subapp.start() + else: + print(self.ipython_dir) + + +class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): + name = u'ipython' + description = usage.cl_usage + crash_handler_class = IPAppCrashHandler + examples = _examples + + flags = Dict(flags) + aliases = Dict(aliases) + classes = List() interactive_shell_class = Type( klass=object, # use default_value otherwise which only allow subclasses. @@ -193,185 +193,185 @@ class TerminalIPythonApp(BaseIPythonApplication, InteractiveShellApp): ).tag(config=True) @default('classes') - def _classes_default(self): - """This has to be in a method, for TerminalIPythonApp to be available.""" - return [ - InteractiveShellApp, # ShellApp comes before TerminalApp, because - self.__class__, # it will also affect subclasses (e.g. QtConsole) - TerminalInteractiveShell, - HistoryManager, - ProfileDir, - PlainTextFormatter, - IPCompleter, - ScriptMagics, - StoreMagics, - ] - - deprecated_subcommands = dict( - qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp', - """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console.""" - ), - notebook=('notebook.notebookapp.NotebookApp', - """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server.""" - ), - console=('jupyter_console.app.ZMQTerminalIPythonApp', - """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console.""" - ), - nbconvert=('nbconvert.nbconvertapp.NbConvertApp', - "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats." - ), - trust=('nbformat.sign.TrustNotebookApp', - "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load." - ), - kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp', - "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications." - ), - ) - subcommands = dict( - profile = ("IPython.core.profileapp.ProfileApp", - "Create and manage IPython profiles." - ), - kernel = ("ipykernel.kernelapp.IPKernelApp", - "Start a kernel without an attached frontend." - ), - locate=('IPython.terminal.ipapp.LocateIPythonApp', - LocateIPythonApp.description - ), - history=('IPython.core.historyapp.HistoryApp', - "Manage the IPython history database." - ), - ) - deprecated_subcommands['install-nbextension'] = ( - "notebook.nbextensions.InstallNBExtensionApp", - "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files" - ) - subcommands.update(deprecated_subcommands) - - # *do* autocreate requested profile, but don't create the config file. - auto_create=Bool(True) - # configurables + def _classes_default(self): + """This has to be in a method, for TerminalIPythonApp to be available.""" + return [ + InteractiveShellApp, # ShellApp comes before TerminalApp, because + self.__class__, # it will also affect subclasses (e.g. QtConsole) + TerminalInteractiveShell, + HistoryManager, + ProfileDir, + PlainTextFormatter, + IPCompleter, + ScriptMagics, + StoreMagics, + ] + + deprecated_subcommands = dict( + qtconsole=('qtconsole.qtconsoleapp.JupyterQtConsoleApp', + """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter Qt Console.""" + ), + notebook=('notebook.notebookapp.NotebookApp', + """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter HTML Notebook Server.""" + ), + console=('jupyter_console.app.ZMQTerminalIPythonApp', + """DEPRECATED, Will be removed in IPython 6.0 : Launch the Jupyter terminal-based Console.""" + ), + nbconvert=('nbconvert.nbconvertapp.NbConvertApp', + "DEPRECATED, Will be removed in IPython 6.0 : Convert notebooks to/from other formats." + ), + trust=('nbformat.sign.TrustNotebookApp', + "DEPRECATED, Will be removed in IPython 6.0 : Sign notebooks to trust their potentially unsafe contents at load." + ), + kernelspec=('jupyter_client.kernelspecapp.KernelSpecApp', + "DEPRECATED, Will be removed in IPython 6.0 : Manage Jupyter kernel specifications." + ), + ) + subcommands = dict( + profile = ("IPython.core.profileapp.ProfileApp", + "Create and manage IPython profiles." + ), + kernel = ("ipykernel.kernelapp.IPKernelApp", + "Start a kernel without an attached frontend." + ), + locate=('IPython.terminal.ipapp.LocateIPythonApp', + LocateIPythonApp.description + ), + history=('IPython.core.historyapp.HistoryApp', + "Manage the IPython history database." + ), + ) + deprecated_subcommands['install-nbextension'] = ( + "notebook.nbextensions.InstallNBExtensionApp", + "DEPRECATED, Will be removed in IPython 6.0 : Install Jupyter notebook extension files" + ) + subcommands.update(deprecated_subcommands) + + # *do* autocreate requested profile, but don't create the config file. + auto_create=Bool(True) + # configurables quick = Bool(False, - help="""Start IPython quickly by skipping the loading of config files.""" + help="""Start IPython quickly by skipping the loading of config files.""" ).tag(config=True) @observe('quick') def _quick_changed(self, change): if change['new']: - self.load_config_file = lambda *a, **kw: None - + self.load_config_file = lambda *a, **kw: None + display_banner = Bool(True, - help="Whether to display a banner upon starting IPython." + help="Whether to display a banner upon starting IPython." ).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. + + # 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, - 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.""" + 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']: - self.interact = True - + self.interact = True + @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: - self.interact = False - - # internal, not-configurable - something_to_run=Bool(False) - - def parse_command_line(self, argv=None): - """override to allow old '-pylab' flag with deprecation warning""" - - argv = sys.argv[1:] if argv is None else argv - - if '-pylab' in argv: - # deprecated `-pylab` given, - # warn and transform into current syntax - argv = argv[:] # copy, don't clobber - idx = argv.index('-pylab') + if new: + self.something_to_run = True + if new and not self.force_interact: + self.interact = False + + # internal, not-configurable + something_to_run=Bool(False) + + def parse_command_line(self, argv=None): + """override to allow old '-pylab' flag with deprecation warning""" + + argv = sys.argv[1:] if argv is None else argv + + if '-pylab' in argv: + # deprecated `-pylab` given, + # warn and transform into current syntax + argv = argv[:] # copy, don't clobber + idx = argv.index('-pylab') warnings.warn("`-pylab` flag has been deprecated.\n" - " Use `--matplotlib <backend>` and import pylab manually.") - argv[idx] = '--pylab' - - return super(TerminalIPythonApp, self).parse_command_line(argv) - - @catch_config_error - def initialize(self, argv=None): - """Do actions after construct, but before starting the app.""" - super(TerminalIPythonApp, self).initialize(argv) - if self.subapp is not None: - # don't bother initializing further, starting subapp - return - # print self.extra_args - if self.extra_args and not self.something_to_run: - self.file_to_run = self.extra_args[0] - self.init_path() - # create the shell - self.init_shell() - # and draw the banner - self.init_banner() - # Now a variety of things that happen after the banner is printed. - self.init_gui_pylab() - self.init_extensions() - self.init_code() - - def init_shell(self): - """initialize the InteractiveShell instance""" - # Create an InteractiveShell instance. - # shell.display_banner should always be False for the terminal - # based app, because we call shell.show_banner() by hand below - # so the banner shows *before* all extension loading stuff. + " Use `--matplotlib <backend>` and import pylab manually.") + argv[idx] = '--pylab' + + return super(TerminalIPythonApp, self).parse_command_line(argv) + + @catch_config_error + def initialize(self, argv=None): + """Do actions after construct, but before starting the app.""" + super(TerminalIPythonApp, self).initialize(argv) + if self.subapp is not None: + # don't bother initializing further, starting subapp + return + # print self.extra_args + if self.extra_args and not self.something_to_run: + self.file_to_run = self.extra_args[0] + self.init_path() + # create the shell + self.init_shell() + # and draw the banner + self.init_banner() + # Now a variety of things that happen after the banner is printed. + self.init_gui_pylab() + self.init_extensions() + self.init_code() + + def init_shell(self): + """initialize the InteractiveShell instance""" + # Create an InteractiveShell instance. + # shell.display_banner should always be False for the terminal + # 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, - ipython_dir=self.ipython_dir, user_ns=self.user_ns) - self.shell.configurables.append(self) - - def init_banner(self): - """optionally display the banner""" - if self.display_banner and self.interact: - self.shell.show_banner() - # Make sure there is a space below the banner. - if self.log_level <= logging.INFO: print() - - def _pylab_changed(self, name, old, new): - """Replace --pylab='inline' with --pylab='auto'""" - if new == 'inline': + ipython_dir=self.ipython_dir, user_ns=self.user_ns) + self.shell.configurables.append(self) + + def init_banner(self): + """optionally display the banner""" + if self.display_banner and self.interact: + self.shell.show_banner() + # Make sure there is a space below the banner. + if self.log_level <= logging.INFO: print() + + def _pylab_changed(self, name, old, new): + """Replace --pylab='inline' with --pylab='auto'""" + if new == 'inline': warnings.warn("'inline' not available as pylab backend, " - "using 'auto' instead.") - self.pylab = 'auto' - - def start(self): - if self.subapp is not None: - return self.subapp.start() - # perform any prexec steps: - if self.interact: - self.log.debug("Starting IPython's mainloop...") - self.shell.mainloop() - else: - self.log.debug("IPython not interactive...") - -def load_default_config(ipython_dir=None): - """Load the default config file from the default ipython_dir. - - This is useful for embedded shells. - """ - if ipython_dir is None: - ipython_dir = get_ipython_dir() - - profile_dir = os.path.join(ipython_dir, 'profile_default') + "using 'auto' instead.") + self.pylab = 'auto' + + def start(self): + if self.subapp is not None: + return self.subapp.start() + # perform any prexec steps: + if self.interact: + self.log.debug("Starting IPython's mainloop...") + self.shell.mainloop() + else: + self.log.debug("IPython not interactive...") + +def load_default_config(ipython_dir=None): + """Load the default config file from the default ipython_dir. + + This is useful for embedded shells. + """ + if ipython_dir is None: + ipython_dir = get_ipython_dir() + + profile_dir = os.path.join(ipython_dir, 'profile_default') app = TerminalIPythonApp() app.config_file_paths.append(profile_dir) app.load_config_file() return app.config - -launch_new_instance = TerminalIPythonApp.launch_instance - - -if __name__ == '__main__': - launch_new_instance() + +launch_new_instance = TerminalIPythonApp.launch_instance + + +if __name__ == '__main__': + launch_new_instance() |