在输入提示中启用箭头键导航

问题描述

简单的输入循环

while True:
    query = input('> ')
    results = get_results(query)
    print(results)

不允许我使用箭头键

  1. 在输入的文本中向后移动光标以更改某些内容
  2. 按下向上箭头以获取过去输入的条目
  3. 按下箭头可向(2)的相反方向移动

相反,它仅显示所有转义码:

> 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$ 

有关更多信息,请参见docs