One step up from str.split()

Matimus mccredie at
Thu Jul 17 00:10:01 CEST 2008

On Jul 15, 4:28 pm, "Joel Koltner" <zapwireDASHgro... at>
> "Sion Arrowsmith" <si... at> wrote in message
> news:Tiv*wYYhs at
> > What's wrong with sys.argv ?
> Mainly that it doesn't exist.  :-)  The example was slightly contrived -- I'm
> really dealing with commands interactively entered within a program in
> response to raw_input(), although the format of the commands is meant to be
> consistent with command-line usage.  (A real command, for instance, would be
> something like this: load "my firmware file.bin" .)
> I ended up using shlex.strip() -- works great!
> ---Joel

Then... better yet... check out the cmd module (you can still use
shlex if you like).

import cmd

class MyCmd(cmd.Cmd):
    def do_blah(self, args):
        """Sing a song about bla"""
        print >>self.stdout, "bla bla bla"

    def do_foo(self, args):
        """Prints out the args"""
        print >>self.stdout, repr(args)

    def do_quit(self, args):
        """exit the command interpreter"""
        print >>self.stdout, "bye bye"
        return True
    do_exit = do_q = do_quit

if __name__ == "__main__":

When run, you will get a "(cmd)" prompt:
(Cmd) help

Documented commands (type help <topic>):
blah  exit  foo  q  quit

Undocumented commands:

(Cmd) help blah
Sing a song about bla
(Cmd) help exit
exit the command interpreter
(Cmd) help foo
Prints out the args
(Cmd) qu
*** Unknown syntax: qu
(Cmd) quit
bye bye

Documentation here:


More information about the Python-list mailing list