【问题标题】:Simulate Python interactive mode模拟 Python 交互模式
【发布时间】:2016-10-15 18:11:33
【问题描述】:

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

【问题讨论】:

    标签: python read-eval-print-loop simulate


    【解决方案1】:

    Python 标准库提供了codecodeop 模块来帮助您解决这个问题。 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.
    

    【讨论】:

      【解决方案2】:

      归结为读取输入,然后

      exec <code> in globals,locals
      

      在无限循环中。

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

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

      实际上,IPython 已经有一个名为 Jupyter Notebook 的交互式 Web 控制台,所以最好的办法是重用它。

      【讨论】:

        猜你喜欢
        • 2019-10-27
        • 1970-01-01
        • 2015-11-01
        • 1970-01-01
        • 2011-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多