Пример #1
0
def page(strng, start=0, screen_lines=0, pager_cmd=None):
    """Print a string, piping through a pager.

    This version ignores the screen_lines and pager_cmd arguments and uses
    yap_ipython's payload system instead.

    Parameters
    ----------
    strng : str or mime-dict
      Text to page, or a mime-type keyed dict of already formatted data.

    start : int
      Starting line at which to place the display.
    """

    # Some routines may auto-compute start offsets incorrectly and pass a
    # negative value.  Offset to 0 for robustness.
    start = max(0, start)
    shell = get_ipython()

    if isinstance(strng, dict):
        data = strng
    else:
        data = {'text/plain': strng}
    payload = dict(
        source='page',
        data=data,
        start=start,
    )
    shell.payload_manager.write_payload(payload)
Пример #2
0
    def __enter__(self):
        from yap_ipython.core.getipython import get_ipython
        from yap_ipython.core.displaypub import CapturingDisplayPublisher
        from yap_ipython.core.displayhook import CapturingDisplayHook

        self.sys_stdout = sys.stdout
        self.sys_stderr = sys.stderr

        if self.display:
            self.shell = get_ipython()
            if self.shell is None:
                self.save_display_pub = None
                self.display = False

        stdout = stderr = outputs = None
        if self.stdout:
            stdout = sys.stdout = StringIO()
        if self.stderr:
            stderr = sys.stderr = StringIO()
        if self.display:
            self.save_display_pub = self.shell.display_pub
            self.shell.display_pub = CapturingDisplayPublisher()
            outputs = self.shell.display_pub.outputs
            self.save_display_hook = sys.displayhook
            sys.displayhook = CapturingDisplayHook(shell=self.shell,
                                                   outputs=outputs)

        return CapturedIO(stdout, stderr, outputs)
Пример #3
0
def test_update_display():
    ip = get_ipython()
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        with nt.assert_raises(TypeError):
            display.update_display('x')
        display.update_display('x', display_id='1')
        display.update_display('y', display_id='2')
    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('x')
            },
            'metadata': {},
            'transient': {
                'display_id': '1',
            },
            'update': True,
        })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('y')
            },
            'metadata': {},
            'transient': {
                'display_id': '2',
            },
            'update': True,
        })
Пример #4
0
def test_display_handle():
    ip = get_ipython()
    handle = display.DisplayHandle()
    nt.assert_is_instance(handle.display_id, str)
    handle = display.DisplayHandle('my-id')
    nt.assert_equal(handle.display_id, 'my-id')
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        handle.display('x')
        handle.update('y')

    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('x')
            },
            'metadata': {},
            'transient': {
                'display_id': handle.display_id,
            }
        })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('y')
            },
            'metadata': {},
            'transient': {
                'display_id': handle.display_id,
            },
            'update': True,
        })
Пример #5
0
def test_image_mimes():
    fmt = get_ipython().display_formatter.format
    for format in display.Image._ACCEPTABLE_EMBEDDINGS:
        mime = display.Image._MIMETYPES[format]
        img = display.Image(b'garbage', format=format)
        data, metadata = fmt(img)
        nt.assert_equal(sorted(data), sorted([mime, 'text/plain']))
Пример #6
0
def test_display_handle():
    ip = get_ipython()
    handle = display.DisplayHandle()
    nt.assert_is_instance(handle.display_id, str)
    handle = display.DisplayHandle('my-id')
    nt.assert_equal(handle.display_id, 'my-id')
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        handle.display('x')
        handle.update('y')

    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('x')
        },
        'metadata': {},
        'transient': {
            'display_id': handle.display_id,
        }
    })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('y')
        },
        'metadata': {},
        'transient': {
            'display_id': handle.display_id,
        },
        'update': True,
    })
Пример #7
0
def test_update_display():
    ip = get_ipython()
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        with nt.assert_raises(TypeError):
            display.update_display('x')
        display.update_display('x', display_id='1')
        display.update_display('y', display_id='2')
    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('x')
        },
        'metadata': {},
        'transient': {
            'display_id': '1',
        },
        'update': True,
    })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('y')
        },
        'metadata': {},
        'transient': {
            'display_id': '2',
        },
        'update': True,
    })
Пример #8
0
def test_image_mimes():
    fmt = get_ipython().display_formatter.format
    for format in display.Image._ACCEPTABLE_EMBEDDINGS:
        mime = display.Image._MIMETYPES[format]
        img = display.Image(b'garbage', format=format)
        data, metadata = fmt(img)
        nt.assert_equal(sorted(data), sorted([mime, 'text/plain']))
Пример #9
0
def page(strng, start=0, screen_lines=0, pager_cmd=None):
    """Print a string, piping through a pager.

    This version ignores the screen_lines and pager_cmd arguments and uses
    yap_ipython's payload system instead.

    Parameters
    ----------
    strng : str or mime-dict
      Text to page, or a mime-type keyed dict of already formatted data.

    start : int
      Starting line at which to place the display.
    """

    # Some routines may auto-compute start offsets incorrectly and pass a
    # negative value.  Offset to 0 for robustness.
    start = max(0, start)
    shell = get_ipython()
    
    if isinstance(strng, dict):
        data = strng
    else:
        data = {'text/plain' : strng}
    payload = dict(
        source='page',
        data=data,
        start=start,
        )
    shell.payload_manager.write_payload(payload)
Пример #10
0
def test_select_figure_formats_bad():
    ip = get_ipython()
    with nt.assert_raises(ValueError):
        pt.select_figure_formats(ip, 'foo')
    with nt.assert_raises(ValueError):
        pt.select_figure_formats(ip, {'png', 'foo'})
    with nt.assert_raises(ValueError):
        pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad'])
Пример #11
0
def test_select_figure_formats_str():
    ip = get_ipython()
    for fmt, active_mime in _fmt_mime_map.items():
        pt.select_figure_formats(ip, fmt)
        for mime, f in ip.display_formatter.formatters.items():
            if mime == active_mime:
                nt.assert_in(Figure, f)
            else:
                nt.assert_not_in(Figure, f)
Пример #12
0
def flush_figures():
    """Send all figures that changed

    This is meant to be called automatically and will call show() if, during
    prior code execution, there had been any calls to draw_if_interactive.

    This function is meant to be used as a post_execute callback in yap_ipython,
    so user-caused errors are handled with showtraceback() instead of being
    allowed to raise.  If this function is not called from within yap_ipython,
    then these exceptions will raise.
    """
    if not show._draw_called:
        return

    if InlineBackend.instance().close_figures:
        # ignore the tracking, just draw and close all figures
        try:
            return show(True)
        except Exception as e:
            # safely show traceback if in yap_ipython, else raise
            ip = get_ipython()
            if ip is None:
                raise e
            else:
                ip.showtraceback()
                return
    try:
        # exclude any figures that were closed:
        active = set([fm.canvas.figure for fm in Gcf.get_all_fig_managers()])
        for fig in [fig for fig in show._to_draw if fig in active]:
            try:
                display(fig)
            except Exception as e:
                # safely show traceback if in yap_ipython, else raise
                ip = get_ipython()
                if ip is None:
                    raise e
                else:
                    ip.showtraceback()
                    return
    finally:
        # clear flags for next round
        show._to_draw = []
        show._draw_called = False
Пример #13
0
def test_set_matplotlib_formats_kwargs():
    from matplotlib.figure import Figure
    ip = get_ipython()
    cfg = _get_inline_config()
    cfg.print_figure_kwargs.update(dict(foo='bar'))
    kwargs = dict(quality=10)
    display.set_matplotlib_formats('png', **kwargs)
    formatter = ip.display_formatter.formatters['image/png']
    f = formatter.lookup_by_type(Figure)
    cell = f.__closure__[0].cell_contents
    expected = kwargs
    expected.update(cfg.print_figure_kwargs)
    nt.assert_equal(cell, expected)
Пример #14
0
def test_set_matplotlib_formats_kwargs():
    from matplotlib.figure import Figure
    ip = get_ipython()
    cfg = _get_inline_config()
    cfg.print_figure_kwargs.update(dict(foo='bar'))
    kwargs = dict(quality=10)
    display.set_matplotlib_formats('png', **kwargs)
    formatter = ip.display_formatter.formatters['image/png']
    f = formatter.lookup_by_type(Figure)
    cell = f.__closure__[0].cell_contents
    expected = kwargs
    expected.update(cfg.print_figure_kwargs)
    nt.assert_equal(cell, expected)
Пример #15
0
def is_event_loop_running_qt4(app=None):
    """Is the qt4 event loop running."""
    # New way: check attribute on shell instance
    ip = get_ipython()
    if ip is not None:
        return ip.active_eventloop and ip.active_eventloop.startswith('qt')

    # Old way: check attribute on QApplication singleton
    if app is None:
        app = get_app_qt4([''])
    if hasattr(app, '_in_event_loop'):
        return app._in_event_loop
    else:
        # Does qt4 provide a other way to detect this?
        return False
Пример #16
0
def test_select_figure_formats_set():
    ip = get_ipython()
    for fmts in [
        {'png', 'svg'},
        ['png'],
        ('jpeg', 'pdf', 'retina'),
        {'svg'},
    ]:
        active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
        pt.select_figure_formats(ip, fmts)
        for mime, f in ip.display_formatter.formatters.items():
            if mime in active_mimes:
                nt.assert_in(Figure, f)
            else:
                nt.assert_not_in(Figure, f)
Пример #17
0
def catch_format_error(method, self, *args, **kwargs):
    """show traceback on failed format call"""
    try:
        r = method(self, *args, **kwargs)
    except NotImplementedError:
        # don't warn on NotImplementedErrors
        return self._check_return(None, args[0])
    except Exception:
        exc_info = sys.exc_info()
        ip = get_ipython()
        if ip is not None:
            ip.showtraceback(exc_info)
        else:
            traceback.print_exception(*exc_info)
        return self._check_return(None, args[0])
    return self._check_return(r, args[0])
Пример #18
0
def test_set_matplotlib_formats():
    from matplotlib.figure import Figure
    formatters = get_ipython().display_formatter.formatters
    for formats in [
        ('png', ),
        ('pdf', 'svg'),
        ('jpeg', 'retina', 'png'),
        (),
    ]:
        active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
        display.set_matplotlib_formats(*formats)
        for mime, f in formatters.items():
            if mime in active_mimes:
                nt.assert_in(Figure, f)
            else:
                nt.assert_not_in(Figure, f)
Пример #19
0
def catch_format_error(method, self, *args, **kwargs):
    """show traceback on failed format call"""
    try:
        r = method(self, *args, **kwargs)
    except NotImplementedError:
        # don't warn on NotImplementedErrors
        return self._check_return(None, args[0])
    except Exception:
        exc_info = sys.exc_info()
        ip = get_ipython()
        if ip is not None:
            ip.showtraceback(exc_info)
        else:
            traceback.print_exception(*exc_info)
        return self._check_return(None, args[0])
    return self._check_return(r, args[0])
Пример #20
0
def test_set_matplotlib_formats():
    from matplotlib.figure import Figure
    formatters = get_ipython().display_formatter.formatters
    for formats in [
        ('png',),
        ('pdf', 'svg'),
        ('jpeg', 'retina', 'png'),
        (),
    ]:
        active_mimes = {_fmt_mime_map[fmt] for fmt in formats}
        display.set_matplotlib_formats(*formats)
        for mime, f in formatters.items():
            if mime in active_mimes:
                nt.assert_in(Figure, f)
            else:
                nt.assert_not_in(Figure, f)
Пример #21
0
def test_display_available():
    """
    Test that display is available without import

    We don't really care if it's in builtin or anything else, but it should
    always be available.
    """
    ip = get_ipython()
    with AssertNotPrints('NameError'):
        ip.run_cell('display')
    try:
        ip.run_cell('del display')
    except NameError:
        pass # it's ok, it might be in builtins
    # even if deleted it should be back
    with AssertNotPrints('NameError'):
        ip.run_cell('display')
Пример #22
0
def is_event_loop_running_wx(app=None):
    """Is the wx event loop running."""
    # New way: check attribute on shell instance
    ip = get_ipython()
    if ip is not None:
        if ip.active_eventloop and ip.active_eventloop == 'wx':
            return True
        # Fall through to checking the application, because Wx has a native way
        # to check if the event loop is running, unlike Qt.

    # Old way: check Wx application
    if app is None:
        app = get_app_wx()
    if hasattr(app, '_in_event_loop'):
        return app._in_event_loop
    else:
        return app.IsMainLoopRunning()
Пример #23
0
def test_select_figure_formats_kwargs():
    ip = get_ipython()
    kwargs = dict(quality=10, bbox_inches='tight')
    pt.select_figure_formats(ip, 'png', **kwargs)
    formatter = ip.display_formatter.formatters['image/png']
    f = formatter.lookup_by_type(Figure)
    cell = f.__closure__[0].cell_contents
    nt.assert_equal(cell, kwargs)

    # check that the formatter doesn't raise
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot([1, 2, 3])
    plt.draw()
    formatter.enabled = True
    png = formatter(fig)
    assert png.startswith(_PNG)
Пример #24
0
def test_display_available():
    """
    Test that display is available without import

    We don't really care if it's in builtin or anything else, but it should
    always be available.
    """
    ip = get_ipython()
    with AssertNotPrints('NameError'):
        ip.run_cell('display')
    try:
        ip.run_cell('del display')
    except NameError:
        pass  # it's ok, it might be in builtins
    # even if deleted it should be back
    with AssertNotPrints('NameError'):
        ip.run_cell('display')
Пример #25
0
def _enable_matplotlib_integration():
    """Enable extra yap_ipython matplotlib integration when we are loaded as the matplotlib backend."""
    from matplotlib import get_backend
    ip = get_ipython()
    backend = get_backend()
    if ip and backend == 'module://%s' % __name__:
        from yap_ipython.core.pylabtools import configure_inline_support, activate_matplotlib
        try:
            activate_matplotlib(backend)
            configure_inline_support(ip, backend)
        except (ImportError, AttributeError):
            # bugs may cause a circular import on Python 2
            def configure_once(*args):
                activate_matplotlib(backend)
                configure_inline_support(ip, backend)
                ip.events.unregister('post_run_cell', configure_once)

            ip.events.register('post_run_cell', configure_once)
Пример #26
0
def test_display_id():
    ip = get_ipython()
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        handle = display.display('x')
        nt.assert_is(handle, None)
        handle = display.display('y', display_id='secret')
        nt.assert_is_instance(handle, display.DisplayHandle)
        handle2 = display.display('z', display_id=True)
        nt.assert_is_instance(handle2, display.DisplayHandle)
    nt.assert_not_equal(handle.display_id, handle2.display_id)

    nt.assert_equal(pub.call_count, 3)
    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('x')
        },
        'metadata': {},
    })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('y')
            },
            'metadata': {},
            'transient': {
                'display_id': handle.display_id,
            },
        })
    args, kwargs = pub.call_args_list[2]
    nt.assert_equal(args, ())
    nt.assert_equal(
        kwargs, {
            'data': {
                'text/plain': repr('z')
            },
            'metadata': {},
            'transient': {
                'display_id': handle2.display_id,
            },
        })
Пример #27
0
def test_display_id():
    ip = get_ipython()
    with mock.patch.object(ip.display_pub, 'publish') as pub:
        handle = display.display('x')
        nt.assert_is(handle, None)
        handle = display.display('y', display_id='secret')
        nt.assert_is_instance(handle, display.DisplayHandle)
        handle2 = display.display('z', display_id=True)
        nt.assert_is_instance(handle2, display.DisplayHandle)
    nt.assert_not_equal(handle.display_id, handle2.display_id)

    nt.assert_equal(pub.call_count, 3)
    args, kwargs = pub.call_args_list[0]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('x')
        },
        'metadata': {},
    })
    args, kwargs = pub.call_args_list[1]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('y')
        },
        'metadata': {},
        'transient': {
            'display_id': handle.display_id,
        },
    })
    args, kwargs = pub.call_args_list[2]
    nt.assert_equal(args, ())
    nt.assert_equal(kwargs, {
        'data': {
            'text/plain': repr('z')
        },
        'metadata': {},
        'transient': {
            'display_id': handle2.display_id,
        },
    })