我该如何从Python AST生成一个.pyc文件,以便我可以从Python中导入该文件?
我使用了compile
来创建代码对象,然后将co_code
属性写入文件,但当我尝试从Python导入文件时,出现了ImportError:Bad magic number in output.pyc
错误。
我该如何从Python AST生成一个.pyc文件,以便我可以从Python中导入该文件?
我使用了compile
来创建代码对象,然后将co_code
属性写入文件,但当我尝试从Python导入文件时,出现了ImportError:Bad magic number in output.pyc
错误。
这个解决方案可以从py_compile
模块进行适应:
import marshal
import py_compile
import time
import ast
codeobject = compile(ast.parse('print "Hello World"'), '<string>', 'exec')
with open('output.pyc', 'wb') as fc:
fc.write('\0\0\0\0')
py_compile.wr_long(fc, long(time.time()))
marshal.dump(codeobject, fc)
fc.flush()
fc.seek(0, 0)
fc.write(py_compile.MAGIC)
compile
是 Python 2.x 和 Python 3.x 的标准函数。然而,你会发现2.x和3.x之间的AST表示形式有很大的不同,所以请做好心理准备。
co_code
属性就是我要找的字节码,对吗? - exuperoexec
或eval
,我没有直接检查字节码。 - Greg Hewgill