获取字符串中 dis.dis() 的结果

noɥ*_*ɐɹƆ 5 python python-3.x

我试图将两个事物的字节码与 difflib 进行比较,但 dis.dis() 总是将其打印到控制台。有什么办法可以得到字符串的输出吗?

Dan*_*etz 6

如果您使用的是 Python 3.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
Run Code Online (Sandbox Code Playgroud)

您可能还想看看dis.get_instructions(),它返回一个命名元组的迭代器,每个元组对应于一个字节码指令。


小智 4

用于StringIO重定向stdout到类似字符串的对象(python 2.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
Run Code Online (Sandbox Code Playgroud)