-1

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

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
David
  • 485
  • 1
  • 5
  • 16

1 Answers1

2

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!
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Awesome. From reading the cmd docs this looks exactly like what I need. It wasn't clear to me how to google for the answer -- my normal course of action -- because the terms have different meanings in different contexts. Appreciate the very helpful response. – David Apr 09 '18 at 20:38