【问题标题】:Get the results of dis.dis() in a string以字符串形式获取 dis.dis() 的结果
【发布时间】:2015-07-10 17:42:01
【问题描述】:

我正在尝试将两件事的字节码与 difflib 进行比较,但 dis.dis() 总是将其打印到控制台。有什么方法可以在字符串中获取输出?

【问题讨论】:

  • @DanGetz 已编辑问题。
  • 如果有人来到这里并正在寻找 Python 2 解决方案,请参阅 this other question

标签: python python-3.x


【解决方案1】:

如果您使用的是 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

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

【讨论】:

    【解决方案2】:

    使用 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
    

    【讨论】:

    • 我喜欢这个。它是动态的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-20
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多