如何将PyCodeObject保存为pyc

source = open("test.py").read()
co = compile(source, "test.py", 'exec')
print co

<code object <module> at 0x7ff430e75db0, file "test.py", line 1>

如何将PyCodeObject保存为test.pyc?

因为在某个项目中有开发者将module通过PyCodeObject的形式引入, 我想了解具体的实现.
但是不知道PyCodeObject如何反编译? 如果可以转成pyc就可以反编译了.

用hexdump查看时发现PyCodeObject包含在pyc文件中, 但是其他文件不知道如何生成.

阅读 6.6k
2 个回答

参考一下py_compile模块的实现就好了,其实很简单的:

    codeobject = __builtin__.compile(codestring, dfile or file,'exec')
    with open(cfile, 'wb') as fc: 
        fc.write('\0\0\0\0')
        wr_long(fc, timestamp)
        marshal.dump(codeobject, fc) 
        fc.flush()
        fc.seek(0, 0)
        fc.write(MAGIC)

这里完善下, 感谢 @felix021 的回答

#!/usr/bin/env python

import py_compile
import imp
import os

def pycodeobject2pyc(pyobj, pycfile):
    with open(pycfile, 'wb') as fc: 
        fc.write('\0\0\0\0')
        timestamp = long(os.fstat(fc.fileno()).st_mtime)
        py_compile.wr_long(fc, timestamp)
        marshal.dump(pyobj, fc)
        fc.flush()
        fc.seek(0, 0)
        MAGIC = imp.get_magic()
        fc.write(MAGIC)
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题