前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python之cmd库学习

python之cmd库学习

作者头像
py3study
发布2020-01-07 16:34:43
7830
发布2020-01-07 16:34:43
举报
文章被收录于专栏:python3

一:cmd介绍

 引用python的官方文档

    The cmd class provides a simple framework for writing line-oriented command interpreters.  These are often useful for test harnesses, administrative tools, and prototypes that will later be wrapped in a more sophisticated interface

 cmd是一个提供一种基于面向命令行解释器编写程序的简单框架,这些通常用于测试工具,管理工具和稍后包裹在更加复杂的接口的原型非常有用。

二:cmd的基本使用

编写基于cmd的程序要注意以下几个点:

代码语言:javascript
复制
1.要继承自cmd.Cmd类
2.要先初始化父类
3.所有的命令都是以do_开头
4.所有的命令帮助都是以help_开头
5.一个命令对应一个帮助,如果没有帮助执行错误命令会出错。

三:cmd例子

代码语言:javascript
复制
# -*- coding: utf-8 -*- 
#!/usr/bin/python env

#引入一些包
import sys
import cmd
import os
#继承cmd.Cmd类
class Cli(cmd.Cmd):
        def __init__(self):
                #先初始化父类
                cmd.Cmd.__init__(self)
                #设置命令行的提示符
                self.prompt = "<zhang>"

    #第一个命令dir命令,带一个参数    
        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 do_quit(self,arg):
                return True
    #dir命令的帮助
        def help_dir(self):
                print "syntax:dir path -- displaya list of files and directories"
    #help命令的帮助
        def help_quit(self):
                print "syntax:quit --terminatesthe application"
    #命令的别名
        do_q = do_quit

if __name__ == "__main__":
#开始执行cmd
        cli = Cli()
#循环接受用户输入的命令
        cli.cmdloop()

四:执行结果

代码语言:javascript
复制
[root@work python]# python cmdtest.py 
<zhang>dir
syntax:dir path -- displaya list of files and directories
<zhang>dir /tmp
keyring-8MjWB8
ferret
.ICE-unix
keyring-6y9txT
orbit-gdm
.X11-unix
keyring-e2WQQa
.X0-lock
pulse-weKNqpdx0HtQ
keyring-AoiV8e
keyring-i47ize
keyring-BshjbU
pulse-8TDHlwHPDc2j
keyring-vIwkfE
keyring-M5PGn7
keyring-pb8Q2x
keyring-TME3bW
keyring-gTw1ih
.esd-0
<zhang>help

Documented commands (type help <topic>):
========================================
dir  quit

Undocumented commands:
======================
help  q

<zhang>q
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

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

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

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

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