分为三部分代码
1.纯处理单一函数
#coding:utf-8 import sys from cmd import Cmd import os class Client(Cmd): prompt = '>' def __init__(self): Cmd.__init__(self) def do_dir(self, arg): if not arg: self.help_dir() elif os.path.exists(arg): print("\n".join(os.listdir(arg))) else: print("No such pathexists.") def help_dir(self): print("syntax: dir path -- displaya list of files and directories") def do_quit(self, arg): return True def help_quit(self): print("syntax: quit -- terminatesthe application") if __name__ == '__main__': client = Client() client.cmdloop()处理结果如下
/Users/wuzi/python35/venv/bin/python /Users/wuzi/workpy/worktest/cmdtest.py
>dir /Users
.localized
Guest
Shared
wuzi
>dir
syntax: dir path -- displaya list of files and directories
>help
Documented commands (type help <topic>):
========================================
dir help quit
>help dir
syntax: dir path -- displaya list of files and directories
>quit
Process finished with exit code 0
处理单一函数的结果值
2,处理所有的文本处理包括无法对应到的命令
#coding:utf-8 import sys from cmd import Cmd import os class Client(Cmd): prompt = '>' def __init__(self): Cmd.__init__(self) def onecmd(self,arg): print ('onecmd:',arg) print(self.parseline(arg)) def do_dir(self, arg): if not arg: self.help_dir() elif os.path.exists(arg): print("\n".join(os.listdir(arg))) else: print("No such pathexists.") def help_dir(self): print("syntax: dir path -- displaya list of files and directories") def do_quit(self, arg): return True def help_quit(self): print("syntax: quit -- terminatesthe application") if __name__ == '__main__': client = Client() client.cmdloop()此时所有的命令数据都会被onecmd()函数接受,此时就不能像上面那个例子直接使用了
>dir /Users
onecmd: dir /Users
('dir', '/Users', 'dir /Users')
>uu
onecmd: uu
('uu', '', 'uu')
>uu lll
onecmd: uu lll
('uu', 'lll', 'uu lll')
>help dir
onecmd: help dir
('help', 'dir', 'help dir')
>quit
onecmd: quit
('quit', '', 'quit')
>
3.使用反射机制实现cmd
#coding:utf-8 import sys from cmd import Cmd import os class Client(Cmd): prompt = '>' def __init__(self): Cmd.__init__(self) def onecmd(self,arg): print ('onecmd:',arg) print(self.parseline(arg)) cmd,args,line = self.parseline(arg) try: func = getattr(self,"do_"+cmd) func(args) except Exception as e: print("error",e) def do_dir(self, arg): if not arg: self.help_dir() elif os.path.exists(arg): print("\n".join(os.listdir(arg))) else: print("No such pathexists.") def help_dir(self): print("syntax: dir path -- displaya list of files and directories") def do_quit(self, arg): sys.exit(0) return True def help_quit(self): print("syntax: quit -- terminatesthe application") if __name__ == '__main__': client = Client() client.cmdloop()这样就实现了命令行的基本功能处理
>dd
onecmd: dd
('dd', '', 'dd')
error 'Client' object has no attribute 'do_dd'
>dir /Users
onecmd: dir /Users
('dir', '/Users', 'dir /Users')
.localized
Guest
Shared
wuzi
>help dir
onecmd: help dir
('help', 'dir', 'help dir')
syntax: dir path -- displaya list of files and directories
>quit
onecmd: quit
('quit', '', 'quit')