Example #1
0
def dis(x=None):
    """
    Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.
    """

    if x is None:
        dismodule.distb()
        return
    if type(x) is types.InstanceType:
        x = x.__class__
    if hasattr(x, 'im_func'):
        x = x.im_func
    if isinstance(x, types.FunctionType):
        x = sys.get_func_code(x)
    if hasattr(x, '__dict__'):
        items = x.__dict__.items()
        items.sort()
        for name, x1 in items:
            if type(x1) in (types.MethodType, types.FunctionType,
                            types.CodeType, types.ClassType):
                print "Disassembly of %s:" % name
                try:
                    dis(x1)
                except TypeError, msg:
                    print "Sorry:", msg
                print
Example #2
0
def dis(x=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        dismodule.distb()
        return
    if hasattr(x, '__func__'):
        x = x.__func__
    if hasattr(x, '__code__'):
        x = getattr(x, '__code__')
    if isinstance(x, FunctionType):
        x = sys.get_func_code(x)
    if hasattr(x, '__dict__'):
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(
                    x1,
                (types.MethodType, types.FunctionType, types.CodeType, type)):
                print("Disassembly of %s:" % name)
                try:
                    dis(x1)
                except TypeError as msg:
                    print("Sorry:", msg)
                print()
    elif hasattr(x, 'co_code'):
        dismodule.disassemble(x)
    elif isinstance(x, (bytes, bytearray)):
        dismodule.disassemble_string(x)
    else:
        raise TypeError("don't know how to disassemble %s objects" %
                        type(x).__name__)
    def disassembleSource(self):
        import dis
        try:
            code = compile(self.data, self.filename, 'exec')
        except:
            oldOut = sys.stdout
            sys.stdout = Utils.PseudoFileOutStore()
            try:
                print _("''' Code does not compile\n\n    Disassembly of Traceback:\n'''")
                try:
                    dis.distb(sys.exc_info()[2])
                except:
                    print _("''' Could not disassemble traceback '''\n")
                return sys.stdout.read()
            finally:
                sys.stdout = oldOut

        oldOut = sys.stdout
        sys.stdout = Utils.PseudoFileOutStore()
        try:
            try:
                dis.disco(code)
            except:
                raise
            return sys.stdout.read()
        finally:
            sys.stdout = oldOut

        return 'Invisible code'
Example #4
0
def dis(x=None):
    """
    Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.
    """

    if x is None:
        dismodule.distb()
        return
    if type(x) is types.InstanceType:
        x = x.__class__
    if hasattr(x, "im_func"):
        x = x.im_func
    if isinstance(x, types.FunctionType):
        x = sys.get_func_code(x)
    if hasattr(x, "__dict__"):
        items = x.__dict__.items()
        items.sort()
        for name, x1 in items:
            if type(x1) in (types.MethodType, types.FunctionType, types.CodeType, types.ClassType):
                print "Disassembly of %s:" % name
                try:
                    dis(x1)
                except TypeError, msg:
                    print "Sorry:", msg
                print
Example #5
0
    def disassembleSource(self):
        import dis
        try:
            code = compile(self.data, self.filename, 'exec')
        except:
            oldOut = sys.stdout
            sys.stdout = Utils.PseudoFileOutStore()
            try:
                print _(
                    "''' Code does not compile\n\n    Disassembly of Traceback:\n'''"
                )
                try:
                    dis.distb(sys.exc_info()[2])
                except:
                    print _("''' Could not disassemble traceback '''\n")
                return sys.stdout.read()
            finally:
                sys.stdout = oldOut

        oldOut = sys.stdout
        sys.stdout = Utils.PseudoFileOutStore()
        try:
            try:
                dis.disco(code)
            except:
                raise
            return sys.stdout.read()
        finally:
            sys.stdout = oldOut

        return 'Invisible code'
def dis(obj, x=None, start_line=-1, end_line=None, relative_pos=False):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        distb()
        return
    if type(x) is types.InstanceType:
        x = x.__class__
    if hasattr(x, 'im_func'):
        obj.msg("Dissassembly of %s: " % x)
        x = x.im_func
    if hasattr(x, 'func_code'):
        obj.msg("Dissassembly of %s: " % x)
        x = x.func_code
    elif hasattr(x, 'f_code'):
        obj.msg("Dissassembly of %s: " % x)
        x = x.f_code
        pass
    elif inspect.iscode(x):
        pass
    if hasattr(x, '__dict__'):
        items = x.__dict__.items()
        items.sort()
        for name, x1 in items:
            if type(x1) in (types.MethodType, types.FunctionType,
                            types.CodeType, types.ClassType):
                try:
                    dis(obj, x1, start_line=start_line, end_line=end_line)
                except TypeError, msg:
                    obj.errmsg("Sorry:", msg)
                obj.msg("")
Example #7
0
def dis(x=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        dismodule.distb()
        return
    if hasattr(x, '__func__'):
        x = x.__func__
    if hasattr(x, '__code__'):
        x = getattr(x, '__code__')
    if isinstance(x, FunctionType):
        x = sys.get_func_code(x)
    if hasattr(x, '__dict__'):
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, (types.MethodType, types.FunctionType,
                               types.CodeType, type)):
                print("Disassembly of %s:" % name)
                try:
                    dis(x1)
                except TypeError as msg:
                    print("Sorry:", msg)
                print()
    elif hasattr(x, 'co_code'):
        dismodule.disassemble(x)
    elif isinstance(x, (bytes, bytearray)):
        dismodule.disassemble_string(x)
    else:
        raise TypeError("don't know how to disassemble %s objects" %
                        type(x).__name__)
Example #8
0
def calculate(x, y):
    try:
        return x / y
    except Exception as e:
        #This will point out that the error happens on line 5 with the instruction BINARY_TRUE_DIVIDE
        dis.distb(e.__traceback__)
    finally:
        print("Traceback was disasembled.")
Example #9
0
def dis(msg, msg_nocr, section, errmsg, x=None, start_line=-1, end_line=None,
        relative_pos = False, color=True):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return
    if type(x) is object:
        x = x.__class__
    if hasattr(x, 'f_code'):
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            pass
        x = x.f_code
        section("Disassembly of %s: " % x)
        disassemble(msg, msg_nocr, section, x, lasti=lasti,
                    start_line=start_line, end_line=end_line,
                    relative_pos = relative_pos)
        return
    elif hasattr(x, '__func__'):  # Method
        x = x.__func__
    if hasattr(x, '__code__'):  # Function
        x = x.__code__
        pass
    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                section("Disassembly of %s: " % x)
                try:
                    dis(msg, msg_nocr, section, errmsg, x1,
                        start_line=start_line, end_line=end_line,
                        relative_pos = relative_pos)
                    msg("")
                except TypeError as msg:
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'): # Code object
        section("Disassembly of %s: " % x)
        disassemble(msg, msg_nocr, section, x, lasti=lasti,
                    start_line=start_line, end_line=end_line,
                    relative_pos = relative_pos)
    elif isinstance(x, (bytes, bytearray)): # Raw bytecode
        _disassemble_bytes(x)
    elif isinstance(x, str):    # Source code
        disassemble_string(msg, msg_nocr, x,)
    else:
       errmsg("Don't know how to disassemble %s objects." %
              type(x).__name__)
    return
Example #10
0
def dis(msg, msg_nocr, section, errmsg, x=None, start_line=-1, end_line=None,
        relative_pos = False, color=True):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return
    if isinstance(x, types.InstanceType):
        x = x.__class__
    if hasattr(x, 'im_func'):
        section("Disassembly of %s: " % x)
        x = x.im_func
    if hasattr(x, 'func_code'):
        section("Disassembly of %s: " % x)
        x = x.func_code
    elif hasattr(x, 'f_code'):
        section("Disassembly of %s: " % x)
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            pass
        x = x.f_code
        pass
    elif inspect.iscode(x):
        pass
    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                section("Disassembly of %s: " % x)
                try:
                    dis(msg, msg_nocr, section, errmsg, x1,
                        start_line=start_line, end_line=end_line,
                        relative_pos = relative_pos)
                    msg("")
                except TypeError:
                    _, msg, _ = sys.exc_info()
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'):  # Code object
        section("Disassembly of %s: " % x)
        disassemble(msg, msg_nocr, section, x, lasti=lasti,
                    start_line=start_line, end_line=end_line,
                    relative_pos = relative_pos)
    elif isinstance(x, str):    # Source code
        disassemble_string(msg, msg_nocr, x,)
    else:
        errmsg("Don't know how to disassemble %s objects." %
               type(x).__name__)
    return
Example #11
0
 def test_distb(self):
     """
     The traceback captured by a L{Failure} is compatible with the stdlib
     L{dis.distb} function as used in post-mortem debuggers. Specifically,
     it doesn't cause that function to raise an exception.
     """
     f = getDivisionFailure()
     buf = StringIO()
     distb(f.getTracebackObject(), file=buf)
     # The bytecode details vary across Python versions, so we only check
     # that the arrow pointing at the source of the exception is present.
     self.assertIn(" --> ", buf.getvalue())
Example #12
0
def dis37(x=None, depth=None):
    """Disassemble classes, methods, functions, and other compiled objects.

    With no argument, disassemble the last traceback.

    Compiled objects currently include generator objects, async generator
    objects, and coroutine objects, all of which store their code object
    in a special attribute.
    """
    if x is None:
        distb()
        return
    # Extract functions from methods.
    if hasattr(x, '__func__'):
        x = x.__func__
    # Extract compiled code objects from...
    if hasattr(x, '__code__'):  # ...a function, or
        x = x.__code__
    elif hasattr(x, 'gi_code'):  #...a generator object, or (added in Py 3.5)
        x = x.gi_code
    elif hasattr(x, 'ag_code'
                 ):  #...an asynchronous generator object, or (added in Py 3.7)
        x = x.ag_code
    elif hasattr(x, 'cr_code'):  #...a coroutine. (added in Py 3.7)
        x = x.cr_code
    # Perform the disassembly.
    if hasattr(x, '__dict__'):  # Class or module (added in Py 3.7)
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                print("Disassembly of %s:" % name)
                try:
                    dis(x1, depth=depth)
                except TypeError as msg:
                    print("Sorry:", msg)
                print()
    elif hasattr(x, 'co_code'):  # Code object
        _disassemble_recursive(x, depth=depth)
    elif isinstance(x, (bytes, bytearray)):  # Raw bytecode
        _disassemble_bytes(x)
    elif isinstance(x, str):  # Source code
        _disassemble_str(x, depth=depth)
    else:
        raise TypeError("don't know how to disassemble %s objects" %
                        type(x).__name__)
Example #13
0
def dis(obj, x=None, start_line=-1, end_line=None, relative_pos = False):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    if x is None:
        distb()
        return
    if type(x) is types.InstanceType:
        x = x.__class__
    if hasattr(x, 'im_func'):
        obj.msg("Dissassembly of %s: " % x)
        x = x.im_func
    if hasattr(x, 'func_code'):
        obj.msg("Dissassembly of %s: " % x)
        x = x.func_code
    elif hasattr(x, 'f_code'):
        obj.msg("Dissassembly of %s: " % x)
        x = x.f_code
        pass
    elif inspect.iscode(x):
        pass
    if hasattr(x, '__dict__'):
        items = x.__dict__.items()
        items.sort()
        for name, x1 in items:
            if type(x1) in (types.MethodType,
                            types.FunctionType,
                            types.CodeType,
                            types.ClassType):
                try:
                    dis(obj, x1, start_line=start_line, end_line=end_line)
                except TypeError, msg:
                    obj.errmsg("Sorry:", msg)
                obj.msg("")
Example #14
0
def run_jobs(job: Callable,
             working_set: Iterable,
             setup_function: Callable = _dummy,
             setupargs: Sequence[Any] = (),
             parse_function: Callable = _dummy,
             process_initializer: Callable = _dummy,
             initargs: Sequence[Any] = (),
             reduce_function: Callable[[T, Any], T] = (lambda x, _: x),
             reduce_start: T = None,
             override_seed: Optional[bytes] = None) -> T:
    logger = getLogger('JobRunner')
    logger.debug('Checking configuration files')
    make_config_files()

    machines = get_machines()
    names = tuple(machines)
    weights = tuple(thread_weight * threads
                    for thread_weight, threads in machines.values())
    logger.debug('Loaded machines %r', machines)
    config = get_config()

    dialog = "\n".join(
        ("Which node am I?", *("{}:\t{}".format(idx, name)
                               for idx, name in enumerate(names)), ""))

    while True:
        resp = input(dialog)
        if resp == 'N/A':
            logger.info('Instantiated without an ID. All jobs will be run.')
            ID = None
        else:
            try:
                ID = int(resp)
                logger.info('Instantiated as ID %i', ID)
            except Exception:
                continue
        break

    TOTAL = sum(weights)

    working_set = list(working_set)
    lw = STOP = len(working_set)

    entropy = get_entropy(working_set)
    logger.debug('Entropy: %s', entropy.hex())
    seed = override_seed or entropy
    if seed is override_seed:
        logger.info('Using override seed for random module: %r', seed)
    random_obj = Random(seed)
    indexed_set = [(idx, (*items, copy(random_obj), config))
                   for idx, items in enumerate(working_set)]
    random_obj.shuffle(indexed_set)

    if ID is not None:
        START = sum(weights[:ID]) * lw // TOTAL
        STOP = sum(weights[:ID + 1]) * lw // TOTAL
        indexed_set = indexed_set[START:STOP]
    else:
        START = 0
    response = ''

    while not response.lower().startswith('y'):
        response = input(
            ('I am {0}. Please verify this is correct.  Checksum: {1}.\n'
             '{2} jobs now queued ({3}-{4}). Total size {5}. (y/n)? ').format(
                 "N/A" if ID is None else names[ID], entropy.hex(),
                 len(indexed_set), START, STOP - 1, lw))
        if response.lower().startswith('n'):
            exit(1)

    if ID is None:
        num_cores = cpu_count()
    else:
        num_cores = machines[names[ID]][1]
    logger.info('%i jobs now queued (%i-%i). Total size %i', len(indexed_set),
                START, STOP - 1, lw)
    logger.info(f"This machine will use {num_cores} worker cores")

    setup_function(config, *setupargs)

    start_time = last_time = time()
    current = reduce_start

    with RESULTS_CSV.open('w') as f:
        f.write(CSV_HEADER.read_text() + '\n')

    install_mp_handler()
    with ProgressPool(num_cores,
                      initializer=process_initializer,
                      initargs=initargs) as p:
        renicer = Thread(target=renicer_thread, args=(p, ), daemon=True)
        renicer.start()
        for idx, (job_id, result) in enumerate(p.istarmap_unordered(
                partial(_indexed_job, job),
                indexed_set,
                chunksize=int(config['ProgressPool']['chunksize']),
                bar_length=int(config['ProgressPool']['bar_length']),
                style=Style(int(config['ProgressPool']['style'])),
        ),
                                               start=1):
            logger.info("Answer received: %i/%i (%0.2f%%)", idx,
                        len(working_set), 100.0 * idx / len(working_set))
            try:
                current = reduce_function(cast(T, current), result)
            except Exception:
                logger.exception("HEY! Your reduce function messed up!")
                try:
                    buff = StringIO()
                    distb(file=buff)
                    buff.seek(0)
                    logger.error(buff.read())
                except Exception:  # might fail in a C module?
                    pass
            new_time = time()
            if result is None:
                result = ()
            if config.getboolean('results', 'compress'):

                def open_method(name, mode='rt'):
                    return open_gzip(str(name) + '.gz', mode)

            else:
                open_method = open

            with open_method(config['results']['file_name'], mode='at') as f:
                results_writer = writer(f)
                meta = []
                if config.getboolean('results', 'include_start_time'):
                    meta.append(start_time)
                if config.getboolean('results', 'include_job_interval'):
                    meta.append(new_time - last_time)
                if config.getboolean('results', 'include_job_done_time'):
                    meta.append(new_time)
                if config.getboolean('results', 'include_job_id'):
                    meta.append(job_id)
                results_writer.writerow((*meta, *result))
            parse_function(config, *meta, *result)
            last_time = new_time
    return cast(T, current)
Example #15
0
#! /usr/bin/env/python
# -*- coding:utf-8 -*-

i = 1
j = 0
k = 3

# ... many lines removed ...

try:
    result = k * (i / j) + (i / k)
except:
    import dis
    import sys
    exc_type, exc_value, exc_tb = sys.exc_info()
    dis.distb(exc_tb)
Example #16
0
def dis(msg,
        msg_nocr,
        section,
        errmsg,
        x=None,
        start_line=-1,
        end_line=None,
        relative_pos=False,
        color=True):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return
    if type(x) is object:
        x = x.__class__
    if hasattr(x, 'f_code'):
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            pass
        x = x.f_code
        section("Disassembly of %s: " % x)
        disassemble(msg,
                    msg_nocr,
                    section,
                    x,
                    lasti=lasti,
                    start_line=start_line,
                    end_line=end_line,
                    relative_pos=relative_pos)
        return
    elif hasattr(x, '__func__'):  # Method
        x = x.__func__
    if hasattr(x, '__code__'):  # Function
        x = x.__code__
        pass
    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                section("Disassembly of %s: " % x)
                try:
                    dis(msg,
                        msg_nocr,
                        section,
                        errmsg,
                        x1,
                        start_line=start_line,
                        end_line=end_line,
                        relative_pos=relative_pos)
                    msg("")
                except TypeError as msg:
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'):  # Code object
        section("Disassembly of %s: " % x)
        disassemble(msg,
                    msg_nocr,
                    section,
                    x,
                    lasti=lasti,
                    start_line=start_line,
                    end_line=end_line,
                    relative_pos=relative_pos)
    elif isinstance(x, (bytes, bytearray)):  # Raw bytecode
        _disassemble_bytes(x)
    elif isinstance(x, str):  # Source code
        disassemble_string(
            msg,
            msg_nocr,
            x,
        )
    else:
        errmsg("Don't know how to disassemble %s objects." % type(x).__name__)
    return
Example #17
0
def dis(msg, msg_nocr, section, errmsg, x=None, start_line=-1, end_line=None,
        relative_pos = False, highlight='light', start_offset=0, end_offset=None,
        include_header=False):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return None, None
    if start_offset is None:
        start_offset = 0
    mess = ''
    if start_line > 1:
        mess += "from line %d " % start_line
    elif start_offset > 1:
        mess = "from offset %d " % start_offset
    if end_line:
        mess += "to line %d" % end_line
    elif end_offset:
        mess += "to offset %d" % end_offset

    sectioned = False


    # Try to dogpaddle to the code object for the type setting x
    if hasattr(types, 'InstanceType') and isinstance(x, types.InstanceType):
        x = x.__class__
    if inspect.ismethod(x):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        x = x.im_func
    elif inspect.isfunction(x) or inspect.isgeneratorfunction(x):
        section("Disassembly of %s: %s" % (x, mess))
        x = x.func_code
        sectioned = True
    elif inspect.isgenerator(x):
        section("Disassembly of %s: %s" % (x, mess))
        frame = x.gi_frame
        lasti = frame.f_last_i
        x = x.gi_code
        sectioned = True
    elif inspect.isframe(x):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            if lasti == -1: lasti = 0
            pass
        opc = get_opcode(PYTHON_VERSION, IS_PYPY)
        x = x.f_code
        if include_header:
            header_lines = Bytecode(x, opc).info().split("\n")
            header = '\n'.join([format_token(Mformat.Comment, h) for h in header_lines])
            msg(header)
        pass
    elif inspect.iscode(x):
        pass

    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                if not sectioned:
                    section("Disassembly of %s: " % x)
                try:
                    dis(msg, msg_nocr, section, errmsg, x1,
                        start_line=start_line, end_line=end_line,
                        relative_pos = relative_pos)
                    msg("")
                except TypeError:
                    _, msg, _ = sys.exc_info()
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'):  # Code object
        if not sectioned:
            section("Disassembly of %s: " % x)
        return disassemble(msg, msg_nocr, section, x, lasti=lasti,
                           start_line=start_line, end_line=end_line,
                           relative_pos = relative_pos,
                           highlight = highlight,
                           start_offset = start_offset,
                           end_offset = end_offset)
    elif isinstance(x, str):    # Source code
        return disassemble_string(msg, msg_nocr, x,)
    else:
        errmsg("Don't know how to disassemble %s objects." %
               type(x).__name__)
    return None, None
Example #18
0
def dis(msg,
        msg_nocr,
        section,
        errmsg,
        x=None,
        start_line=-1,
        end_line=None,
        relative_pos=False,
        color=True):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return
    if type(x) is types.InstanceType:
        x = x.__class__
    if hasattr(x, 'im_func'):
        section("Disassembly of %s: " % x)
        x = x.im_func
    if hasattr(x, 'func_code'):
        section("Disassembly of %s: " % x)
        x = x.func_code
    elif hasattr(x, 'f_code'):
        section("Disassembly of %s: " % x)
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            pass
        x = x.f_code
        pass
    elif inspect.iscode(x):
        pass
    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                section("Disassembly of %s: " % x)
                try:
                    dis(msg,
                        msg_nocr,
                        section,
                        errmsg,
                        x1,
                        start_line=start_line,
                        end_line=end_line,
                        relative_pos=relative_pos)
                    msg("")
                except TypeError:
                    _, msg, _ = sys.exc_info()
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'):  # Code object
        section("Disassembly of %s: " % x)
        disassemble(msg,
                    msg_nocr,
                    section,
                    x,
                    lasti=lasti,
                    start_line=start_line,
                    end_line=end_line,
                    relative_pos=relative_pos)
    elif isinstance(x, str):  # Source code
        disassemble_string(
            msg,
            msg_nocr,
            x,
        )
    else:
        errmsg("Don't know how to disassemble %s objects." % type(x).__name__)
    return
Example #19
0
def dis(msg, msg_nocr, section, errmsg, x=None, start_line=-1, end_line=None,
        relative_pos = False, highlight='light', start_offset=0, end_offset=None,
        include_header=False):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return None, None
    if start_offset is None:
        start_offset = 0
    mess = ''
    if start_line > 1:
        mess += "from line %d " % start_line
    elif start_offset > 1:
        mess = "from offset %d " % start_offset
    if end_line:
        mess += "to line %d" % end_line
    elif end_offset:
        mess += "to offset %d" % end_offset

    sectioned = False


    # Try to dogpaddle to the code object for the type setting x
    if hasattr(types, 'InstanceType') and isinstance(x, types.InstanceType):
        x = x.__class__
    if inspect.ismethod(x):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        x = x.im_func
    elif inspect.isfunction(x) or inspect.isgeneratorfunction(x):
        section("Disassembly of %s: %s" % (x, mess))
        x = x.func_code
        sectioned = True
    elif inspect.isgenerator(x):
        section("Disassembly of %s: %s" % (x, mess))
        frame = x.gi_frame
        lasti = frame.f_last_i
        x = x.gi_code
        sectioned = True
    elif inspect.isframe(x):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            if lasti == -1: lasti = 0
            pass
        opc = get_opcode(PYTHON_VERSION, IS_PYPY)
        x = x.f_code
        if include_header:
            header_lines = Bytecode(x, opc).info().split("\n")
            header = '\n'.join([format_token(Mformat.Comment, h) for h in header_lines])
            msg(header)
        pass
    elif inspect.iscode(x):
        pass

    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                if not sectioned:
                    section("Disassembly of %s: " % x)
                try:
                    dis(msg, msg_nocr, section, errmsg, x1,
                        start_line=start_line, end_line=end_line,
                        relative_pos = relative_pos)
                    msg("")
                except TypeError:
                    _, msg, _ = sys.exc_info()
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'):  # Code object
        if not sectioned:
            section("Disassembly of %s: " % x)
        return disassemble(msg, msg_nocr, section, x, lasti=lasti,
                           start_line=start_line, end_line=end_line,
                           relative_pos = relative_pos,
                           highlight = highlight,
                           start_offset = start_offset,
                           end_offset = end_offset)
    elif isinstance(x, str):    # Source code
        return disassemble_string(msg, msg_nocr, x,)
    else:
        errmsg("Don't know how to disassemble %s objects." %
               type(x).__name__)
    return None, None
Example #20
0
def dis(msg,
        msg_nocr,
        section,
        errmsg,
        x=None,
        start_line=-1,
        end_line=None,
        relative_pos=False,
        highlight='light',
        start_offset=0,
        end_offset=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return
    mess = ''
    if start_line > 1:
        mess += " from line %d" % start_line
    if end_line:
        mess += " to line %d" % end_line
    if start_offset > 1:
        mess = " from offset %d" % start_offset
    if end_offset:
        mess += " to offset %d" % end_offset

    sectioned = False
    if isinstance(x, types.InstanceType):
        x = x.__class__
    if hasattr(x, 'im_func'):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        x = x.im_func
    if hasattr(x, 'func_code'):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        x = x.func_code
    elif hasattr(x, 'f_code'):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            pass
        x = x.f_code
        pass
    elif inspect.iscode(x):
        pass
    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                if not sectioned:
                    section("Disassembly of %s: " % x)
                try:
                    dis(msg,
                        msg_nocr,
                        section,
                        errmsg,
                        x1,
                        start_line=start_line,
                        end_line=end_line,
                        relative_pos=relative_pos)
                    msg("")
                except TypeError:
                    _, msg, _ = sys.exc_info()
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'):  # Code object
        if not sectioned:
            section("Disassembly of %s: " % x)
        disassemble(msg,
                    msg_nocr,
                    section,
                    x,
                    lasti=lasti,
                    start_line=start_line,
                    end_line=end_line,
                    relative_pos=relative_pos,
                    highlight=highlight,
                    start_offset=start_offset,
                    end_offset=end_offset)
    elif isinstance(x, str):  # Source code
        disassemble_string(
            msg,
            msg_nocr,
            x,
        )
    else:
        errmsg("Don't know how to disassemble %s objects." % type(x).__name__)
    return
Example #21
0
# vals
i = 1
j = 0
k = 3

try:
    res = k * (i / j) + (i / k)

except Exception:

    import dis
    import sys

    exc_type, exc_val, exc_trabk = sys.exc_info()
    dis.distb(exc_trabk)
#!/usr/bin/env python
# encoding: utf-8

i = 1
j = 0
k = 3

# ... molte righe rimosse ...

try:
    result = k * (i / j) + (i / k)
except:
    import dis
    import sys
    exc_type, exc_value, exc_tb = sys.exc_info()
    dis.distb(exc_tb)
import dis

j = 4
i = i + 4

dis.distb()
Example #24
0
def dis(msg, msg_nocr, section, errmsg, x=None, start_line=-1, end_line=None,
        relative_pos = False, highlight='light', start_offset=0, end_offset=None):
    """Disassemble classes, methods, functions, or code.

    With no argument, disassemble the last traceback.

    """
    lasti = -1
    if x is None:
        distb()
        return
    mess = ''
    if start_line > 1:
        mess += " from line %d" % start_line
    if end_line:
        mess += " to line %d" % end_line
    if start_offset > 1:
        mess = " from offset %d" % start_offset
    if end_offset:
        mess += " to offset %d" % end_offset

    sectioned = False
    if isinstance(x, types.InstanceType):
        x = x.__class__
    if hasattr(x, 'im_func'):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        x = x.im_func
    if hasattr(x, 'func_code'):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        x = x.func_code
    elif hasattr(x, 'f_code'):
        section("Disassembly of %s: %s" % (x, mess))
        sectioned = True
        if hasattr(x, 'f_lasti'):
            lasti = x.f_lasti
            pass
        x = x.f_code
        pass
    elif inspect.iscode(x):
        pass
    if hasattr(x, '__dict__'):  # Class or module
        items = sorted(x.__dict__.items())
        for name, x1 in items:
            if isinstance(x1, _have_code):
                if not sectioned:
                    section("Disassembly of %s: " % x)
                try:
                    dis(msg, msg_nocr, section, errmsg, x1,
                        start_line=start_line, end_line=end_line,
                        relative_pos = relative_pos)
                    msg("")
                except TypeError:
                    _, msg, _ = sys.exc_info()
                    errmsg("Sorry:", msg)
                    pass
                pass
            pass
        pass
    elif hasattr(x, 'co_code'):  # Code object
        if not sectioned:
            section("Disassembly of %s: " % x)
        disassemble(msg, msg_nocr, section, x, lasti=lasti,
                    start_line=start_line, end_line=end_line,
                    relative_pos = relative_pos,
                    highlight = highlight,
                    start_offset = start_offset,
                    end_offset = end_offset)
    elif isinstance(x, str):    # Source code
        disassemble_string(msg, msg_nocr, x,)
    else:
        errmsg("Don't know how to disassemble %s objects." %
               type(x).__name__)
    return
Example #25
0
 def update_event(self, inp=-1):
     self.set_output_val(0, dis.distb(self.input(0)))