Python learners should learn this #python first

I have recently discovered the python cmd library - a really useful library for creating command line programs in python.  I am beginning to wonder why we don't teach beginning python programmers the cmd library first.

Here is a really simple (and rather pointless) python command line program to demonstrate how to use the various features.

import cmd

class App(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)

if __name__ == "__main__":
    myapp = App()
    myapp.cmdloop()





Here we begin by importing the cmd library (it is part of the standard library so you will have it available).  I create an App class to contain my various command line functions and create a constructor method __init__.

This program doesn't really do much at the moment.  Running it you will see a command prompt.

We have created a new command line.  The only command that is currently implemented is 'help'. Type 'help' and see what happens...

Now we will add a new command.  It would be useful to have a way of stopping our program, so we will implement a 'quit' command.

import cmd

class App(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)

    def do_quit(self, args):
        return True
 
if __name__ == "__main__":
    myapp = App()
    myapp.cmdloop()




Adding a new command is as simple as creating a new method called do_something().  Returning True from a method will exit the cmdloop() method, so this will suffice for our quit method, for now.

Run the program and you will notice that a new command 'quit' has been added to the program documentation.


import cmd

class App(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)

    def do_quit(self, args):

        """Exits the program."""
        return True
    
if __name__ == "__main__":
    myapp = App()
    myapp.cmdloop()


We don't like 'undocumented commands'.  Adding documentation is as easy as adding a docstring to the method.  The docstring is the triple-quoted string.

Yay!  Documented commands.  Try typing 'help quit' at the prompt.


import cmd

class App(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        cmd.Cmd.prompt = "(enter command or 'help'): "

    def do_quit(self, args):
        """Exits the program."""
        return True
 
if __name__ == "__main__":
    myapp = App()
    myapp.cmdloop()




The default prompt is not very helpful.  You will probably want to change the prompt to a useful symbol or helpful message.  This is easily done by changing the value of the prompt attribute of your cmd object.

Customizing the prompt.

import cmd
import datetime

class App(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        cmd.Cmd.prompt = "(enter command or 'help'): "

    def do_time(self, args):
        """Displays the current time."""
        print( datetime.datetime.strftime((datetime.datetime.now()), '%H:%M:%S') )
     
     
    def do_quit(self, args):
        """Exits the program."""
        return True
 
if __name__ == "__main__":
    myapp = App()
    myapp.cmdloop("Command Prompt")



Let's get the program to do something a little more interesting.  Here we have added a new method do_time, such that when you type 'time' you will see the current time...

...and the date....

import cmd
import datetime

class App(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        cmd.Cmd.prompt = "(enter command or 'help'): "

    def do_time(self, args):
        """Displays the current time."""
        print( datetime.datetime.strftime((datetime.datetime.now()), '%H:%M:%S') )
     
    def do_date(self, args):
        """Displays the current date."""
        print( datetime.datetime.strftime((datetime.datetime.now()), '%Y-%m-%d') )
   
    def do_quit(self, args):
        """Exits the program."""
        return True
 
if __name__ == "__main__":
    myapp = App()
    myapp.cmdloop("Command Prompt")

Notice that we can pass a banner or a greeting message to the program by passing a string as parameter to the cmdloop() method?

Our app now does something useful!

Notice that each of the user-defined methods has an argument called 'args'.  Our one-word commands can actually take other commands as parameters and then do something useful with them.  For example, here we create a new command 'path'...

import cmd
import datetime
import os

class App(cmd.Cmd):
    def __init__(self):
        cmd.Cmd.__init__(self)
        cmd.Cmd.prompt = "(enter command or 'help'): "

    def do_path(self, args):
        """Lists the directory eg c:\\users"""
        try:
            for filename in os.listdir(args):
                print(filename)
        except (FileNotFoundError):
            print ("Cannot find files for '", args, "'")
         
    def do_time(self, args):
        """Displays the current time."""
        print( datetime.datetime.strftime((datetime.datetime.now()), '%H:%M:%S') )
     
    def do_date(self, args):
        """Displays the current date."""
        print( datetime.datetime.strftime((datetime.datetime.now()), '%Y-%m-%d') )
   
    def do_quit(self, args):
        """Exits the program."""
        return True
 
if __name__ == "__main__":
    myapp = App()
    myapp.cmdloop("Command Prompt")


An example of passing a parameter to one of our user-defined methods.  Here we obtain a directory listing and display it on the screen.

Notice that it is necessary to add exception handing in the do_path() method.  This is because it is highly likely that the user will type something meaningless (such as a non-existent filepath) which might otherwise crash the program.

The following method shows how we can use other commands as though the user had typed them.  For example, it might be useful to have a users command, which works in the same way as though the user had typed path c:\\users


    def do_users(self, args):
        """Displays a list of users on this system"""
        myapp.onecmd("path c:\\users")

    
That's it for now.  We've looked at how we can implement simple but powerful command line interfaces to our python programs.  We've seen how to add documentation and pass parameters to our commands.  We have also seen how we can get python to run our own commands as though the user had typed them.

Hopefully you agree that the cmd library provides a whole load of useful and powerful features for python beginners, and it is easy too.

Read more about the cmd library here.

1 comments:

Very useful information, the post shared was very nice.
python Online Training