在 python 中创建类似 shell 的环境的正确方法是什么?
我正在尝试创建一个类似 shell 的环境,其中向用户显示“>>”并可以输入任何预定义的命令。然而,我能想到实现这一点的唯一方法是使用字典映射命令->代码和python的“exec”。
有更正确的方法吗?
I'm trying to create a shell like environment, where a user is presented with ">>>" and can type in any of a number of pre-defined commands. However, the only way I can think of implementing this is with a dictionary mapping commands->code and python's "exec".
Is there a more correct way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
标准库模块 cmd 专门用于此目的。
如果您最终推出了自己的解决方案,则无需涉及 exec。将命令映射到代码的字典应该将字符串映射到字符串。它可以将字符串映射到实际函数。事实上,类是字符串到代码(方法名称到方法定义)的映射。
The standard library module cmd is specifically for this.
If you do end up rolling your own solution, there's no need to involve exec. Your dictionary mapping commands to code should map strings to strings. It can map strings to actual functions. In fact, a class is a mapping of strings to code (method names to method definitions).
如果您正在制作 Python 交互式解释器,请查看 code 模块。
If it is a Python interactive interpreter you are making, check out the code module.