在 python 中创建类似 shell 的环境的正确方法是什么?

发布于 2024-08-31 05:43:55 字数 126 浏览 0 评论 0原文

我正在尝试创建一个类似 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

‘画卷フ 2024-09-07 05:43:55

标准库模块 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).

千仐 2024-09-07 05:43:55

如果您正在制作 Python 交互式解释器,请查看 code 模块。

If it is a Python interactive interpreter you are making, check out the code module.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文