Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?


1 Answers

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

like image 126
Mithilesh_Kunal Avatar answered Sep 16 '25 07:09

Mithilesh_Kunal