代码之家  ›  专栏  ›  技术社区  ›  Valentin Lorentz

Python 3字节码格式

  •  1
  • Valentin Lorentz  · 技术社区  · 9 年前

    我想读一本 .pyc 文件但是,我找不到任何关于格式的文档。

    这个 only one I found 不适用于Python 3(尽管它适用于Pyhon 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)
    

    封送仅消耗一个字节: \x00 ,这确实不是marshall的有效第一个字符(作为比较,Python 2字节码的第一个字节是 c )

    那么,我怎样才能解码标题后面的内容呢?

    2 回复  |  直到 9 年前
        1
  •  3
  •   aghast    9 年前

    试试这个。这在前一段时间起了作用。他们在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
    
        2
  •  0
  •   Robert Jacobs    9 年前