【问题标题】:Python 3 bytecode formatPython 3 字节码格式
【发布时间】:2016-04-08 21:05:38
【问题描述】:

我想读取.pyc 文件。但是,我找不到有关该格式的任何文档。

only one I found 不适用于 Python 3(尽管它适用于 Python 2):

>>> f = open('__pycache__/foo.cpython-34.pyc', 'rb')
>>> f.read(4)
b'\xee\x0c\r\n'
>>> f.read(4)
b'\xf8\x17\x08W'
>>> marshal.load(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: bad marshal data (unknown type code)

marshal 只消耗一个字节:\x00,这确实不是 marshall 的有效第一个字符(作为比较,相同空模块的 Python 2 字节码的第一个字节是 c

那么,我如何解码标题后面的内容?

【问题讨论】:

标签: python python-3.x python-3.4 bytecode


【解决方案1】:

试试这个。它工作了一段时间。他们在 v3 中添加了另一个 int32。

def load_file(self, source):
    if isinstance(source, str):
        import os.path
        if not os.path.exists(source):
            raise IOError("Cannot load_file('"
                + source
                + "'): does not exist")
        with open(source, "rb") as fh:
            header_bytes = fh.read(12)
            # ignore header
            self.code = marshal.load(fh)

        return self.code

【讨论】:

  • 这似乎应该是一个正常的功能(没有self)。
【解决方案2】:

【讨论】:

  • 反汇编器获取一个必须解码的代码对象(我链接的资源为此使用了 marshal)
猜你喜欢
  • 1970-01-01
  • 2021-09-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
相关资源
最近更新 更多