Exemple #1
0
def get_ipython():
    """Get the global InteractiveShell instance.
    
    Returns None if no InteractiveShell instance is registered.
    """
    from yap_ipython.core.interactiveshell import InteractiveShell
    if InteractiveShell.initialized():
        return InteractiveShell.instance()
Exemple #2
0
def clear_output(wait=False):
    """Clear the output of the current cell receiving output.

    Parameters
    ----------
    wait : bool [default: false]
        Wait to clear the output until new output is available to replace it."""
    from yap_ipython.core.interactiveshell import InteractiveShell
    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()
Exemple #3
0
def clear_output(wait=False):
    """Clear the output of the current cell receiving output.

    Parameters
    ----------
    wait : bool [default: false]
        Wait to clear the output until new output is available to replace it."""
    from yap_ipython.core.interactiveshell import InteractiveShell
    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()
Exemple #4
0
def format_display_data(obj, include=None, exclude=None):
    """Return a format data dict for an object.

    By default all format types will be computed.

    Parameters
    ----------
    obj : object
        The Python object whose format data will be computed.

    Returns
    -------
    format_dict : dict
        A dictionary of key/value pairs, one or each format that was
        generated for the object. The keys are the format types, which
        will usually be MIME type strings and the values and JSON'able
        data structure containing the raw data for the representation in
        that format.
    include : list or tuple, optional
        A list of format type strings (MIME types) to include in the
        format data dict. If this is set *only* the format types included
        in this list will be computed.
    exclude : list or tuple, optional
        A list of format type string (MIME types) to exclue in the format
        data dict. If this is set all format types will be computed,
        except for those included in this argument.
    """
    from yap_ipython.core.interactiveshell import InteractiveShell

    return InteractiveShell.instance().display_formatter.format(
        obj, include, exclude)
Exemple #5
0
def format_display_data(obj, include=None, exclude=None):
    """Return a format data dict for an object.

    By default all format types will be computed.

    Parameters
    ----------
    obj : object
        The Python object whose format data will be computed.

    Returns
    -------
    format_dict : dict
        A dictionary of key/value pairs, one or each format that was
        generated for the object. The keys are the format types, which
        will usually be MIME type strings and the values and JSON'able
        data structure containing the raw data for the representation in
        that format.
    include : list or tuple, optional
        A list of format type strings (MIME types) to include in the
        format data dict. If this is set *only* the format types included
        in this list will be computed.
    exclude : list or tuple, optional
        A list of format type string (MIME types) to exclue in the format
        data dict. If this is set all format types will be computed,
        except for those included in this argument.
    """
    from yap_ipython.core.interactiveshell import InteractiveShell

    return InteractiveShell.instance().display_formatter.format(
        obj,
        include,
        exclude
    )
Exemple #6
0
def set_matplotlib_formats(*formats, **kwargs):
    """Select figure formats for the inline backend. Optionally pass quality for JPEG.

    For example, this enables PNG and JPEG output with a JPEG quality of 90%::

        In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)

    To set this in your config files use the following::

        c.InlineBackend.figure_formats = {'png', 'jpeg'}
        c.InlineBackend.print_figure_kwargs.update({'quality' : 90})

    Parameters
    ----------
    *formats : strs
        One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
    **kwargs :
        Keyword args will be relayed to ``figure.canvas.print_figure``.
    """
    from yap_ipython.core.interactiveshell import InteractiveShell
    from yap_ipython.core.pylabtools import select_figure_formats
    # build kwargs, starting with InlineBackend config
    kw = {}
    from yap_kernel.pylab.config import InlineBackend
    cfg = InlineBackend.instance()
    kw.update(cfg.print_figure_kwargs)
    kw.update(**kwargs)
    shell = InteractiveShell.instance()
    select_figure_formats(shell, formats, **kw)
Exemple #7
0
def set_matplotlib_formats(*formats, **kwargs):
    """Select figure formats for the inline backend. Optionally pass quality for JPEG.

    For example, this enables PNG and JPEG output with a JPEG quality of 90%::

        In [1]: set_matplotlib_formats('png', 'jpeg', quality=90)

    To set this in your config files use the following::

        c.InlineBackend.figure_formats = {'png', 'jpeg'}
        c.InlineBackend.print_figure_kwargs.update({'quality' : 90})

    Parameters
    ----------
    *formats : strs
        One or more figure formats to enable: 'png', 'retina', 'jpeg', 'svg', 'pdf'.
    **kwargs :
        Keyword args will be relayed to ``figure.canvas.print_figure``.
    """
    from yap_ipython.core.interactiveshell import InteractiveShell
    from yap_ipython.core.pylabtools import select_figure_formats
    # build kwargs, starting with InlineBackend config
    kw = {}
    from yap_kernel.pylab.config import InlineBackend
    cfg = InlineBackend.instance()
    kw.update(cfg.print_figure_kwargs)
    kw.update(**kwargs)
    shell = InteractiveShell.instance()
    select_figure_formats(shell, formats, **kw)
Exemple #8
0
def crash_handler_lite(etype, evalue, tb):
    """a light excepthook, adding a small message to the usual traceback"""
    traceback.print_exception(etype, evalue, tb)
    
    from yap_ipython.core.interactiveshell import InteractiveShell
    if InteractiveShell.initialized():
        # we are in a Shell environment, give %magic example
        config = "%config "
    else:
        # we are not in a shell, show generic config
        config = "c."
    print(_lite_message_template.format(email=author_email, config=config), file=sys.stderr)
Exemple #9
0
def crash_handler_lite(etype, evalue, tb):
    """a light excepthook, adding a small message to the usual traceback"""
    traceback.print_exception(etype, evalue, tb)

    from yap_ipython.core.interactiveshell import InteractiveShell
    if InteractiveShell.initialized():
        # we are in a Shell environment, give %magic example
        config = "%config "
    else:
        # we are not in a shell, show generic config
        config = "c."
    print(_lite_message_template.format(email=author_email, config=config),
          file=sys.stderr)
Exemple #10
0
def publish_display_data(data,
                         metadata=None,
                         source=None,
                         *,
                         transient=None,
                         **kwargs):
    """Publish data and metadata to all frontends.

    See the ``display_data`` message in the messaging documentation for
    more details about this message type.

    Keys of data and metadata can be any mime-type.

    Parameters
    ----------
    data : dict
        A dictionary having keys that are valid MIME types (like
        'text/plain' or 'image/svg+xml') and values that are the data for
        that MIME type. The data itself must be a JSON'able data
        structure. Minimally all data should have the 'text/plain' data,
        which can be displayed by all frontends. If more than the plain
        text is given, it is up to the frontend to decide which
        representation to use.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data. mime-type keys matching those in data can be used
        to specify metadata about particular representations.
    source : str, deprecated
        Unused.
    transient : dict, keyword-only
        A dictionary of transient data, such as display_id.
        """
    from yap_ipython.core.interactiveshell import InteractiveShell

    display_pub = InteractiveShell.instance().display_pub

    # only pass transient if supplied,
    # to avoid errors with older yap_kernel.
    # TODO: We could check for yap_kernel version and provide a detailed upgrade message.
    if transient:
        kwargs['transient'] = transient

    display_pub.publish(data=data, metadata=metadata, **kwargs)
Exemple #11
0
def publish_display_data(data, metadata=None, source=None, *, transient=None, **kwargs):
    """Publish data and metadata to all frontends.

    See the ``display_data`` message in the messaging documentation for
    more details about this message type.

    Keys of data and metadata can be any mime-type.

    Parameters
    ----------
    data : dict
        A dictionary having keys that are valid MIME types (like
        'text/plain' or 'image/svg+xml') and values that are the data for
        that MIME type. The data itself must be a JSON'able data
        structure. Minimally all data should have the 'text/plain' data,
        which can be displayed by all frontends. If more than the plain
        text is given, it is up to the frontend to decide which
        representation to use.
    metadata : dict
        A dictionary for metadata related to the data. This can contain
        arbitrary key, value pairs that frontends can use to interpret
        the data. mime-type keys matching those in data can be used
        to specify metadata about particular representations.
    source : str, deprecated
        Unused.
    transient : dict, keyword-only
        A dictionary of transient data, such as display_id.
        """
    from yap_ipython.core.interactiveshell import InteractiveShell

    display_pub = InteractiveShell.instance().display_pub

    # only pass transient if supplied,
    # to avoid errors with older yap_kernel.
    # TODO: We could check for yap_kernel version and provide a detailed upgrade message.
    if transient:
        kwargs['transient'] = transient

    display_pub.publish(
        data=data,
        metadata=metadata,
        **kwargs
    )
Exemple #12
0
def create_inputhook_qt4(mgr, app=None):
    """Create an input hook for running the Qt4 application event loop.

    Parameters
    ----------
    mgr : an InputHookManager

    app : Qt Application, optional.
        Running application to use.  If not given, we probe Qt for an
        existing application object, and create a new one if none is found.

    Returns
    -------
    A pair consisting of a Qt Application (either the one given or the
    one found or created) and a inputhook.

    Notes
    -----
    We use a custom input hook instead of PyQt4's default one, as it
    interacts better with the readline packages (issue #481).

    The inputhook function works in tandem with a 'pre_prompt_hook'
    which automatically restores the hook as an inputhook in case the
    latter has been temporarily disabled after having intercepted a
    KeyboardInterrupt.
    """

    if app is None:
        app = QtCore.QCoreApplication.instance()
        if app is None:
            app = QtGui.QApplication([" "])

    # Re-use previously created inputhook if any
    ip = InteractiveShell.instance()
    if hasattr(ip, '_inputhook_qt4'):
        return app, ip._inputhook_qt4

    # Otherwise create the inputhook_qt4/preprompthook_qt4 pair of
    # hooks (they both share the got_kbdint flag)

    def inputhook_qt4():
        """PyOS_InputHook python hook for Qt4.

        Process pending Qt events and if there's no pending keyboard
        input, spend a short slice of time (50ms) running the Qt event
        loop.

        As a Python ctypes callback can't raise an exception, we catch
        the KeyboardInterrupt and temporarily deactivate the hook,
        which will let a *second* CTRL+C be processed normally and go
        back to a clean prompt line.
        """
        try:
            allow_CTRL_C()
            app = QtCore.QCoreApplication.instance()
            if not app:  # shouldn't happen, but safer if it happens anyway...
                return 0
            app.processEvents(QtCore.QEventLoop.AllEvents, 300)
            if not stdin_ready():
                # Generally a program would run QCoreApplication::exec()
                # from main() to enter and process the Qt event loop until
                # quit() or exit() is called and the program terminates.
                #
                # For our input hook integration, we need to repeatedly
                # enter and process the Qt event loop for only a short
                # amount of time (say 50ms) to ensure that Python stays
                # responsive to other user inputs.
                #
                # A naive approach would be to repeatedly call
                # QCoreApplication::exec(), using a timer to quit after a
                # short amount of time. Unfortunately, QCoreApplication
                # emits an aboutToQuit signal before stopping, which has
                # the undesirable effect of closing all modal windows.
                #
                # To work around this problem, we instead create a
                # QEventLoop and call QEventLoop::exec(). Other than
                # setting some state variables which do not seem to be
                # used anywhere, the only thing QCoreApplication adds is
                # the aboutToQuit signal which is precisely what we are
                # trying to avoid.
                timer = QtCore.QTimer()
                event_loop = QtCore.QEventLoop()
                timer.timeout.connect(event_loop.quit)
                while not stdin_ready():
                    timer.start(50)
                    event_loop.exec_()
                    timer.stop()
        except KeyboardInterrupt:
            global got_kbdint, sigint_timer

            ignore_CTRL_C()
            got_kbdint = True
            mgr.clear_inputhook()

            # This generates a second SIGINT so the user doesn't have to
            # press CTRL+C twice to get a clean prompt.
            #
            # Since we can't catch the resulting KeyboardInterrupt here
            # (because this is a ctypes callback), we use a timer to
            # generate the SIGINT after we leave this callback.
            #
            # Unfortunately this doesn't work on Windows (SIGINT kills
            # Python and CTRL_C_EVENT doesn't work).
            if (os.name == 'posix'):
                pid = os.getpid()
                if (not sigint_timer):
                    sigint_timer = threading.Timer(.01,
                                                   os.kill,
                                                   args=[pid, signal.SIGINT])
                    sigint_timer.start()
            else:
                print("\nKeyboardInterrupt - Ctrl-C again for new prompt")

        except:  # NO exceptions are allowed to escape from a ctypes callback
            ignore_CTRL_C()
            from traceback import print_exc
            print_exc()
            print("Got exception from inputhook_qt4, unregistering.")
            mgr.clear_inputhook()
        finally:
            allow_CTRL_C()
        return 0

    def preprompthook_qt4(ishell):
        """'pre_prompt_hook' used to restore the Qt4 input hook

        (in case the latter was temporarily deactivated after a
        CTRL+C)
        """
        global got_kbdint, sigint_timer

        if (sigint_timer):
            sigint_timer.cancel()
            sigint_timer = None

        if got_kbdint:
            mgr.set_inputhook(inputhook_qt4)
        got_kbdint = False

    ip._inputhook_qt4 = inputhook_qt4
    ip.set_hook('pre_prompt_hook', preprompthook_qt4)

    return app, inputhook_qt4
Exemple #13
0
def display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs):
    """Display a Python object in all frontends.

    By default all representations will be computed and sent to the frontends.
    Frontends can decide which representation is used and how.

    In terminal yap_ipython this will be similar to using :func:`print`, for use in richer
    frontends see Jupyter notebook examples with rich display logic.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display.
    raw : bool, optional
        Are the objects to be displayed already mimetype-keyed dicts of raw display data,
        or Python objects that need to be formatted before display? [default: False]
    include : list, tuple or set, optional
        A list of format type strings (MIME types) to include in the
        format data dict. If this is set *only* the format types included
        in this list will be computed.
    exclude : list, tuple or set, optional
        A list of format type strings (MIME types) to exclude in the format
        data dict. If this is set all format types will be computed,
        except for those included in this argument.
    metadata : dict, optional
        A dictionary of metadata to associate with the output.
        mime-type keys in this dictionary will be associated with the individual
        representation formats, if they exist.
    transient : dict, optional
        A dictionary of transient data to associate with the output.
        Data in this dict should not be persisted to files (e.g. notebooks).
    display_id : str, bool optional
        Set an id for the display.
        This id can be used for updating this display area later via update_display.
        If given as `True`, generate a new `display_id`
    kwargs: additional keyword-args, optional
        Additional keyword-arguments are passed through to the display publisher.

    Returns
    -------

    handle: DisplayHandle
        Returns a handle on updatable displays for use with :func:`update_display`,
        if `display_id` is given. Returns :any:`None` if no `display_id` is given
        (default).

    Examples
    --------

    >>> class Json(object):
    ...     def __init__(self, json):
    ...         self.json = json
    ...     def _repr_pretty_(self, pp, cycle):
    ...         import json
    ...         pp.text(json.dumps(self.json, indent=2))
    ...     def __repr__(self):
    ...         return str(self.json)
    ...

    >>> d = Json({1:2, 3: {4:5}})

    >>> print(d)
    {1: 2, 3: {4: 5}}

    >>> display(d)
    {
      "1": 2,
      "3": {
        "4": 5
      }
    }

    >>> def int_formatter(integer, pp, cycle):
    ...     pp.text('I'*integer)

    >>> plain = get_ipython().display_formatter.formatters['text/plain']
    >>> plain.for_type(int, int_formatter)
    <function _repr_pprint at 0x...>
    >>> display(7-5)
    II

    >>> del plain.type_printers[int]
    >>> display(7-5)
    2

    See Also
    --------

    :func:`update_display`

    Notes
    -----

    In Python, objects can declare their textual representation using the
    `__repr__` method. yap_ipython expands on this idea and allows objects to declare
    other, rich representations including:

      - HTML
      - JSON
      - PNG
      - JPEG
      - SVG
      - LaTeX

    A single object can declare some or all of these representations; all are
    handled by yap_ipython's display system.

    The main idea of the first approach is that you have to implement special
    display methods when you define your class, one for each representation you
    want to use. Here is a list of the names of the special methods and the
    values they must return:

      - `_repr_html_`: return raw HTML as a string
      - `_repr_json_`: return a JSONable dict
      - `_repr_jpeg_`: return raw JPEG data
      - `_repr_png_`: return raw PNG data
      - `_repr_svg_`: return raw SVG data as a string
      - `_repr_latex_`: return LaTeX commands in a string surrounded by "$".
      - `_repr_mimebundle_`: return a full mimebundle containing the mapping
                             from all mimetypes to data.
                             Use this for any mime-type not listed above.

    When you are directly writing your own classes, you can adapt them for
    display in yap_ipython by following the above approach. But in practice, you
    often need to work with existing classes that you can't easily modify.

    You can refer to the documentation on integrating with the display system in
    order to register custom formatters for already existing types
    (:ref:`integrating_rich_display`).

    .. versionadded:: 5.4 display available without import
    .. versionadded:: 6.1 display available without import

    Since yap_ipython 5.4 and 6.1 :func:`display` is automatically made available to
    the user without import. If you are using display in a document that might
    be used in a pure python context or with older version of yap_ipython, use the
    following import at the top of your file::

        from yap_ipython.display import display

    """
    from yap_ipython.core.interactiveshell import InteractiveShell
    
    if not InteractiveShell.initialized():
        # Directly print objects.
        print(*objs)
        return
    
    raw = kwargs.pop('raw', False)
    if transient is None:
        transient = {}
    if metadata is None:
        metadata={}
    if display_id:
        if display_id is True:
            display_id = _new_id()
        transient['display_id'] = display_id
    if kwargs.get('update') and 'display_id' not in transient:
        raise TypeError('display_id required for update_display')
    if transient:
        kwargs['transient'] = transient

    if not raw:
        format = InteractiveShell.instance().display_formatter.format

    for obj in objs:
        if raw:
            publish_display_data(data=obj, metadata=metadata, **kwargs)
        else:
            format_dict, md_dict = format(obj, include=include, exclude=exclude)
            if not format_dict:
                # nothing to display (e.g. _ipython_display_ took over)
                continue
            if metadata:
                # kwarg-specified metadata gets precedence
                _merge(md_dict, metadata)
            publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
    if display_id:
        return DisplayHandle(display_id)
Exemple #14
0
def display(*objs,
            include=None,
            exclude=None,
            metadata=None,
            transient=None,
            display_id=None,
            **kwargs):
    """Display a Python object in all frontends.

    By default all representations will be computed and sent to the frontends.
    Frontends can decide which representation is used and how.

    In terminal yap_ipython this will be similar to using :func:`print`, for use in richer
    frontends see Jupyter notebook examples with rich display logic.

    Parameters
    ----------
    objs : tuple of objects
        The Python objects to display.
    raw : bool, optional
        Are the objects to be displayed already mimetype-keyed dicts of raw display data,
        or Python objects that need to be formatted before display? [default: False]
    include : list, tuple or set, optional
        A list of format type strings (MIME types) to include in the
        format data dict. If this is set *only* the format types included
        in this list will be computed.
    exclude : list, tuple or set, optional
        A list of format type strings (MIME types) to exclude in the format
        data dict. If this is set all format types will be computed,
        except for those included in this argument.
    metadata : dict, optional
        A dictionary of metadata to associate with the output.
        mime-type keys in this dictionary will be associated with the individual
        representation formats, if they exist.
    transient : dict, optional
        A dictionary of transient data to associate with the output.
        Data in this dict should not be persisted to files (e.g. notebooks).
    display_id : str, bool optional
        Set an id for the display.
        This id can be used for updating this display area later via update_display.
        If given as `True`, generate a new `display_id`
    kwargs: additional keyword-args, optional
        Additional keyword-arguments are passed through to the display publisher.

    Returns
    -------

    handle: DisplayHandle
        Returns a handle on updatable displays for use with :func:`update_display`,
        if `display_id` is given. Returns :any:`None` if no `display_id` is given
        (default).

    Examples
    --------

    >>> class Json(object):
    ...     def __init__(self, json):
    ...         self.json = json
    ...     def _repr_pretty_(self, pp, cycle):
    ...         import json
    ...         pp.text(json.dumps(self.json, indent=2))
    ...     def __repr__(self):
    ...         return str(self.json)
    ...

    >>> d = Json({1:2, 3: {4:5}})

    >>> print(d)
    {1: 2, 3: {4: 5}}

    >>> display(d)
    {
      "1": 2,
      "3": {
        "4": 5
      }
    }

    >>> def int_formatter(integer, pp, cycle):
    ...     pp.text('I'*integer)

    >>> plain = get_ipython().display_formatter.formatters['text/plain']
    >>> plain.for_type(int, int_formatter)
    <function _repr_pprint at 0x...>
    >>> display(7-5)
    II

    >>> del plain.type_printers[int]
    >>> display(7-5)
    2

    See Also
    --------

    :func:`update_display`

    Notes
    -----

    In Python, objects can declare their textual representation using the
    `__repr__` method. yap_ipython expands on this idea and allows objects to declare
    other, rich representations including:

      - HTML
      - JSON
      - PNG
      - JPEG
      - SVG
      - LaTeX

    A single object can declare some or all of these representations; all are
    handled by yap_ipython's display system.

    The main idea of the first approach is that you have to implement special
    display methods when you define your class, one for each representation you
    want to use. Here is a list of the names of the special methods and the
    values they must return:

      - `_repr_html_`: return raw HTML as a string
      - `_repr_json_`: return a JSONable dict
      - `_repr_jpeg_`: return raw JPEG data
      - `_repr_png_`: return raw PNG data
      - `_repr_svg_`: return raw SVG data as a string
      - `_repr_latex_`: return LaTeX commands in a string surrounded by "$".
      - `_repr_mimebundle_`: return a full mimebundle containing the mapping
                             from all mimetypes to data.
                             Use this for any mime-type not listed above.

    When you are directly writing your own classes, you can adapt them for
    display in yap_ipython by following the above approach. But in practice, you
    often need to work with existing classes that you can't easily modify.

    You can refer to the documentation on integrating with the display system in
    order to register custom formatters for already existing types
    (:ref:`integrating_rich_display`).

    .. versionadded:: 5.4 display available without import
    .. versionadded:: 6.1 display available without import

    Since yap_ipython 5.4 and 6.1 :func:`display` is automatically made available to
    the user without import. If you are using display in a document that might
    be used in a pure python context or with older version of yap_ipython, use the
    following import at the top of your file::

        from yap_ipython.display import display

    """
    from yap_ipython.core.interactiveshell import InteractiveShell

    if not InteractiveShell.initialized():
        # Directly print objects.
        print(*objs)
        return

    raw = kwargs.pop('raw', False)
    if transient is None:
        transient = {}
    if metadata is None:
        metadata = {}
    if display_id:
        if display_id is True:
            display_id = _new_id()
        transient['display_id'] = display_id
    if kwargs.get('update') and 'display_id' not in transient:
        raise TypeError('display_id required for update_display')
    if transient:
        kwargs['transient'] = transient

    if not raw:
        format = InteractiveShell.instance().display_formatter.format

    for obj in objs:
        if raw:
            publish_display_data(data=obj, metadata=metadata, **kwargs)
        else:
            format_dict, md_dict = format(obj,
                                          include=include,
                                          exclude=exclude)
            if not format_dict:
                # nothing to display (e.g. _ipython_display_ took over)
                continue
            if metadata:
                # kwarg-specified metadata gets precedence
                _merge(md_dict, metadata)
            publish_display_data(data=format_dict, metadata=md_dict, **kwargs)
    if display_id:
        return DisplayHandle(display_id)