Beispiel #1
0
 def function(self, *xss):
     """Run selected function on data."""
     function = self.w_functions.function
     # pass the required number of function arguments
     argspec = inspect.getargspec(function)
     nargs = len(argspec.args)
     if argspec.defaults is not None:
         nargs -= len(argspec.defaults)
     try:
         if nargs == 0:
             raise ValueError('Data function must accept at least one ' +
                              'non-default argument.')
         if nargs == 1:
             zs = self.w_functions.function(xss[-1])
         elif (nargs == 2) and (len(xss) > 1):
             zs = self.w_functions.function(xss[0], xss[-1])
         elif (nargs == 3) and (len(xss) > 2):
             zs = self.w_functions.function(xss[0], xss[1], xss[2])
         else:
             raise ValueError('Data function requires more arguments than' +
                              'available.')
     except:
         tb = VerboseTB()
         print(tb.text(*sys.exc_info(), tb_offset=1))
         # return a matrix of NaNs
         zs = np.full_like(xss[0], np.nan)
     return zs
Beispiel #2
0
 def __init__(self):
     if self.instance is not None:
         raise RuntimeError(
             "Only one instance of KernelPartManager is allowed"
         )
     self.parts = {}
     self.options_bags = {}
     self.error_formatter = VerboseTB()
Beispiel #3
0
def print_traceback(exc_info):
    # call_pdb does not work properly from a different thread. Instead, can
    # I store the traceback and call ipdb form the main thread, e.g. with
    # Dispatcher.debug()?
    if not hasattr(print_traceback, 'TRACEBACK_PRINTER'):
        from IPython.core.ultratb import VerboseTB
        print_traceback.TRACEBACK_PRINTER = VerboseTB()
    print_traceback.TRACEBACK_PRINTER(*exc_info)
Beispiel #4
0
def show_traceback(einfo=None):
    if not einfo:
        einfo = sys.exc_info()
    (etype, evalue, tb) = einfo
    # once for the user
    h = VerboseTB(color_scheme='Linux',
                  call_pdb=False,
                  ostream=None,
                  tb_offset=0,
                  long_header=False,
                  include_vars=False,
                  check_cache=None)
    h(etype, evalue, tb)
Beispiel #5
0
def hook(exc_type, exc, tb):
    global selectable

    from IPython import embed
    from IPython.core.ultratb import VerboseTB

    tb_handler = VerboseTB(color_scheme='Neutral')
    tb_handler(exc_type, exc, tb)

    frames = [t[0] for t in traceback.walk_tb(tb)][::-1]

    while True:
        print()

        if selectable:
            print('Select a stack frame to embed IPython shell:')
            for i, frame in enumerate(frames):
                print('{}. {}'.format(i, frame))
            try:
                s = input('> ').strip()
                n = int(s) if s else 0
                frame = frames[n]
            except (KeyboardInterrupt, EOFError):
                break
            except:
                continue
        else:
            frame = frames[0]

        print('Embedded into', frame)

        user_module = inspect.getmodule(frame)
        user_ns = frame.f_locals

        user_ns.setdefault('etype', exc_type)
        user_ns.setdefault('evalue', exc)
        user_ns.setdefault('etb', tb)

        embed(banner1='',
              user_module=user_module,
              user_ns=user_ns,
              colors='Neutral')

        if not selectable:
            break
Beispiel #6
0
    def exception_handler(etype, evalue, tb):
        print 'FATAL ERROR (%s): %s' % (etype.__name__, evalue)

        # once for the log file.
        with file(dotdynadir / 'crash.log', 'wb') as crashreport:
            h = VerboseTB(color_scheme='Linux',
                          call_pdb=False,
                          ostream=crashreport,
                          long_header=True,
                          include_vars=True,
                          check_cache=None)
            h(etype, evalue, tb)

        show_traceback((etype, evalue, tb))

        for hook in crash_handler.hooks:
            hook()

        print 'Crash log available %s' % crashreport.name
Beispiel #7
0
def test_handlers():
    def spam(c, d_e):
        (d, e) = d_e
        x = c + d
        y = c * d
        foo(x, y)

    def foo(a, b, bar=1):
        eggs(a, b + bar)

    def eggs(f, g, z=globals()):
        h = f + g
        i = f - g
        return h / i

    buff = io.StringIO()

    buff.write('')
    buff.write('*** Before ***')
    try:
        buff.write(spam(1, (2, 3)))
    except:
        traceback.print_exc(file=buff)

    handler = ColorTB(ostream=buff)
    buff.write('*** ColorTB ***')
    try:
        buff.write(spam(1, (2, 3)))
    except:
        handler(*sys.exc_info())
    buff.write('')

    handler = VerboseTB(ostream=buff)
    buff.write('*** VerboseTB ***')
    try:
        buff.write(spam(1, (2, 3)))
    except:
        handler(*sys.exc_info())
    buff.write('')
Beispiel #8
0
class KernelPartManager:
    instance = None

    @classmethod
    def Create(cls):
        if cls.instance is not None:
            return cls.instance
        return KernelPartManager()

    def __init__(self):
        if self.instance is not None:
            raise RuntimeError(
                "Only one instance of KernelPartManager is allowed"
            )
        self.parts = {}
        self.options_bags = {}
        self.error_formatter = VerboseTB()
        # Connect to a comm

    def create_part(self, type_name, uuid):
        part = KernelPart.Create(type_name)
        part.uuid = uuid
        self.parts[uuid] = part
        self.options_bags[uuid] = OptionsBag(part.get_metadata())

    def destroy_part(self, uuid):
        self.parts[uuid].dispose()
        del self.parts[uuid]
        del self.options_bags[uuid]

    def initialize_part(self, uuid):
        self.parts[uuid].initialize()

    def render_part(self, uuid, options):
        bag: OptionsBag = self.options_bags[uuid]
        bag.is_stale = True
        for opt in options.keys():
            bag[opt] = options[opt]
        bag.set_fresh()
        with capture_output() as capture:
            ret = self.parts[uuid].render(bag)
        if ret is not None:
            return ret
        elif len(capture.outputs) > 0:
            return capture.outputs[0]
        else:
            return capture.stdout + capture.stderr

    def dispatch_msg(self, msg, comm: Comm):
        data = msg['content']['data']
        msg_type = data['msg_type']
        uuid = data['uuid']
        payload = data['payload']
        if msg_type == "create":
            self.create_part(payload, uuid)
            bag: OptionsBag = self.options_bags[uuid]
            bag.OnStale.subscribe(lambda args: comm.send({
                "msg_type": "stale",
                "uuid": uuid,
                "payload": {
                    "name": args[0],
                    "value": serialize(args[1], guess_type(args[1]))
                }
            }))
        if msg_type == "initialize":
            error = None
            try:
                self.initialize_part(uuid)
            except:  # noqa: E722
                exc_info = sys.exc_info()
                error = self.error_formatter.text(*exc_info)
            comm.send({
                "msg_type": "initialize_done",
                "uuid": uuid,
                "payload": None,
                "error": error
            })
        if msg_type == "render":
            options = {
                name: deserialize(value) for name, value in payload.items()
            }
            error = None
            value = None
            try:
                display_data, display_metadata = format_display_data(
                    self.render_part(uuid, options)
                )
                value = {
                    "data": display_data,
                    "metadata": display_metadata
                }
            except:  # noqa: E722
                exc_info = sys.exc_info()
                error = self.error_formatter.text(*exc_info)
            comm.send({
                "msg_type": "render_done",
                "uuid": uuid,
                "payload": value,
                "error": error
            })
        if msg_type == "dispose":
            return self.destroy_part(uuid)
Beispiel #9
0
   will instead send ``expr_error``.
 - ``expr_error``: If a expression evaluation failed, this will be sent instead
   of ``expr_value`` and will include a serialized form of error that clients
   must present to the user.
"""

import re
import sys
from typing import AnyStr, Dict, Any
from IPython import get_ipython
from IPython.core.ultratb import VerboseTB
from ipykernel.comm import Comm
from ..serialization import serialize, deserialize, guess_type

MESSAGE_TYPES = ["evaluate_expr"]
tb_formatter = VerboseTB()
global_regex = re.compile(r"\@([A-Za-z][A-Za-z0-9_]*)")


def evaluate_expr(expr: AnyStr, globals_dict: Dict[AnyStr, Any], comm: Comm,
                  parent: AnyStr):
    ip = get_ipython()
    locals_dict = {}
    locals_dict.update(ip.user_ns)
    locals_dict.update(globals_dict)
    expr = global_regex.sub(r"\1", expr)
    try:
        value = eval(expr, ip.user_global_ns, locals_dict)
    except:  # noqa: E722
        exc_info = sys.exc_info()
        exc = tb_formatter.text(*exc_info)
Beispiel #10
0
             if isinstance(e, unittest.case.SkipTest):
                 skipped += 1
                 print(str(test) + ' ... skipped')
             elif isinstance(e, AssertionError):
                 fails += 1
                 print(str(test))
                 ipdb.post_mortem(sys.exc_info()[2])
             elif isinstance(e, NotImplementedError):
                 not_implemented += 1
                 print(str(test) + ' ... not implemented')
             else:
                 exceptions += 1
                 print(test._testMethodName)
                 try:
                     from IPython.core.ultratb import VerboseTB
                     vtb = VerboseTB(call_pdb=1)
                     vtb(*sys.exc_info())
                 except Exception:
                     import traceback
                     print('\n')
                     traceback.print_exc()
                 ipdb.post_mortem(sys.exc_info()[2])
 if _print:
     end_time = time.time()
     run_time = end_time - start_time
     print(
         '----------------------------------------------------------------------'
     )
     print('Ran ' + str(n) + ' tests in {:.3f}s\n'.format(run_time))
     result_str = ''
     if fails <= 0 and exceptions <= 0: