Python 交互式 Shell 类型应用程序
我想创建一个交互式 shell 类型的应用程序。例如:
> ./app.py
Enter a command to do something. eg `create name price`.
For to get help, enter "help" (without quotes)
> create item1 10
Created "item1", cost $10
> del item1
Deleted item1
> exit
...
我当然可以使用无限循环获取用户输入,分割行以获取命令的各个部分,但是有更好的方法吗?即使在 PHP(Symfony 2 控制台) 中,它们也允许您创建控制台命令例如,帮助设置 Web 应用程序。 Python中有类似的东西吗? (我使用的是Python 3)
I want to create an interactive shell type application. For example:
> ./app.py
Enter a command to do something. eg `create name price`.
For to get help, enter "help" (without quotes)
> create item1 10
Created "item1", cost $10
> del item1
Deleted item1
> exit
...
I could of course use an infinte loop getting user input, splitting the line to get the individual parts of the command, but is there a better way? Even in PHP (Symfony 2 Console) they allow you to create console commands to help setup web applications for example. Is there something like that in Python? (I am using Python 3)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需在循环中
输入
命令即可。为了解析输入,
shlex.split
是一个不错的选择。或者直接使用简单的str.split
。readline
库添加历史记录功能(向上箭头)等。 Python 交互式 shell 使用它。Just
input
the commands in a loop.For parsing the input,
shlex.split
is a nice option. Or just go with plainstr.split
.The
readline
library adds history functionality (up arrow) and more. Python interactive shell uses it.构建此类交互式应用程序的另一种方法是使用 cmd 模块。
这是运行上述代码的输出(如果上述代码位于名为
app.py
的文件中):Another approach to building interactive applications like this is by using the cmd module.
And here is the output of running the above code (if the above code was in a file named
app.py
):您可以首先查看 argparse。
它并不像您所要求的那样提供完整的交互式 shell,但它有助于创建类似于 PHP 示例的功能。
You could start by having a look at argparse.
It does not provide a complete interactive shell, like you ask, but it helps in creating functionality similar to your PHP example.