Exemplo n.º 1
0
def make_kernel(namespace, kernel_factory, 
                out_stream_factory=None, display_hook_factory=None):
    """ Creates a kernel, redirects stdout/stderr, and installs a display hook
    and exception handler.
    """
    # Re-direct stdout/stderr, if necessary.
    if namespace.no_stdout or namespace.no_stderr:
        blackhole = file(os.devnull, 'w')
        if namespace.no_stdout:
            sys.stdout = sys.__stdout__ = blackhole
        if namespace.no_stderr:
            sys.stderr = sys.__stderr__ = blackhole

    # Install minimal exception handling
    sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor', 
                                 ostream=sys.__stdout__)

    # Create a context, a session, and the kernel sockets.
    io.raw_print("Starting the kernel at pid:", os.getpid())
    context = zmq.Context()
    # Uncomment this to try closing the context.
    # atexit.register(context.close)
    session = Session(username=u'kernel')

    reply_socket = context.socket(zmq.XREP)
    xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep)
    io.raw_print("XREP Channel on port", xrep_port)

    pub_socket = context.socket(zmq.PUB)
    pub_port = bind_port(pub_socket, namespace.ip, namespace.pub)
    io.raw_print("PUB Channel on port", pub_port)

    req_socket = context.socket(zmq.XREQ)
    req_port = bind_port(req_socket, namespace.ip, namespace.req)
    io.raw_print("REQ Channel on port", req_port)

    hb = Heartbeat(context, (namespace.ip, namespace.hb))
    hb.start()
    hb_port = hb.port
    io.raw_print("Heartbeat REP Channel on port", hb_port)

    # Helper to make it easier to connect to an existing kernel, until we have
    # single-port connection negotiation fully implemented.
    io.raw_print("To connect another client to this kernel, use:")
    io.raw_print("-e --xreq {0} --sub {1} --rep {2} --hb {3}".format(
        xrep_port, pub_port, req_port, hb_port))

    # Redirect input streams and set a display hook.
    if out_stream_factory:
        sys.stdout = out_stream_factory(session, pub_socket, u'stdout')
        sys.stderr = out_stream_factory(session, pub_socket, u'stderr')
    if display_hook_factory:
        sys.displayhook = display_hook_factory(session, pub_socket)

    # Create the kernel.
    kernel = kernel_factory(session=session, reply_socket=reply_socket, 
                            pub_socket=pub_socket, req_socket=req_socket)
    kernel.record_ports(xrep_port=xrep_port, pub_port=pub_port,
                        req_port=req_port, hb_port=hb_port)
    return kernel
Exemplo n.º 2
0
def make_kernel(namespace, kernel_factory, 
                out_stream_factory=None, display_hook_factory=None):
    """ Creates a kernel, redirects stdout/stderr, and installs a display hook
    and exception handler.
    """
    # If running under pythonw.exe, the interpreter will crash if more than 4KB
    # of data is written to stdout or stderr. This is a bug that has been with
    # Python for a very long time; see http://bugs.python.org/issue706263.
    if sys.executable.endswith('pythonw.exe'):
        blackhole = file(os.devnull, 'w')
        sys.stdout = sys.stderr = blackhole
        sys.__stdout__ = sys.__stderr__ = blackhole 

    # Install minimal exception handling
    sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor', 
                                 ostream=sys.__stdout__)

    # Create a context, a session, and the kernel sockets.
    io.raw_print("Starting the kernel at pid:", os.getpid())
    context = zmq.Context()
    # Uncomment this to try closing the context.
    # atexit.register(context.close)
    session = Session(username=u'kernel')

    reply_socket = context.socket(zmq.XREP)
    xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep)
    io.raw_print("XREP Channel on port", xrep_port)

    pub_socket = context.socket(zmq.PUB)
    pub_port = bind_port(pub_socket, namespace.ip, namespace.pub)
    io.raw_print("PUB Channel on port", pub_port)

    req_socket = context.socket(zmq.XREQ)
    req_port = bind_port(req_socket, namespace.ip, namespace.req)
    io.raw_print("REQ Channel on port", req_port)

    hb = Heartbeat(context, (namespace.ip, namespace.hb))
    hb.start()
    hb_port = hb.port
    io.raw_print("Heartbeat REP Channel on port", hb_port)

    # Helper to make it easier to connect to an existing kernel, until we have
    # single-port connection negotiation fully implemented.
    io.raw_print("To connect another client to this kernel, use:")
    io.raw_print("-e --xreq {0} --sub {1} --rep {2} --hb {3}".format(
        xrep_port, pub_port, req_port, hb_port))

    # Redirect input streams and set a display hook.
    if out_stream_factory:
        sys.stdout = out_stream_factory(session, pub_socket, u'stdout')
        sys.stderr = out_stream_factory(session, pub_socket, u'stderr')
    if display_hook_factory:
        sys.displayhook = display_hook_factory(session, pub_socket)

    # Create the kernel.
    kernel = kernel_factory(session=session, reply_socket=reply_socket, 
                            pub_socket=pub_socket, req_socket=req_socket)
    kernel.record_ports(xrep_port=xrep_port, pub_port=pub_port,
                        req_port=req_port, hb_port=hb_port)
    return kernel
Exemplo n.º 3
0
def format_traceback(err: _E) -> str:
    tb_formatter = FormattedTB('Context', 'NoColor')
    structured_tb: List[str] = tb_formatter.structured_traceback(
        type(err), err, err.__traceback__
    )
    tb_string: str = tb_formatter.stb2text(structured_tb)
    return html.escape(tb_string)
Exemplo n.º 4
0
        def _wrap_errors(_):
            """Install traceback handling for callbacks"""
            self._traceback = sys.exc_info()[2]

            # Compute number of stack frames to skip to get down to callback
            tb_werkzeug = get_current_traceback()
            skip = 0
            if dev_tools_prune_errors:
                for i, line in enumerate(tb_werkzeug.plaintext.splitlines()):
                    if "%% callback invoked %%" in line:
                        skip = int((i + 1) / 2)
                        break

            # Customized formatargvalues function so we can place function parameters
            # on separate lines
            original_formatargvalues = inspect.formatargvalues
            inspect.formatargvalues = _custom_formatargvalues
            try:
                # Use IPython traceback formatting to build colored ANSI traceback
                # string
                ostream = io.StringIO()
                ipytb = FormattedTB(
                    tb_offset=skip,
                    mode="Verbose",
                    color_scheme="Linux",
                    include_vars=True,
                    ostream=ostream
                )
                ipytb()
            finally:
                # Restore formatargvalues
                inspect.formatargvalues = original_formatargvalues

            # Print colored ANSI representation if requested
            ansi_stacktrace = ostream.getvalue()

            if inline_exceptions:
                print(ansi_stacktrace)

            # Use ansi2html to convert the colored ANSI string to HTML
            conv = Ansi2HTMLConverter(scheme="ansi2html", dark_bg=False)
            html_str = conv.convert(ansi_stacktrace)

            # Set width to fit 75-character wide stack trace and font to a size the
            # won't require a horizontal scroll bar
            html_str = html_str.replace(
                '<html>',
                '<html style="width: 75ch; font-size: 0.86em">'
            )

            # Remove explicit background color so Dash dev-tools can set background
            # color
            html_str = re.sub("background-color:[^;]+;", "", html_str)

            return html_str, 500
Exemplo n.º 5
0
 def init_crash_handler(self):
     # Install minimal exception handling
     sys.excepthook = FormattedTB(mode='Verbose',
                                  color_scheme='NoColor',
                                  ostream=sys.__stdout__)
Exemplo n.º 6
0
def setup_exceptions():
    try:
        from IPython.core.ultratb import FormattedTB
        sys.excepthook = FormattedTB(mode='Plain', color_scheme='Neutral')
    except ImportError:
        pass