模拟 Python 交互模式

Simulate Python interactive mode

我正在为 VK 编写一个私人的在线 Python 解释器,它将非常模拟 IDLE 控制台。只有我和白名单中的一些人可以使用此功能,没有可能损害我的服务器的不安全代码。但我有一个小问题。例如,我发送带有代码 def foo(): 的字符串,我不想得到 SyntaxError,而是继续逐行定义函数,而不使用 \n 编写长字符串。 exec()eval() 在那种情况下不适合我。我应该使用什么来达到预期的效果?对不起,如果重复,仍然不要从类似的问题中得到它。

归结为读取输入,然后

exec <code> in globals,locals

无限循环。

参见例如IPython.frontend.terminal.console.interactiveshell.TerminalInteractiveSh ell.mainloop().

通过尝试 ast.parse()inputsplitter.push_accepts_more() 中完成连续检测。

实际上,IPython 已经有一个名为 Jupyter Notebook 的交互式 Web 控制台,因此您最好的选择应该是重复使用它。

Python 标准库提供了 code and codeop 模块来帮助您。 code 模块直接模拟标准交互式解释器:

import code
code.interact()

它还提供了一些工具来更详细地控制和自定义其工作方式。

如果您想从更基本的组件构建东西,codeop 模块提供了一个命令编译器,它可以记住 __future__ 语句并识别不完整的命令:

import codeop
compiler = codeop.CommandCompiler()

try:
    codeobject = compiler(some_source_string)
    # codeobject is an exec-utable code object if some_source_string was a
    # complete command, or None if the command is incomplete.
except (SyntaxError, OverflowError, ValueError):
    # If some_source_string is invalid, we end up here.
    # OverflowError and ValueError can occur in some cases involving invalid literals.