Python has lots of surprises for it's lovers, one such pleasant one is the cmd.Cmd module.
A programmer might encounter tons of project where she might have to write a command line interpreter for his program to execute it. Typical undergrad lab. projects have tonnes of such project where one has to implement something, say for example Graph or a toy ticket reservation system. All these projects require the developer to create a command terminal which will prompt the user to write a command from some predefined set of them and then print the result in the terminal.
Python provides a brilliant solution to such repreatative task in the form of a module cmd.Cmd. The best part is that the it gives the developer the freedom to do his implementation task independently to the command interpreter module. Cmd module offers tonnes of feature, some of them are --
The result when this code is run of a terminal is something like this,
A programmer might encounter tons of project where she might have to write a command line interpreter for his program to execute it. Typical undergrad lab. projects have tonnes of such project where one has to implement something, say for example Graph or a toy ticket reservation system. All these projects require the developer to create a command terminal which will prompt the user to write a command from some predefined set of them and then print the result in the terminal.
Python provides a brilliant solution to such repreatative task in the form of a module cmd.Cmd. The best part is that the it gives the developer the freedom to do his implementation task independently to the command interpreter module. Cmd module offers tonnes of feature, some of them are --
- command auto-completion
- auto help functions
- auto generated description of the command from the python docs.
- function stubs as place holders for the python functions.
- command history, if readline module is available.
1: from cmd import Cmd
2:
3:
4:
5: class Console(Cmd):
6: def __init__(self):
7: Cmd.__init__(self)
8: self.prompt = '=>>'
9: self.intro = "Enter Commands"
10:
11: def emptyline(self):
12: pass
13: def default(self, line):
14: print "Unrecognized Command"
15:
16: #Exit Commands
17: def do_EOF(self, args):
18: return -1
19: def do_exit(self, args):
20: self.do_EOF(args);
21:
22: #Commands
23: def do_CommandA(self, args):
24: """ Help on Command A """
25: print "Command A executed"
26: def do_CommandB(self, args):
27: """ Help on Command B """
28: print "Command B executed"
29:
30: if __name__=="__main__":
31: Console().cmdloop()
32:
The result when this code is run of a terminal is something like this,
Comments
Post a Comment