我正在尝试将两件事的字节码与difflib进行比较,但是dis.dis()总是将其打印到控制台。有什么方法可以得到字符串的输出吗?
发布于 2015-07-10 18:03:57
使用StringIO将std重新定义为类似字符串的对象(python2.7解决方案)
import sys
import StringIO
import dis
def a():
print "Hello World"
stdout = sys.stdout # Hold onto the stdout handle
f = StringIO.StringIO()
sys.stdout = f # Assign new stdout
dis.dis(a) # Run dis.dis()
sys.stdout = stdout # Reattach stdout
print f.getvalue() # print contents发布于 2015-07-10 17:52:40
如果使用Python3.4或更高版本,则可以使用Bytecode.dis()方法获得该字符串
>>> s = dis.Bytecode(lambda x: x + 1).dis()
>>> print(s)
1 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (1)
6 BINARY_ADD
7 RETURN_VALUE您可能还想看看dis.get_instructions(),它返回一个命名元组的迭代器,每个迭代器对应一个字节码指令。
https://stackoverflow.com/questions/31347044
复制相似问题