One step up from str.split()

Matimus mccredie at gmail.com
Wed Jul 16 18:10:01 EDT 2008


On Jul 15, 4:28 pm, "Joel Koltner" <zapwireDASHgro... at yahoo.com>
wrote:
> "Sion Arrowsmith" <si... at chiark.greenend.org.uk> wrote in message
>
> news:Tiv*wYYhs at news.chiark.greenend.org.uk...
>
> > 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).

[code]
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__":
    MyCmd().cmdloop()
[/code]

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

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

Undocumented commands:
======================
help

(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: http://docs.python.org/lib/module-cmd.html


Matt



More information about the Python-list mailing list