Python2.7 --- 命令行交互模式脚本编写

Python 专栏收录该内容
1 篇文章 0 订阅

Python2.7 — 命令行交互模式脚本编写

做一个简单的cmd+参数解析示例

代码cmddemo.py

# -*- coding: utf-8 -*-
import argparse
import cmd
import os
import sys
import traceback
from functools import wraps


def handle_errors(func):
    @wraps(func)
    def wrapper_func(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            print(e.message, os.linesep, traceback.format_exc())
    return wrapper_func

class CmdDemo():
    def __init__(self,name, arg):
        self.name = name
        self.arg = arg
        print("Create CmdDemo: %s:%s"%(name,arg))

    def get_name(self, user_name, user_arg):
        return  "%s: [%s], %s: [%s]"%(user_name, user_arg, self.name, self.arg)
        

class CmdDemoDebuger(cmd.Cmd):
    prompt = 'CmdDemo>'
    intro = 'CmdDemo debug tool'

    @handle_errors
    def do_get_name(self, line):
        '''get_name user_name user_arg
        '''
        #用空格代替‘,’
        line = line.replace(' ', ',')
        ret = self.cmddemo.get_name(*list(eval(line)))
        print("%s"%(ret))

    @handle_errors
    def do_quit(self, line):
        '''quit'''
        return True

    @handle_errors
    def do_help(self, line):
        '''help'''
        func_methods=filter(lambda x: x.startswith('do_') and callable(getattr(self,x)), dir(self))
        print('Usage:')
        for func in func_methods:
            print(eval("self."+func).__doc__)

        return True

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    #添加参数
    parser.add_argument('-n', '--name', help='name', default='xiaoming')
    parser.add_argument('-d', '--desc', help='desciption', default='boy')
    args = parser.parse_args()
	
    cmddemo_dbg= CmdDemoDebuger()
    cmddemo_dbg.cmddemo=CmdDemo(args.name, args.desc)
    cmddemo_dbg.cmdloop()

使用

$ python2.7 cmddemo.py -n niuniu -d girl
Create CmdDemo: niuniu:girl
CmdDemo debug tool
CmdDemo>
CmdDemo>get_name "zhuzhu" "boy"
zhuhzu: [boy], niuniu: [girl]
CmdDemo>help
Usage:
get_name user_name user_arg
        
help
quit
CmdDemo>
CmdDemo>quit
$
  • 1
    点赞
  • 0
    评论
  • 0
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值