前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >比较全的python cmd模块的用法

比较全的python cmd模块的用法

作者头像
py3study
发布2020-01-10 01:18:19
1.7K0
发布2020-01-10 01:18:19
举报
文章被收录于专栏:python3python3

   百度搜了下python cmd的用法,发现都比较片,自己看了官方文档,写个稍微完整的例子,没有onecmd,另外undoc_header misc_header官网描述也太少了,使用没什么效果

代码语言:javascript
复制
# 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 [i for i in completions if i.startswith(text)]
    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()
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-08-29 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
命令行工具
腾讯云命令行工具 TCCLI 是管理腾讯云资源的统一工具。使用腾讯云命令行工具,您可以快速调用腾讯云 API 来管理您的腾讯云资源。此外,您还可以基于腾讯云的命令行工具来做自动化和脚本处理,以更多样的方式进行组合和重用。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档