[Tutor] using cmd

Alan Gauld alan.gauld at freenet.co.uk
Sat Mar 18 14:02:53 CET 2006


>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:

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

Its just how the module works - many GUI frameworks 
adopt a similar convention - eg Visual Basic command handlers.

My guess os that cmd builds the command string then uses eval() to 
execute the function, but I could be wrong. But in general frameworks 
like cmd will either:
1) expect some kind of standard naming scheme 
    (like cmd apparently does) or
2) Have some form of function registration mechanism so that code 
    looks like

def someFunc(): 
    # blah, blah
registerFunc("someCommand', someFunc)

def another():
   # and more here
registerFunc("another", another)

Or sometimes as a table:

def foo(): # blah
def baz(): # more blah

registerFuncs( {"commandFoo": foo, "commandBaz": baz})

wxPython (Or more accurately its underlying framework, wxWidgets) 
uses this second approach, for example. As does Microsoft in their 
MFC C++ framework.

HTH

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list