pythonpython-3.xcommand-promptread-eval-print-loop

Enable arrow key navigation in input prompt


Simple input loop

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

Doesn't allow me to use arrow keys to

  1. Move cursor backwards through entered text to change something
  2. Press up arrow to get entries entered in the past
  3. Press down arrow to move in the opposite direction to (2)

Instead it just prints all the escape codes:

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

How can I make it behave like a REPL or shell prompt?


Solution

  • Use cmd module to create a cmd interpreter class like below.

    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()
    

    Attaching the output of this program on trying few commands below:

    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$ 
    

    For more info, refer the docs