Line oriented command interpreter in Python

The Cmd class provides a simple framework for writing line-oriented command interpreters. A Cmd instance or subclass instance is a line-oriented interpreter framework. There is no good reason to instantiate Cmd itself; rather, it’s useful as a superclass of an interpreter class you define yourself in order to inherit Cmd‘s methods and encapsulate action methods.

Sample class (defining two commands, exit and help):

import cmd
 
class Mycmd(cmd.Cmd):
 
	def do_exit(self, line):
		return True
 
	def help_exit(self):
		print 'exit application'
 
	def help_help(self):
		print 'show help'
 
	def __init__(self):
		cmd.Cmd.__init__(self)
		self.completekey = 'Tab'
		self.prompt = 'mycmd>'
 
	def start(self):
		self.cmdloop()

Usage:

#!/usr/bin/python
 
import os
 
from mypackage import Mycmd
 
def main():
 
	# start console interpreter
	console = Mycmd()
	console.start()
 
if __name__ == "__main__":
    main()
Categories: Python Tags: , , , ,
%d bloggers like this: