python-3.x 在输入提示中启用箭头键导航

xn1cxnb4  于 4个月前  发布在  Python
关注(0)|答案(2)|浏览(54)

简单输入回路

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

字符串
不允许我使用箭头键
1.在输入的文本中向后移动光标以更改某些内容
1.按向上箭头可获取过去输入的条目
1.按向下箭头,向(2)的相反方向移动
相反,它只是打印所有的转义码:

> my query^[[C^[[D^[[D^[[D^[[A^[[A^[[A


我怎样才能使它像一个REPL或shell提示符一样工作?

ar5n3qh5

ar5n3qh51#

使用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

jc3wubiy

jc3wubiy2#

python的cmd库没有什么花哨的。它还在内部调用input。启用箭头键和其他稍微高级一些的功能(如自动完成)的是readline导入。
所以你需要做的就是:

import readline
a = input('>')

字符串

相关问题