简体   繁体   English

模拟Python交互模式

[英]Simulate Python interactive mode

Im writing a private online Python interpreter for VK , which would closely simulate IDLE console.我正在为VK编写一个私有的在线 Python 解释器,它将密切模拟 IDLE 控制台。 Only me and some people in whitelist would be able to use this feature, no unsafe code which can harm my server.只有我和白名单中的一些人才能使用此功能,没有会损害我的服务器的不安全代码。 But I have a little problem.但我有一个小问题。 For example, I send the string with code def foo(): , and I dont want to get SyntaxError but continue defining function line by line without writing long strings with use of \\n .例如,我发送带有代码def foo():的字符串,我不想得到SyntaxError但继续逐行定义函数而不使用\\n编写长字符串。 exec() and eval() doesn't suit me in that case. exec()eval()在这种情况下不适合我。 What should I use to get desired effect?我应该用什么来达到预期的效果? Sorry if duplicate, still dont get it from similar questions.对不起,如果重复,仍然不要从类似的问题中得到它。

It boils down to reading input, then它归结为读取输入,然后

exec <code> in globals,locals

in an infinite loop.在无限循环中。

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

Continuation detection is done in inputsplitter.push_accepts_more() by trying ast.parse() .通过尝试ast.parse()inputsplitter.push_accepts_more()完成连续检测。

Actually, IPython already has an interactive web console called Jupyter Notebook , so your best bet should be to reuse it.实际上,IPython 已经有一个名为Jupyter Notebook的交互式 Web 控制台,因此最好的办法是重用它。

The Python standard library provides the code and codeop modules to help you with this. Python 标准库提供了codecodeop模块来帮助您解决这个问题。 The code module just straight-up simulates the standard interactive interpreter: code模块直接模拟了标准的交互式解释器:

import code
code.interact()

It also provides a few facilities for more detailed control and customization of how it works.它还提供了一些工具,用于对其工作方式进行更详细的控制和自定义。

If you want to build things up from more basic components, the codeop module provides a command compiler that remembers __future__ statements and recognizes incomplete commands:如果你想从更基本的组件构建东西, 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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM