Why does the "dis" module print?

Bengt Richter bokr at oz.net
Mon Aug 12 13:16:18 EDT 2002


On 12 Aug 2002 08:46:37 -0700, tweedgeezer at hotmail.com (Jeremy Fincher) wrote:

>It seems that it would be a lot easier to pull information out of the
>output of the dis.dis function if, instead of printing its results, it
>returned a list of the disassembled bytecodes.  Printing bytecodes
>from a returned list is trivial; making a list from the printed
>bytecodes is much less so.  Why does dis print instead of returning a
>list of bytecodes?
>
Not very tested, but does this help?

 >>> class SOCapture:
 ...     import sys
 ...     def __init__(self):
 ...         self.so = self.sys.stdout
 ...         self.text = []
 ...     def start(self, starttext=None):
 ...         self.sys.stdout = self
 ...         if starttext is None: return
 ...         self.text.append(starttext)
 ...     def end(self, endtext=None):
 ...         self.sys.stdout = self.so
 ...         if endtext is None: return
 ...         self.text.append(endtext)
 ...     def gettext(self): return ''.join(self.text)
 ...     def clear(self): self.text = []
 ...     def write(self, s): self.text.append(s)
 ...
 >>> so=SOCapture()
 >>> def foo(): print 'foo'
 ...
 >>> import dis
 >>> so.start('--<capture foo disassembly >--\n')
 >>> dis.dis(foo)
 >>> so.end('--<end dis foo >--\n')
 >>> print so.gettext()
 --<capture foo disassembly >--
           0 SET_LINENO               1 

           3 SET_LINENO               1
           6 LOAD_CONST               1 ('foo')
           9 PRINT_ITEM
          10 PRINT_NEWLINE
          11 LOAD_CONST               0 (None)
          14 RETURN_VALUE
 --<end dis foo >--

or did you want something like
 >>> foo.func_code.co_code
 '\x7f\x01\x00\x7f\x01\x00d\x01\x00GHd\x00\x00S'

or the numbers
 >>> map(ord,foo.func_code.co_code)
 [127, 1, 0, 127, 1, 0, 100, 1, 0, 71, 72, 100, 0, 0, 83]

or
 >>> for i,x in zip(range(len(foo.func_code.co_code)),foo.func_code.co_code):
 ...     print '%3d %s (%d)' % (i, dis.opname[ord(x)], ord(x))
 ...
   0 SET_LINENO (127)
   1 POP_TOP (1)
   2 STOP_CODE (0)
   3 SET_LINENO (127)
   4 POP_TOP (1)
   5 STOP_CODE (0)
   6 LOAD_CONST (100)
   7 POP_TOP (1)
   8 STOP_CODE (0)
   9 PRINT_ITEM (71)
  10 PRINT_NEWLINE (72)
  11 LOAD_CONST (100)
  12 STOP_CODE (0)
  13 STOP_CODE (0)
  14 RETURN_VALUE (83)

Regards,
Bengt Richter



More information about the Python-list mailing list