[Tutor] using cmd

Kent Johnson kent37 at tds.net
Sat Mar 18 14:59:38 CET 2006

Christopher Spears wrote:
> I just completed an assignment out of Learning Python
> in which I used the Cmd class from the cmd module to
> create a little shell:
> My main question concerns the naming of functions such
> as:
> def do_ls(self, line):
>         if line == '': dirs = [os.curdir]
>         else: dirs = line.split()
>         for dirname in dirs:
>             print 'Listing of %s:' % dirname
>             print '\n'.join(os.listdir(dirname))
> Originally, I called the function 'ls', but when I did
> that, the function didn't work when I typed 'ls' at
> the prompt.  When I looked in the back of the book, I
> saw the name the authors gave their function, which
> was 'do_ls'.  When I changed the function's name to
> do_ls, the function worked when I typed 'ls' at the
> prompt.  Does anyone know why this happened?

Cmd uses introspection (using the built-in function getattr()) to find 
the handler methods. For a command named 'ls' it looks for a method 
'do_ls' to handle the command. You can also provide 'help_ls' to respond 
to the user command 'help ls'. This naming convention is built-in to Cmd 
so you have to use it for the module to work correctly.


More information about the Tutor mailing list