[Tutor] using cmd

Christopher Spears cspears2002 at yahoo.com
Sat Mar 18 00:36:58 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:

import cmd, os, shutil, sys

class shell(cmd.Cmd):
    def do_EOF(self, line):
        sys.exit()
        
    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))

    def do_cd(self, path):
        os.chdir(path)

    def do_mv(self, line):
        src, dest = line.splt()
        os.rename(src, dest)

    def do_cp(self, line):
        words = line.split()
        sourcefiles, target = words[:-1], words[-1]
        for sourcefile in sourcefiles:
            shutil.copyfile(sourcefile, target)

    def do_rm(self, line):
        [os.remove(arg) for arg in line.split()]

class DirectoryPrompt:
    def __repr__(self):
        return os.getcwd() + '> '

cmd.Cmd.prompt = DirectoryPrompt()
newShell = shell()
newShell.cmdloop()


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?

  




More information about the Tutor mailing list