Python调试自动输出变量名信息
选择并修改http://blog.csdn.net/balabalamerobert/article/details/2327135#reply
import sys
import dis
import StringIO
def parse_bytecodes(bufvalue):
var_names = []
bytecodes = bufvalue.split('\n')
length = len(bytecodes)
var_count = 0
for i in range(length-1, -1, -1):
bytecode = bytecodes[i]
if var_count != 0:
var_names.append(bytecode.split()[-1][1:-1])
var_count -= 1
if '-->' in bytecode:
var_count = int(bytecode.split()[-1])
var_names.reverse()
return var_names
def print_name(*args):
#replace standard stdout with a StringIO object
buf = StringIO.StringIO()
old_stdout = sys.stdout
sys.stdout = buf
#call dis.disco to get bytecodes
f = sys._getframe(1)
dis.disco(f.f_code, f.f_lasti)
#restore standard stdout
sys.stdout = old_stdout
#process bytecode
var_names = parse_bytecodes(buf.getvalue())
buf.close()
#print var name and var value
for i, var_name in enumerate(var_names):
print '<%s, %s>' % (var_name, args[i])
class A(object):
def __init__(self):
pass
def __str__(self):
return 'i am a'
def g():
a = 1
b = 2
c = 3
d = A()
print_name(a, b, c, d)
g()