Ejemplo n.º 1
0
    def __init__(self,
                 db,
                 frame,
                 tb,
                 exception,
                 exception_description,
                 init=None,
                 shell=False,
                 shell_vars=None,
                 source=None):
        self.db = db
        self.shell = shell
        self.init_message = init
        self.stack, self.trace, self.index = self.db.get_trace(frame, tb)
        self.exception = exception
        self.exception_description = exception_description
        # Copy locals to avoid strange cpython behaviour
        self.locals = list(map(lambda x: x[0].f_locals, self.stack))
        self.htmldiff = Html5Diff(4)
        if self.shell:
            self.locals[self.index] = shell_vars or {}

        if source:
            with open(source) as f:
                compiled_code = compile(f.read(), '<source>', 'exec')
            # Executing in locals to keep local scope
            # (http://bugs.python.org/issue16781)
            execute(compiled_code, self.current_locals, self.current_locals)
Ejemplo n.º 2
0
Archivo: ui.py Proyecto: lxhope/wdb
    def __init__(
            self, db, frame, tb, exception, exception_description,
            init=None, shell=False, shell_vars=None, source=None,
            timeout=None):
        self.db = db
        self.shell = shell
        self.init_message = init
        self.stack, self.trace, self.index = self.db.get_trace(frame, tb)
        self.exception = exception
        self.exception_description = exception_description
        # Copy locals to avoid strange cpython behaviour
        self.locals = list(map(lambda x: x[0].f_locals, self.stack))
        self.htmldiff = Html5Diff(4)
        self.timeout = timeout
        if self.timeout:
            def handler(*args):
                raise KeyboardInterrupt()
            signal.signal(signal.SIGALRM, handler)
            signal.alarm(self.timeout)

        if self.shell:
            self.locals[self.index] = shell_vars or {}

        if source:
            with open(source) as f:
                compiled_code = compile(f.read(), '<source>', 'exec')
            # Executing in locals to keep local scope
            # (http://bugs.python.org/issue16781)
            execute(
                compiled_code,
                self.current_locals,
                self.current_locals)
Ejemplo n.º 3
0
def serialize_answer(prompt, frame):
    prompt = prompt.strip()
    duration = 0
    answer = []
    f_globals = dict(frame.f_globals)
    f_locals = dict(frame.f_locals)
    f_globals.update(f_locals)
    f_locals["_current_frame"] = frame
    f_locals["cut"] = cut

    with capture_exception(answer), capture_display(answer), capture_std(
        answer
    ):
        compiled_code = None
        try:
            compiled_code = compile(prompt, "<stdin>", "single")
        except SetFrameError:
            raise
        except Exception:
            try:
                compiled_code = compile(prompt, "<stdin>", "exec")
            except SetFrameError:
                raise
            except Exception:
                # handle ex
                sys.excepthook(*sys.exc_info())

        start = time.time()
        if compiled_code is not None:
            try:
                exec(compiled_code, f_globals, f_locals)
            except SetFrameError:
                raise
            except Exception:
                # handle ex
                sys.excepthook(*sys.exc_info())
            del f_locals["_current_frame"]
            del f_locals["cut"]
            sync_locals(frame, f_locals)
        duration = int((time.time() - start) * 1000 * 1000 * 1000)

    return {"prompt": prompt, "answer": answer, "duration": duration}
Ejemplo n.º 4
0
def eval_(src, *args, **kwargs):
    return eval(compile(src, '<stdin>', 'eval'), *args, **kwargs)
Ejemplo n.º 5
0
    def do_eval(self, data):
        redir = None
        suggest = None
        raw_data = data.strip()
        if raw_data.startswith('!<'):
            filename = raw_data[2:].strip()
            try:
                with open(filename, 'r') as f:
                    raw_data = f.read()
            except Exception:
                self.fail('Eval', 'Unable to read from file %s' % filename)
                return

        lines = raw_data.split('\n')
        if '>!' in lines[-1]:
            try:
                last_line, redir, append = tokenize_redir(raw_data)
            except TokenError:
                last_line = redir = None
                append = False
            if redir and last_line:
                indent = len(lines[-1]) - len(lines[-1].lstrip())
                lines[-1] = indent * u(' ') + last_line
                raw_data = '\n'.join(lines)
        data = raw_data
        # Keep spaces
        raw_data = raw_data.replace(' ', u(' '))
        # Compensate prompt for multi line
        raw_data = raw_data.replace('\n', '\n' + u(' ' * 4))
        duration = None
        with self.db.capture_output(with_hook=redir is None) as (out, err):
            compiled_code = None
            try:
                compiled_code = compile(data, '<stdin>', 'single')
            except Exception:
                try:
                    compiled_code = compile(data, '<stdin>', 'exec')
                except Exception:
                    maybe_hook = self.handle_exc()

                # Hack from codeop
                e1 = e2 = None
                try:
                    compiled_code = compile(data + '\n', '<stdin>', 'exec')
                except Exception as e:
                    e1 = e
                try:
                    compile(data + '\n\n', '<stdin>', 'exec')
                except Exception as e:
                    e2 = e

                if not compiled_code:
                    if repr(e1) != repr(e2):
                        # Multiline not terminated
                        self.db.send('NewLine')
                        return
                    else:
                        self.db.hooked = maybe_hook

            l = self.current_locals
            start = time.time()
            if compiled_code is not None:
                self.db.compile_cache[id(compiled_code)] = data
                try:
                    execute(compiled_code, self.get_globals(), l)
                except NameError as e:
                    m = re.match("name '(.+)' is not defined", str(e))
                    if m:
                        name = m.groups()[0]
                        if importable_module(name):
                            suggest = 'import %s' % name

                    self.db.hooked = self.handle_exc()
                except Exception:
                    self.db.hooked = self.handle_exc()

        duration = int((time.time() - start) * 1000 * 1000)
        if redir and not self.db.hooked:
            try:
                with open(redir, 'a' if append else 'w') as f:
                    f.write('\n'.join(out) + '\n'.join(err) + '\n')
            except Exception:
                self.fail('Eval', 'Unable to write to file %s' % redir)
                return
            self.db.send('Print|%s' % dump({
                'for':
                raw_data,
                'result':
                escape(
                    '%s to file %s' %
                    ('Appended' if append else 'Written', redir), )
            }))
        else:
            rv = escape('\n'.join(out) + '\n'.join(err))
            try:
                dump(rv)
            except Exception:
                rv = rv.decode('ascii', 'ignore')

            if rv and self.db.hooked:
                result = self.db.hooked + '\n' + rv
            elif rv:
                result = rv
            else:
                result = self.db.hooked

            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': result,
                'suggest': suggest,
                'duration': duration
            }))
Ejemplo n.º 6
0
Archivo: ui.py Proyecto: elyzabeth/wdb
def eval_(src, *args, **kwargs):
    return eval(compile(src,  '<stdin>', 'eval'), *args, **kwargs)
Ejemplo n.º 7
0
Archivo: ui.py Proyecto: elyzabeth/wdb
    def do_eval(self, data):
        redir = None
        suggest = None
        raw_data = data.strip()
        if raw_data.startswith('!<'):
            filename = raw_data[2:].strip()
            try:
                with open(filename, 'r') as f:
                    raw_data = f.read()
            except Exception:
                self.fail('Eval', 'Unable to read from file %s' % filename)
                return

        lines = raw_data.split('\n')
        if '>!' in lines[-1]:
            try:
                last_line, redir, append = tokenize_redir(raw_data)
            except TokenError:
                last_line = redir = None
                append = False
            if redir and last_line:
                indent = len(lines[-1]) - len(lines[-1].lstrip())
                lines[-1] = indent * u(' ') + last_line
                raw_data = '\n'.join(lines)
        data = raw_data
        # Keep spaces
        raw_data = raw_data.replace(' ', u(' '))
        # Compensate prompt for multi line
        raw_data = raw_data.replace('\n', '\n' + u(' ' * 4))
        duration = None
        with self.db.capture_output(
                with_hook=redir is None) as (out, err):
            try:
                compiled_code = compile(data, '<stdin>', 'single')
                self.db.compile_cache[id(compiled_code)] = data

                l = self.current_locals
                start = time.time()
                execute(compiled_code, self.get_globals(), l)
                duration = int((time.time() - start) * 1000 * 1000)
            except NameError as e:
                m = re.match("name '(.+)' is not defined", str(e))
                if m:
                    name = m.groups()[0]
                    if importable_module(name):
                        suggest = 'import %s' % name

                self.db.hooked = self.handle_exc()
            except Exception:
                self.db.hooked = self.handle_exc()

        if redir and not self.db.hooked:
            try:
                with open(redir, 'a' if append else 'w') as f:
                    f.write('\n'.join(out) + '\n'.join(err) + '\n')
            except Exception:
                self.fail('Eval', 'Unable to write to file %s' % redir)
                return
            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': escape('%s to file %s' % (
                    'Appended' if append else 'Written', redir),)
            }))
        else:
            rv = escape('\n'.join(out) + '\n'.join(err))
            try:
                _ = dump(rv)
            except Exception:
                rv = rv.decode('ascii', 'ignore')

            if rv and self.db.last_obj is None or not self.db.hooked:
                result = rv
            elif not rv:
                result = self.db.hooked
            else:
                result = self.db.hooked + '\n' + rv

            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': result,
                'suggest': suggest,
                'duration': duration
            }))
Ejemplo n.º 8
0
    def do_eval(self, data):
        redir = None
        suggest = None
        raw_data = data.strip()
        if raw_data.startswith('!<'):
            filename = raw_data[2:].strip()
            try:
                with open(filename, 'r') as f:
                    raw_data = f.read()
            except Exception:
                fail(self.db, 'Eval', 'Unable to read from file %s' % filename)
                return

        lines = raw_data.split('\n')
        if '>!' in lines[-1]:
            try:
                last_line, redir, append = tokenize_redir(raw_data)
            except TokenError:
                last_line = redir = None
                append = False
            if redir and last_line:
                indent = len(lines[-1]) - len(lines[-1].lstrip())
                lines[-1] = indent * u(' ') + last_line
                raw_data = '\n'.join(lines)
        data = raw_data
        # Keep spaces
        raw_data = raw_data.replace(' ', u(' '))
        # Compensate prompt for multi line
        raw_data = raw_data.replace('\n', '\n' + u(' ' * 4))

        with self.db.capture_output(with_hook=redir is None) as (out, err):
            try:
                compiled_code = compile(data, '<stdin>', 'single')
                l = self.locals[self.index]
                execute(compiled_code, self.get_globals(), l)
            except NameError as e:
                m = re.match("name '(.+)' is not defined", str(e))
                if m:
                    name = m.groups()[0]
                    for loader, module, ispkg in pkgutil.iter_modules():
                        if module == name:
                            suggest = 'import %s' % module
                            break
                self.db.hooked = handle_exc()
            except Exception:
                self.db.hooked = handle_exc()

        if redir and not self.db.hooked:
            try:
                with open(redir, 'a' if append else 'w') as f:
                    f.write('\n'.join(out) + '\n'.join(err) + '\n')
            except Exception:
                fail(self.db, 'Eval', 'Unable to write to file %s' % redir)
                return
            self.db.send('Print|%s' % dump({
                'for':
                raw_data,
                'result':
                escape(
                    '%s to file %s' %
                    ('Appended' if append else 'Written', redir), )
            }))
        else:
            rv = escape('\n'.join(out) + '\n'.join(err))
            try:
                _ = dump(rv)
            except:
                rv = rv.decode('ascii', 'ignore')

            if rv and self.db.last_obj is None or not self.db.hooked:
                result = rv
            elif not rv:
                result = self.db.hooked
            else:
                result = self.db.hooked + '\n' + rv

            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': result,
                'suggest': suggest
            }))
Ejemplo n.º 9
0
Archivo: ui.py Proyecto: B-Rich/wdb
    def do_eval(self, data):
        redir = None
        raw_data = data.strip()
        if raw_data.startswith('!<'):
            filename = raw_data[2:].strip()
            try:
                with open(filename, 'r') as f:
                    raw_data = f.read()
            except Exception:
                fail(self.db, 'Eval', 'Unable to read from file %s' % filename)
                return

        lines = raw_data.split('\n')
        if '>!' in lines[-1]:
            try:
                last_line, redir, append = tokenize_redir(raw_data)
            except TokenError:
                last_line = redir = None
                append = False
            if redir and last_line:
                indent = len(lines[-1]) - len(lines[-1].lstrip())
                lines[-1] = indent * u(' ') + last_line
                raw_data = '\n'.join(lines)
        data = raw_data
        # Keep spaces
        raw_data = raw_data.replace(' ', u(' '))
        # Compensate prompt for multi line
        raw_data = raw_data.replace('\n', '\n' + u(' ' * 4))

        with self.db.capture_output(
                with_hook=redir is None) as (out, err):
            try:
                print
                compiled_code = compile(data, '<stdin>', 'single')
                l = self.locals[self.index]
                execute(compiled_code, self.get_globals(), l)
            except Exception:
                self.db.hooked = handle_exc()

        if redir and not self.db.hooked:
            try:
                with open(redir, 'a' if append else 'w') as f:
                    f.write('\n'.join(out) + '\n'.join(err) + '\n')
            except Exception:
                fail(self.db, 'Eval', 'Unable to write to file %s' % redir)
                return
            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': escape('%s to file %s' % (
                    'Appended' if append else 'Written', redir))
            }))
        else:
            rv = escape('\n'.join(out) + '\n'.join(err))
            try:
                _ = dump(rv)
            except:
                rv = rv.decode('ascii', 'ignore')

            if rv and self.db.last_obj is None or not self.db.hooked:
                result = rv
            elif not rv:
                result = self.db.hooked
            else:
                result = self.db.hooked + '\n' + rv

            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': result
            }))
Ejemplo n.º 10
0
    def do_eval(self, data):
        redir = None
        imports = []
        raw_data = data.strip()
        if raw_data.startswith('!<'):
            filename = raw_data[2:].strip()
            try:
                with open(filename, 'r') as f:
                    raw_data = f.read()
            except Exception:
                self.fail('Eval', 'Unable to read from file %s' % filename)
                return

        lines = raw_data.split('\n')
        if '>!' in lines[-1]:
            try:
                last_line, redir, append = tokenize_redir(raw_data)
            except TokenError:
                last_line = redir = None
                append = False
            if redir and last_line:
                indent = len(lines[-1]) - len(lines[-1].lstrip())
                lines[-1] = indent * u(' ') + last_line
                raw_data = '\n'.join(lines)
        data = raw_data
        # Keep spaces
        raw_data = raw_data.replace(' ', u(' '))
        # Compensate prompt for multi line
        raw_data = raw_data.replace('\n', '\n' + u(' ' * 4))
        duration = None
        with self.db.capture_output(with_hook=redir is None) as (out, err):
            compiled_code = None
            try:
                compiled_code = compile(data, '<stdin>', 'single')
            except Exception:
                try:
                    compiled_code = compile(data, '<stdin>', 'exec')
                except Exception:
                    maybe_hook = self.handle_exc()

                # Hack from codeop
                e1 = e2 = None
                try:
                    compiled_code = compile(data + '\n', '<stdin>', 'exec')
                except Exception as e:
                    e1 = e
                try:
                    compile(data + '\n\n', '<stdin>', 'exec')
                except Exception as e:
                    e2 = e

                if not compiled_code:
                    if repr(e1) != repr(e2):
                        # Multiline not terminated
                        self.db.send('NewLine')
                        return
                    else:
                        self.db.hooked = maybe_hook

            l = self.current_locals
            start = time.time()
            if compiled_code is not None:
                self.db.compile_cache[id(compiled_code)] = data
                try:
                    execute(compiled_code, self.get_globals(), l)
                except NameError as e:
                    m = re.match("name '(.+)' is not defined", str(e))
                    if m:
                        name = m.groups()[0]
                        if self.db._importmagic_index:
                            scores = self.db._importmagic_index.symbol_scores(
                                name)
                            for _, module, variable in scores:
                                if variable is None:
                                    imports.append('import %s' % module)
                                else:
                                    imports.append(
                                        'from %s import %s' % (
                                            module, variable))
                        elif importable_module(name):
                            imports.append('import %s' % name)

                    self.db.hooked = self.handle_exc()
                except Exception:
                    self.db.hooked = self.handle_exc()

        duration = int((time.time() - start) * 1000 * 1000)
        if redir and not self.db.hooked:
            try:
                with open(redir, 'a' if append else 'w') as f:
                    f.write('\n'.join(out) + '\n'.join(err) + '\n')
            except Exception:
                self.fail('Eval', 'Unable to write to file %s' % redir)
                return
            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': escape('%s to file %s' % (
                    'Appended' if append else 'Written', redir),)
            }))
        else:
            rv = escape('\n'.join(out) + '\n'.join(err))
            try:
                dump(rv)
            except Exception:
                rv = rv.decode('ascii', 'ignore')

            if rv and self.db.hooked:
                result = self.db.hooked + '\n' + rv
            elif rv:
                result = rv
            else:
                result = self.db.hooked

            self.db.send('Print|%s' % dump({
                'for': raw_data,
                'result': result,
                'duration': duration
            }))
            if imports:
                self.db.send('Suggest|%s' % dump({
                    'imports': imports
                }))