Saturday, January 05, 2008

Introducing cmd2

cmd is a Python Standard Library module for constructing command-prompt applications. It's very easy to use - just subclass its Cmd type, create an instance, and call that instance's .cmdloop(). To support a command, just write a do_yourcommandname(self, arg) method within your Cmd instance.

cmd is also very bare-bones. It forms the backbone of sqlpython, and while improving that package, I've created cmd2. cmd2 is an extension for cmd that adds helpful functionality without requiring any changes to cmd-based applications.
  • Searchable command history
  • Load commands from file, save to file, edit commands in file
  • Multi-line commands
  • Case-insensitive commands
  • Special-character shortcut commands (beyond cmd's "@" and "!")
  • Settable environment parameters
  • Parsing commands with flags

I've found several alternatives to cmd in the Cheese Shop - CmdLoop, cly, CMdO, and pycopia. cly looks wonderful, but I haven't been able to get it working under Windows, and that's a show-stopper for many potential sqlpython users. In any case, none of the alternatives are based on cmd - they're written from scratch, which means that a cmd-based app would need complete rewriting to use them. I like sticking close to the Standard Library whenever possible. cmd2 lets you do that.

Switching a cmd application to cmd2 is as simple as changing from from cmd import Cmd to from cmd2 import Cmd, and the new functionality is ready to go. See a usage example of cmd2.

It's in the Cheese Shop, so you can easy_install cmd2. (Cheese Shop page for cmd2)

2 comments:

Unknown said...

I was not able to attend pycon 2010, so I have been checking out the Miro videos and just saw your talk on cmd2. It is awesome and I can see a couple of uses right off the top of my head. Especially, I am thinking of an interactive version of Petit: opensource.eyemg.com/Petit

Also, have you tried using it as the interpreter in bash scripts? That has always been my biggest complaint of ALL python scripting ( I am a sysadmin and still love the elegance of in line commands in bash). It would be phenomenal to be able to run commands in line and use python in a single script.

Unknown said...

Any plans to do a version of cmd2 that uses argparse instead of optparse?