简单的输入循环
while True:
query = input('> ')
results = get_results(query)
print(results)
不允许我使用箭头键
它只是打印所有转义码:
> my query^[[C^[[D^[[D^[[D^[[A^[[A^[[A
如何让它表现得像 REPL 或 shell 提示符?
使用
cmd
模块创建一个 cmd 解释器类,如下所示。
import cmd
class CmdParse(cmd.Cmd):
prompt = '> '
commands = []
def do_list(self, line):
print(self.commands)
def default(self, line):
print(line[::])
# Write your code here by handling the input entered
self.commands.append(line)
def do_exit(self, line):
return True
if __name__ == '__main__':
CmdParse().cmdloop()
附上尝试以下几个命令时该程序的输出:
mithilesh@mithilesh-desktop:~/playground/on_the_fly$ python cmds.py
> 123
123
> 456
456
> list
['123', '456']
> exit
mithilesh@mithilesh-desktop:~/playground/on_the_fly$
有关更多信息,请参阅文档
cmd
python 库没有什么花哨的。它还在内部调用 input
。启用箭头键和其他稍微高级的功能(例如自动完成)的是 readline
导入。
所以你需要做的就是:
import readline
a = input('>')