zhu894532094 发表于 2018-8-8 11:21:09

比较全的python cmd模块的用法

# coding=utf-8  
from cmd import *
  
import sys
  
class TestCmd(Cmd):
  
    def __init__(self):
  
      Cmd.__init__(self)
  
      Cmd.intro="测试用的模块"
  
    def do_test1(self,line):
  
      print "test模块下的test命令"
  
    def help_test1(self):
  
      print "用于测试这个模块"
  
    def preloop(self):
  
      print u"进入test模块"
  
    def postloop(self):
  
      print u"退出test模块"
  
    def do_exit(self,line):
  
      return True
  
    def help_exit(self):
  
      print "退出命令,返回主循环"
  
    def do_quit(self,line):#这个的do_exit和do_quit并没有什么区别
  
      return True
  
    def help_quit(self):
  
      print "返回主循环"
  
class MyShell(Cmd):
  
    def __init__(self):
  
      Cmd.__init__(self)
  
      self.prompt="Oxo>"
  
      self.intro="""
  
      这是个玩具,目的用于测试cmd
  
      大家都退下吧
  
    """
  
      self.doc_header="修改help帮助信息头的"
  
      self.doc_leader='这里是leader'#其他两个misc_header undoc_header是无效的
  

  
    def preloop(self):
  
      print u"运行之前的欢迎信息"
  

  
    def postloop(self):
  
      print u"运行之后的结束信息"
  

  
    #def precmd(self, line):这个钩子函数基本上是用不到,也许调试会用
  
   #   print "print this line before do a command"
  
      #return Cmd.precmd(self, line)
  

  
   # def postcmd(self, stop, line):#这个钩子函数基本用不到
  
    #    print "print this line after do a command"
  
   #   return Cmd.postcmd(self, stop, line)
  
    def do_hello(self,line):
  
      print u"你好"
  
      print line
  
    def help_hello(self):
  
      print u"hello后面可接参数欢迎具体的某个人"
  
    #options是自动补全的
  
    def complete_hello(self,text,line,begidx,endidx):
  
      if not text:#列出可选参数
  
            completions=['timo','jack','jams']
  
            return completions
  
      else:
  
            completions=['timo','jack','jams']#补全参数
  
            return
  
    def do_test(self, line):
  
      i=TestCmd()#嵌套新的解释器
  
      i.prompt=self.prompt[:-1] +':Test>'
  
      i.cmdloop()
  
    def help_test(self):
  
      print u"这就是一个测试"
  
    def do_exit(self,line):
  
      print u"我退出!!"
  
      #sys.exit()不需要自己退出的,会有问题
  
      return True
  
    def help_exit(self):
  
      print "退出交互器"
  
    def emptyline(self):#输入命令为空处理办法
  
      pass
  
    def default(self,line):#输入无效命令处理办法
  
      print u"没有这个命令"
  
MyShell().cmdloop()
页: [1]
查看完整版本: 比较全的python cmd模块的用法