Search code examples
pythonpython-3.xinteractive-shell

Is there a pattern for writing a python program that responds like a shell program


I want to modify a python program I've written to accept commands from the command line and then respond to these commands just like a shell.

Is there a standard pattern or library for doing this, or do I just use something like a while True: and stdin.readline()?


Solution

  • This is what the cmd module, in the standard library, is designed for:

    The Cmd class provides a simple framework for writing line-oriented command interpreters. These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface.

    and from the Example section:

    The cmd module is mainly useful for building custom shells that let a user work with a program interactively.

    and a quick demo example:

    import cmd
    
    class CmdDemo(cmd.Cmd):
        intro = "Welcome to the cmd module demo. Type any command, as long as it's black!"
        prompt = '(demo) '
    
        def default(self, arg):
            print("Sorry, we do't have that color")
    
        def do_black(self, arg):
            """The one and only valid command"""
            print("Like Henry Ford said, you can have any color you like.")
            print(f"You now have a black {arg}")
    
        def do_exit(self, arg):
            """Exit the shell"""
            print('Goodbye!')
            return True
    
    if __name__ == '__main__':
        CmdDemo().cmdloop()
    

    which when run produces:

    Welcome to the cmd module demo. Type any command, as long as it's black!
    (demo) ?
    
    Documented commands (type help <topic>):
    ========================================
    black  exit  help
    
    (demo) help black
    The one and only valid command
    (demo) red Volvo
    Sorry, we do't have that color
    (demo) black Austin Martin
    Like Henry Ford said, you can have any color you like.
    You now have a black Austin Martin
    (demo) exit
    Goodbye!