mydis.disco() ( was: tofile(), tostring(), etc... )

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Wed, 16 Mar 1994 18:01:28 -0500

And here is the code that inspired the need for the previous functions.
mydis.disco( ) is an output postprocessor for dis.disco(), that uses
linecache.getline() to grab the source line. It reformats dis.disco()'s
output, inserting the source lines into the output stream.

Note:
(1) Like dis.disco, the argument is not a FUNCTION, but the function's
"func_code" attribute/member. Call it as "disco( func.func_code )."
(2) Since it want's to look up the source code with linecache, it
will fail if it is 'compile()'-ed code from an internal string,
or it linecache can't find the file on sys.path.

Try this on your favorite Python function to see what Python byte-code
"assembler" looks like!

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics

----------------------------------------------------------------

# module <mydis>
import dis
from linecache import getline
import string
from redirect import tolines

def disco( fcode ):
print fcode
for m in fcode.__members__ :
if m == 'co_code' :
print m+':',
for icode in getattr( fcode, m ):
print ord(icode),
print
else: print m+':', getattr( fcode, m )
print
# capture the output from dis.disco ...
for line in tolines( dis.disco, fcode ):
field = string.split( line )
if field[1:] and field[1] == 'SET_LINENO' :
# and if it's a SET_LINENO, print the source line first
print
lineno = string.atoi( field[-1] )
print '|', getline( fcode.co_filename, lineno )[:-1],
print '\t #',lineno,'\n'
if field: print line,