14.5.5 覆盖基类方法
Cmd包括的很多方法可以被覆盖为hook,来采取动作或改变基类行为。下面这个例子并不详尽,不过其中包含很多经常用到的很有用的方法。
# Set up gnureadline if installed.
try:
import gnureadline
import sys
sys.modules['readline'] = gnureadline
except ImportError:
pass
import cmd
class Illustrate(cmd.Cmd):
"Illustrate the base class method use."
def cmdloop(self,intro=None):
print('cmdloop({})'.format(intro))
return cmd.Cmd.cmdloop(self,intro)
def preloop(self):
print('preloop()')
def postloop(self):
print('postloop()')
def parseline(self,line):
print('parseline({!r}) =>'.format(line),end='')
ret = cmd.Cmd.parseline(self,line)
print(ret)
return ret
def onecmd(self,s):
print('onecmd({})'.format(s))
return cmd.Cmd.onecmd(self,s)
def emptyline(self):
print('emptyline()')
return cmd.Cmd.emptyline(self)
def default(self,line):
print('default({})'.format(line))
return cmd.Cmd.default(self,line)
def precmd(self,line):
print('precmd({})'.format(line))
return cmd.Cmd.precmd(self,line)
def postcmd(self,stop,line):
print('postcmd({},{})'.format(stop,line))
return cmd.Cmd.postcmd(self,stop,line)
def do_greet(self,line):
print('hello,',line)
def do_EOF(self,line):
"Exit"
return True
if __name__ == '__main__':
Illustrate().cmdloop('Illustrating the methods of cmd.Cmd')
cmdloop()是解释器的主处理循环。通常没有必要覆盖这个循环,因为可以使用preloop()和postloop hook。
每次cmdloop()迭代都会调用onecmd(),将命令分派到它的处理器。实际输入行用parseline()解析来创建一个元组,其中包括命令和该行上的其余部分。如果这一行为空,则调用emptyline()。默认实现会自爱吃运行前面的命令。如果这一行包含一个命令,那么首先调用precmd(),然后查看并调用处理器。如果没有找到,则
调用default()。最后调用postcmd()。
以下输出显示增加了print语句的一个示例会话。