Jie*_*eng 5 console-application python-3.x
我想创建一个交互式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
...
Run Code Online (Sandbox Code Playgroud)
我当然可以使用infinte循环获取用户输入,拆分行以获取命令的各个部分,但是有更好的方法吗?即使在PHP(Symfony 2控制台)中,它们也允许您创建控制台命令以帮助设置Web应用程序.在Python中有类似的东西(我使用的是Python 3)
Ole*_*pin 10
只是input循环中的命令.
对于解析输入,shlex.split是一个不错的选择.或者只是简单地说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))
Run Code Online (Sandbox Code Playgroud)
该readline库添加了历史功能(向上箭头)等.Python交互式shell使用它.
构建此类交互式应用程序的另一种方法是使用cmd模块。
# app.py
from cmd import Cmd
class MyCmd(Cmd):
prompt = "> "
def do_create(self, args):
name, cost = args.rsplit(" ", 1) # args is string of input after create
print('Created "{}", cost ${}'.format(name, cost))
def do_del(self, name):
print('Deleted {}'.format(name))
def do_exit(self, args):
raise SystemExit()
if __name__ == "__main__":
app = MyCmd()
app.cmdloop('Enter a command to do something. eg `create name price`.')
Run Code Online (Sandbox Code Playgroud)
这是运行上述代码的输出(如果上述代码位于名为 的文件中app.py):
$ python app.py
Enter a command to do something. eg `create name price`.
> create item1 10
Created "item1", cost $10
> del item1
Deleted item1
> exit
$
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6322 次 |
| 最近记录: |