source = open("test.py").read() co = compile(source, "test.py", 'exec') print co
at 0x7ff430e75db0, file "test.py", line 1>
如何将PyCodeObject保存为test.pyc?
因为在某个项目中有开发者将module通过PyCodeObject的形式引入, 我想了解具体的实现.
但是不知道PyCodeObject如何反编译? 如果可以转成pyc就可以反编译了.
用hexdump查看时发现PyCodeObject包含在pyc文件中, 但是其他文件不知道如何生成.
这里完善下, 感谢 @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)
参考一下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)