Generate .pyc from Python AST?

前提是你 提交于 2019-12-03 17:30:20

问题


How would I generate a .pyc file from a Python AST such that I could import the file from Python?

I've used compile to create a code object, then written the co_code attribute to a file, but when I try to import the file from Python, I get an ImportError: Bad magic number in output.pyc.


回答1:


The solution can be adapted from the py_compile module:

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)




回答2:


The compile standard function provides this function for both Python 2.x and Python 3.x. However, you will find that the AST representation between 2.x and 3.x is quite different, so be prepared for that.



来源:https://stackoverflow.com/questions/8627835/generate-pyc-from-python-ast

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!