Python 中快速动态代码执行的可能性
我有一些以某种形式的 AST 提供的代码,我想执行它。
我可以想到几种方法来做到这一点,例如:
- 直接解释它。
- 将其转换为 Python AST(
ast
模块)并- Python-
编译
或者 - Python-
评估
。
- Python-
- 将其翻译成Python源代码(例如纯字符串)并
- Python-
编译
或者 - Python-
评估
。
- Python-
- 将其转换为某种形式的低级代码,并用 Python 编写一个简单的 VM 来运行它。
我想我可以通过将其转换为 Python AST、编译并运行来获得快速执行。特别是。当使用 PyPy 时,我什至可能通过 PyPys JIT 编译优化获得改进(我希望我能做到,是吗?)。
你能想到其他的可能性吗?您能就什么是最好的方法提出建议吗?
I have some code available in some form of AST and I would like to execute it.
I can think of several ways to do this, e.g.:
- Just straight-forwardly interpret it.
- Translate it into a Python AST (the
ast
module) and- Python-
compile
that or - Python-
eval
that.
- Python-
- Translate it into Python source code (e.g. a pure string) and
- Python-
compile
that or - Python-
eval
that.
- Python-
- Translate it in some form of low level code and write a simple VM in Python which runs that.
I guess I would get the fasted execution by translating it into a Python AST, compile
that and run that. Esp. when using PyPy, I might even get improvements by PyPys JIT compiling optimizations (I hope I do, do I?).
Can you think of other possibilities? Can you give suggestions on what might be the best way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
另一种可能性:转换为 Cython 代码,写入文件,用 Cython 编译,然后打开优化的 C 编译器,加载生成的模块并执行它。
如果代码具有可以转换为 Cython/C 类型的类型注释,则速度会非常快。不过要小心,因为 Cython 还处于测试阶段,而且边缘仍然有点粗糙。此外,该解决方案仅适用于 CPython。
Another possibility: translate to Cython code, write out to a file, compile with Cython then a C compiler with optimization turned on, load the resulting module and execute it.
If the code has type annotations that can be translated to Cython/C types, this can be blazing fast. Watch out, though, as Cython is in beta and still a bit rough around the edges. Also, this solution only works for CPython.
另一种可能性:将 AST 直接翻译为 Python 字节码并执行。除了使用现有的 Python VM 之外,这就像您的最后一个想法。
这不是一个很大的可能性,因为它可能需要大量工作,并且 Python
compile
可能会做得更好,除非在相当特殊的情况下,但我只是把它扔掉在那里。Another possibility: translate the AST directly to Python byte code and execute that. This is like your last idea except using the existing Python VM.
It is not a great possibility because it could be a lot of work and Python
compile
would probably do a better job except in rather peculiar cases, but I'm just throwing it out there.