Back to index

python3.2  3.2.2
Functions | Variables
dis Namespace Reference

Functions

def _try_compile
def dis
def distb
def pretty_flags
def code_info
def _format_code_info
def show_code
def disassemble
def _disassemble_bytes
def _disassemble_str
def findlabels
def findlinestarts
def _test

Variables

list __all__
tuple _have_code = (types.MethodType, types.FunctionType, types.CodeType, type)
dictionary COMPILER_FLAG_NAMES
 disco = disassemble

Detailed Description

Disassembler of Python byte code into mnemonics.

Function Documentation

def dis._disassemble_bytes (   code,
  lasti = -1,
  varnames = None,
  names = None,
  constants = None 
) [private]

Definition at line 196 of file dis.py.

00196 
00197                        constants=None):
00198     labels = findlabels(code)
00199     n = len(code)
00200     i = 0
00201     while i < n:
00202         op = code[i]
00203         if i == lasti: print('-->', end=' ')
00204         else: print('   ', end=' ')
00205         if i in labels: print('>>', end=' ')
00206         else: print('  ', end=' ')
00207         print(repr(i).rjust(4), end=' ')
00208         print(opname[op].ljust(15), end=' ')
00209         i = i+1
00210         if op >= HAVE_ARGUMENT:
00211             oparg = code[i] + code[i+1]*256
00212             i = i+2
00213             print(repr(oparg).rjust(5), end=' ')
00214             if op in hasconst:
00215                 if constants:
00216                     print('(' + repr(constants[oparg]) + ')', end=' ')
00217                 else:
00218                     print('(%d)'%oparg, end=' ')
00219             elif op in hasname:
00220                 if names is not None:
00221                     print('(' + names[oparg] + ')', end=' ')
00222                 else:
00223                     print('(%d)'%oparg, end=' ')
00224             elif op in hasjrel:
00225                 print('(to ' + repr(i + oparg) + ')', end=' ')
00226             elif op in haslocal:
00227                 if varnames:
00228                     print('(' + varnames[oparg] + ')', end=' ')
00229                 else:
00230                     print('(%d)' % oparg, end=' ')
00231             elif op in hascompare:
00232                 print('(' + cmp_op[oparg] + ')', end=' ')
00233         print()

Here is the call graph for this function:

Here is the caller graph for this function:

def dis._disassemble_str (   source) [private]
Compile the source string, then disassemble the code object.

Definition at line 234 of file dis.py.

00234 
00235 def _disassemble_str(source):
00236     """Compile the source string, then disassemble the code object."""
00237     disassemble(_try_compile(source, '<dis>'))

Here is the call graph for this function:

Here is the caller graph for this function:

def dis._format_code_info (   co) [private]

Definition at line 112 of file dis.py.

00112 
00113 def _format_code_info(co):
00114     lines = []
00115     lines.append("Name:              %s" % co.co_name)
00116     lines.append("Filename:          %s" % co.co_filename)
00117     lines.append("Argument count:    %s" % co.co_argcount)
00118     lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount)
00119     lines.append("Number of locals:  %s" % co.co_nlocals)
00120     lines.append("Stack size:        %s" % co.co_stacksize)
00121     lines.append("Flags:             %s" % pretty_flags(co.co_flags))
00122     if co.co_consts:
00123         lines.append("Constants:")
00124         for i_c in enumerate(co.co_consts):
00125             lines.append("%4d: %r" % i_c)
00126     if co.co_names:
00127         lines.append("Names:")
00128         for i_n in enumerate(co.co_names):
00129             lines.append("%4d: %s" % i_n)
00130     if co.co_varnames:
00131         lines.append("Variable names:")
00132         for i_n in enumerate(co.co_varnames):
00133             lines.append("%4d: %s" % i_n)
00134     if co.co_freevars:
00135         lines.append("Free variables:")
00136         for i_n in enumerate(co.co_freevars):
00137             lines.append("%4d: %s" % i_n)
00138     if co.co_cellvars:
00139         lines.append("Cell variables:")
00140         for i_n in enumerate(co.co_cellvars):
00141             lines.append("%4d: %s" % i_n)
00142     return "\n".join(lines)

Here is the call graph for this function:

Here is the caller graph for this function:

def dis._test ( ) [private]
Simple test program to disassemble a file.

Definition at line 287 of file dis.py.

00287 
00288 def _test():
00289     """Simple test program to disassemble a file."""
00290     if sys.argv[1:]:
00291         if sys.argv[2:]:
00292             sys.stderr.write("usage: python dis.py [-|file]\n")
00293             sys.exit(2)
00294         fn = sys.argv[1]
00295         if not fn or fn == "-":
00296             fn = None
00297     else:
00298         fn = None
00299     if fn is None:
00300         f = sys.stdin
00301     else:
00302         f = open(fn)
00303     source = f.read()
00304     if fn is not None:
00305         f.close()
00306     else:
00307         fn = "<stdin>"
00308     code = compile(source, fn, "exec")
00309     dis(code)

Here is the call graph for this function:

def dis._try_compile (   source,
  name 
) [private]
Attempts to compile the given source, first as an expression and
   then as a statement if the first approach fails.

   Utility function to accept strings in functions that otherwise
   expect code objects

Definition at line 15 of file dis.py.

00015 
00016 def _try_compile(source, name):
00017     """Attempts to compile the given source, first as an expression and
00018        then as a statement if the first approach fails.
00019 
00020        Utility function to accept strings in functions that otherwise
00021        expect code objects
00022     """
00023     try:
00024         c = compile(source, name, 'eval')
00025     except SyntaxError:
00026         c = compile(source, name, 'exec')
00027     return c

Here is the call graph for this function:

Here is the caller graph for this function:

def dis.code_info (   x)
Formatted details of methods, functions, or code.

Definition at line 98 of file dis.py.

00098 
00099 def code_info(x):
00100     """Formatted details of methods, functions, or code."""
00101     if hasattr(x, '__func__'): # Method
00102         x = x.__func__
00103     if hasattr(x, '__code__'): # Function
00104         x = x.__code__
00105     if isinstance(x, str):     # Source code
00106         x = _try_compile(x, "<code_info>")
00107     if hasattr(x, 'co_code'):  # Code object
00108         return _format_code_info(x)
00109     else:
00110         raise TypeError("don't know how to disassemble %s objects" %
00111                         type(x).__name__)

Here is the call graph for this function:

Here is the caller graph for this function:

def dis.dis (   x = None)
Disassemble classes, methods, functions, or code.

With no argument, disassemble the last traceback.

Definition at line 28 of file dis.py.

00028 
00029 def dis(x=None):
00030     """Disassemble classes, methods, functions, or code.
00031 
00032     With no argument, disassemble the last traceback.
00033 
00034     """
00035     if x is None:
00036         distb()
00037         return
00038     if hasattr(x, '__func__'):  # Method
00039         x = x.__func__
00040     if hasattr(x, '__code__'):  # Function
00041         x = x.__code__
00042     if hasattr(x, '__dict__'):  # Class or module
00043         items = sorted(x.__dict__.items())
00044         for name, x1 in items:
00045             if isinstance(x1, _have_code):
00046                 print("Disassembly of %s:" % name)
00047                 try:
00048                     dis(x1)
00049                 except TypeError as msg:
00050                     print("Sorry:", msg)
00051                 print()
00052     elif hasattr(x, 'co_code'): # Code object
00053         disassemble(x)
00054     elif isinstance(x, (bytes, bytearray)): # Raw bytecode
00055         _disassemble_bytes(x)
00056     elif isinstance(x, str):    # Source code
00057         _disassemble_str(x)
00058     else:
00059         raise TypeError("don't know how to disassemble %s objects" %
00060                         type(x).__name__)

Here is the call graph for this function:

Here is the caller graph for this function:

def dis.disassemble (   co,
  lasti = -1 
)
Disassemble a code object.

Definition at line 147 of file dis.py.

00147 
00148 def disassemble(co, lasti=-1):
00149     """Disassemble a code object."""
00150     code = co.co_code
00151     labels = findlabels(code)
00152     linestarts = dict(findlinestarts(co))
00153     n = len(code)
00154     i = 0
00155     extended_arg = 0
00156     free = None
00157     while i < n:
00158         op = code[i]
00159         if i in linestarts:
00160             if i > 0:
00161                 print()
00162             print("%3d" % linestarts[i], end=' ')
00163         else:
00164             print('   ', end=' ')
00165 
00166         if i == lasti: print('-->', end=' ')
00167         else: print('   ', end=' ')
00168         if i in labels: print('>>', end=' ')
00169         else: print('  ', end=' ')
00170         print(repr(i).rjust(4), end=' ')
00171         print(opname[op].ljust(20), end=' ')
00172         i = i+1
00173         if op >= HAVE_ARGUMENT:
00174             oparg = code[i] + code[i+1]*256 + extended_arg
00175             extended_arg = 0
00176             i = i+2
00177             if op == EXTENDED_ARG:
00178                 extended_arg = oparg*65536
00179             print(repr(oparg).rjust(5), end=' ')
00180             if op in hasconst:
00181                 print('(' + repr(co.co_consts[oparg]) + ')', end=' ')
00182             elif op in hasname:
00183                 print('(' + co.co_names[oparg] + ')', end=' ')
00184             elif op in hasjrel:
00185                 print('(to ' + repr(i + oparg) + ')', end=' ')
00186             elif op in haslocal:
00187                 print('(' + co.co_varnames[oparg] + ')', end=' ')
00188             elif op in hascompare:
00189                 print('(' + cmp_op[oparg] + ')', end=' ')
00190             elif op in hasfree:
00191                 if free is None:
00192                     free = co.co_cellvars + co.co_freevars
00193                 print('(' + free[oparg] + ')', end=' ')
00194         print()

Here is the call graph for this function:

Here is the caller graph for this function:

def dis.distb (   tb = None)
Disassemble a traceback (default: last traceback).

Definition at line 61 of file dis.py.

00061 
00062 def distb(tb=None):
00063     """Disassemble a traceback (default: last traceback)."""
00064     if tb is None:
00065         try:
00066             tb = sys.last_traceback
00067         except AttributeError:
00068             raise RuntimeError("no last traceback to disassemble")
00069         while tb.tb_next: tb = tb.tb_next
00070     disassemble(tb.tb_frame.f_code, tb.tb_lasti)
00071 
00072 # The inspect module interrogates this dictionary to build its
00073 # list of CO_* constants. It is also used by pretty_flags to
# turn the co_flags field into a human readable list.

Here is the call graph for this function:

Here is the caller graph for this function:

def dis.findlabels (   code)
Detect all offsets in a byte code which are jump targets.

Return the list of offsets.

Definition at line 240 of file dis.py.

00240 
00241 def findlabels(code):
00242     """Detect all offsets in a byte code which are jump targets.
00243 
00244     Return the list of offsets.
00245 
00246     """
00247     labels = []
00248     n = len(code)
00249     i = 0
00250     while i < n:
00251         op = code[i]
00252         i = i+1
00253         if op >= HAVE_ARGUMENT:
00254             oparg = code[i] + code[i+1]*256
00255             i = i+2
00256             label = -1
00257             if op in hasjrel:
00258                 label = i+oparg
00259             elif op in hasjabs:
00260                 label = oparg
00261             if label >= 0:
00262                 if label not in labels:
00263                     labels.append(label)
00264     return labels

Here is the caller graph for this function:

def dis.findlinestarts (   code)
Find the offsets in a byte code which are start of lines in the source.

Generate pairs (offset, lineno) as described in Python/compile.c.

Definition at line 265 of file dis.py.

00265 
00266 def findlinestarts(code):
00267     """Find the offsets in a byte code which are start of lines in the source.
00268 
00269     Generate pairs (offset, lineno) as described in Python/compile.c.
00270 
00271     """
00272     byte_increments = list(code.co_lnotab[0::2])
00273     line_increments = list(code.co_lnotab[1::2])
00274 
00275     lastlineno = None
00276     lineno = code.co_firstlineno
00277     addr = 0
00278     for byte_incr, line_incr in zip(byte_increments, line_increments):
00279         if byte_incr:
00280             if lineno != lastlineno:
00281                 yield (addr, lineno)
00282                 lastlineno = lineno
00283             addr += byte_incr
00284         lineno += line_incr
00285     if lineno != lastlineno:
00286         yield (addr, lineno)

Here is the caller graph for this function:

def dis.pretty_flags (   flags)
Return pretty representation of code flags.

Definition at line 84 of file dis.py.

00084 
00085 def pretty_flags(flags):
00086     """Return pretty representation of code flags."""
00087     names = []
00088     for i in range(32):
00089         flag = 1<<i
00090         if flags & flag:
00091             names.append(COMPILER_FLAG_NAMES.get(flag, hex(flag)))
00092             flags ^= flag
00093             if not flags:
00094                 break
00095     else:
00096         names.append(hex(flags))
00097     return ", ".join(names)

Here is the caller graph for this function:

def dis.show_code (   co)
Print details of methods, functions, or code to stdout.

Definition at line 143 of file dis.py.

00143 
00144 def show_code(co):
00145     """Print details of methods, functions, or code to stdout."""
00146     print(code_info(co))

Here is the call graph for this function:

Here is the caller graph for this function:


Variable Documentation

Initial value:
00001 ["code_info", "dis", "disassemble", "distb", "disco",
00002            "findlinestarts", "findlabels", "show_code"]

Definition at line 9 of file dis.py.

Definition at line 13 of file dis.py.

Initial value:
00001 {
00002      1: "OPTIMIZED",
00003      2: "NEWLOCALS",
00004      4: "VARARGS",
00005      8: "VARKEYWORDS",
00006     16: "NESTED",
00007     32: "GENERATOR",
00008     64: "NOFREE",
00009 }

Definition at line 74 of file dis.py.

Definition at line 238 of file dis.py.