JacksonHunt
JacksonHunt

Reputation: 602

How do you make a console application which accepts commands?

I am relatively new to Python and programming in general. I am working on writing a console application.

How do you write a console application that accepts commands in a terminal? For instance, like how a terminal itself accepts commands and does a corresponding task. Are the "commands" actually just functions in the application that are called by the user? Is the console interface itself just a function? E.g. :

def console_interface():
    user_input = input()
    if user_input == "some_function":
        some_function()

    if user_input == "some_other_function":
        some_other_function()

Although it is not efficient, I know the above works because I have tested it. Is this general idea correct or is it way off?

Upvotes: 1

Views: 2376

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882751

Python's standard library offers a module that encapsulates exactly the "console application that accepts commands" functionality: see https://docs.python.org/3/library/cmd.html .

In that module, the commands are actually methods of your class, which subclasses cmd.Cmd: do_this, do_that, etc, by naming convention. The example at https://docs.python.org/3/library/cmd.html#cmd-example is a rich "console accepting commands" for turtle graphics, so you can play with it.

Didactically, you may want to start with far simpler examples given at http://pymotw.com/2/cmd/ -- that's Python 2 but the functionality is just about the same. The excellent series of examples need a little adaptation to run in Python 3, but it shouldn't be too hard.

For example, consider the very first one:

import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    def do_greet(self, line):
        print "hello"

    def do_EOF(self, line):
        return True

if __name__ == '__main__':
    HelloWorld().cmdloop()

The do_EOF is what happens when the user terminates standard input (control-D on Unix); as https://docs.python.org/3/library/cmd.html#cmd.Cmd.cmdloop says,

An end-of-file on input is passed back as the string 'EOF'.

(In this case, the return True terminates the program).

The only thing you need to change to run this in Python 2 rather than 3 is the one line:

        print "hello"

which must become

        print("hello")

because print, which was a statement in Python 2, is now a function in Python 3.

I find the cmd.py sources at http://www.opensource.apple.com/source/python/python-3/python/Lib/cmd.py to also be quite instructive and I would recommend studying them as an introduction to the world of "dispatching"...!

Upvotes: 4

Related Questions