美文网首页Python小推车python学习
Python学习打call第二十七天:命令行参数解析

Python学习打call第二十七天:命令行参数解析

作者: 暖A暖 | 来源:发表于2019-02-27 15:31 被阅读1次

    1.argparse模块简介

    • argparse是python标准库里面用来处理命令行参数的库;

    • 大多数情况下,脚本很可能需要多个参数,而且每次参数的类型用处各不相同,那么这个时候在参数前添加标签表明参数的类型和用途便十分有用,而利用argparse模块可以很方便得实现这一目的;

    2.argparse模块的使用步骤

    # 导入模块
    import argparse
    
    # 此函数作用为:自定义打印帮助信息,且可以通过转义符号带颜色打印
    def print_help_description():
        print('\033[1;35m这里可以打印你的参数规则\033[0m')
        print('\033[1;35m脚本执行示例: python server.py -s=nginx -a=running\033[0m')
    
    # 实例化parser解析对象
    parser = argparse.ArgumentParser(add_help=False) # False表示不显示帮助信息
    
    # 给parser对象绑定参数
    parser.add_argument('-h', "--help", help="\033[1;36m显示脚本帮助信息\033[0m", action='store_true', )
    parser.add_argument('-s', "--service",help="\033[1;36mmysql, httpd, nginx, redis, mongodb \033[0m", )
    parser.add_argument('-a', "--application",help="\033[1;36mhealth, ping, running, \033[0m")
    
    
    # 解析参数
    args = parser.parse_args()
    
    # 开始对脚本传递的参数进行判断
    if not args.service or not args.application: # 如果两个条件都为False,才会进入帮助信息的打印
        parser.print_help() # 打印帮助信息
        print_help_description()  # 打印自定义函数
    else:
        if args.service == 'mysql':
            if args.application == 'health':
                print('check health')
            elif args.application == 'ping':
                print('check ping')
            elif args.application == 'running':
                print('check running')
            else:
                parser.print_help()
                print_help_description()
        elif args.service == 'httpd':
            if args.application == 'health':
                print('check health')
            elif args.application == 'ping':
                print('check ping')
            elif args.application == 'running':
                print('check running')
            else:
                parser.print_help()
                print_help_description()
        else:
            parser.print_help()
            print_help_description()
    
    • import argparse 首先导入模块;

    • parser = argparse.ArgumentParser() 创建一个解析对象;

    • parser.add_argument() 向该对象中添加你要关注的命令行参数和选项;

    • parser.parse_args() 进行解析;

    3.ArgumentParser()方法参数

    ArgumentParser(prog=None, usage=None,description=None, epilog=None, parents=[],formatter_class=argparse.HelpFormatter, prefix_chars='-',fromfile_prefix_chars=None, argument_default=None,conflict_handler='error', add_help=True);

    • prog:程序的名字(默认:sys.argv[0]);

    • usage: 描述程序用法的字符串(默认:从解析器的参数生成);

    • description: 参数帮助信息之前的文本(默认:空);

    • epilog :参数帮助信息之后的文本(默认:空);

    • parents :ArgumentParser 对象的一个列表,这些对象的参数应该包括进去;

    • formatter_class:定制化帮助信息的类;

    • prefix_chars:可选参数的前缀字符集(默认:‘-‘);

    • fromfile_prefix_chars:额外的参数应该读取的文件的前缀字符集(默认:None);

    • argument_default:参数的全局默认值(默认:None);

    • conflict_handler:解决冲突的可选参数的策略(通常没有必要);

    • add_help:给解析器添加-h/–help 选项(默认:True);

    4.add_argument()方法参数

    add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest]);

    • name or flags:指定参数的形式,想写几个写几个,不过我们一般就写两个,一个短参数一个长参数,例如 ”-f”, “–file”;

    • action: 命令行遇到参数时的动作,默认值是 store;

    • nargs :指定这个参数后面的value有多少个;

    • const : action 和 nargs 所需要的常量值;

    • default :不指定参数时的默认值;

    • type :命令行参数应该被转换成的类型;

    • choices :参数可允许的值的一个容器;

    • required :可选参数是否可以省略 (仅针对可选参数);

    • help :参数的帮助信息,当指定为 argparse.SUPPRESS 时表示不显示该参数的帮助信息;

    • metavar :在 usage 说明中的参数名称,对于必选参数默认就是参数名称,对于可选参数默认是全大写的参数名称;

    • dest :解析后的参数名称,默认情况下,对于可选参数选取最长的名称,中划线转换为下划线;

    参考:侠课岛(9xkd.com)Python同学计划

    相关文章

      网友评论

        本文标题:Python学习打call第二十七天:命令行参数解析

        本文链接:https://www.haomeiwen.com/subject/oidfuqtx.html