Muhammed Özen
Muhammed Özen

Reputation: 53

Curses Command Line Application in Python

I'm writing a command line console application that receives input from user and interprets it as a command and performs the necessary action (like metasploit console). My application is already done and ready to go but my problem is I implemented it with input() function which does not handle arrow keys. If I mistype something and not notice it, I have to delete every character back to that typo and retype the rest of the command. I want to implement it in a way that would accept arrow keys to navigate around the characters. Is there anyone who knows how to do that?

(As I specified above, I'm trying to find a way to do that with curses library. But any other library that can do what I need would be highly appreciated)

Code example:

while True:
    command = input("command >")

    if command == "say_hello":
        print("Hello")
    elif command == "exit":
        exit()
    else:
        print("Undefined command")

Upvotes: 2

Views: 579

Answers (1)

Michael Wheeler
Michael Wheeler

Reputation: 937

Try using Python's built-in cmd library. You would sub-class cmd.Cmd and then write do_* methods for each of the commands you'd like recognized:

import cmd

class SimpleAppShell(cmd.Cmd):
    """A simple example of Python's Cmd library."""
    
    prompt = "command > "

    def do_say_hello(self, arg):
        print("Hello")

    def do_exit(self, arg):
        print("Goodbye")
        exit()


if __name__ == "__main__":
    SimpleAppShell().cmdloop()

Because cmd.Cmd uses by default the readline library (the Python interface to GNU Readline), you'll get the ability to move the cursor around and edit the line input by default, as well as a whole bunch of other helpful behavior out-of-the-box. See this PyMOTW post for more info and examples.

Upvotes: 1

Related Questions