2

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")
2
  • Could you please provide a minimal reproducible code example? Commented Aug 2, 2021 at 16:50
  • I just edited the post and included the code. But instead of input(), I want to use something else that implements arrow key handling as I described above Commented Aug 2, 2021 at 17:12

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.