Python交互式外壳类型应用程序 [英] Python Interactive Shell Type Application
问题描述
我想创建一个交互式外壳类型应用程序。例如:
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
...
我当然可以使用无限循环来获取用户输入,拆分这行代码可以获取命令的各个部分,但是还有更好的方法吗?即使在 PHP(Symfony 2控制台)中,它们也可以创建控制台命令来帮助您例如,设置Web应用程序。在Python中有类似的东西(我正在使用Python 3)
I could of course use a 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)
推荐答案
只需输入
循环执行命令。
要解析输入,请 shlex.split
是一个不错的选择。或者只是使用普通的 str.split
。
For parsing the input, shlex.split
is a nice option. Or just go with plain str.split
.
import readline
import shlex
print('Enter a command to do something, e.g. `create name price`.')
print('To get help, enter `help`.')
while True:
cmd, *args = shlex.split(input('> '))
if cmd=='exit':
break
elif cmd=='help':
print('...')
elif cmd=='create':
name, cost = args
cost = int(cost)
# ...
print('Created "{}", cost ${}'.format(name, cost))
# ...
else:
print('Unknown command: {}'.format(cmd))
readline
库添加了历史记录功能(向上箭头)等。 Python交互式外壳程序使用它。
The readline
library adds history functionality (up arrow) and more. Python interactive shell uses it.
这篇关于Python交互式外壳类型应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!