第十四章:应用构建模块-argparse:命令行选项和参数解析-帮助输出-定制帮助

14.1.5.2 定制帮助
对于需要直接处理帮助输出的应用,ArgumentParser提供了一些很有用的工具方法,可以创建定制动作来打印包含额外信息的帮助。

import argparse

parser = argparse.ArgumentParser(add_help=True)

parser.add_argument('-a',action="store_true",default=False)
parser.add_argument('-b',action="store",dest="b")
parser.add_argument('-c',action="store",dest="c",type=int)

print('print_usage output:')
parser.print_usage()
print()

print('print_help output:')
parser.print_help()

print_usage()会为一个参数解析器打印简短的用法消息,print_help()会打印完整的帮助输出。
在这里插入图片描述
ArgumentParser使用一个格式化器类来控制帮助输出的外观。要改变这个类,可以在实例化ArgumentParser时传入formatter_class。

import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""
    description
        not
            warpped""",
    epilog="""
    epilog
        not
            wrapped"""
    )

parser.add_argument(
    '-a',action="store_true",
    help="""argument
    help is
    wrapped
    """,
    )

parser.print_help()

命令描述和epilog中的所有文档都保存不变。
在这里插入图片描述
RawTextHelpFormatter会把所有帮助文本处理为好像已经预先格式化一样。

import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.RawTextHelpFormatter,
    description="""
    description
        not
            warpped""",
    epilog="""
    epilog
        not
            wrapped"""
    )

parser.add_argument(
    '-a',action="store_true",
    help="""argument
    help is not
    wrapped
    """,
    )

parser.print_help()

对应-a参数的帮助文档不会再妥善地换行。
在这里插入图片描述
有些应用的描述或epilog中有一些例子,改变文本的格式可能会使这些例子不再有效,对于这些应用,原始格式化器可能很有用。MetavarTypeHelpFormatter会打印每种选项类型的名字,而不是目标变量,这对于有
大量不同类型选项的应用可能很有用。

import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.MetavarTypeHelpFormatter,
    )

parser.add_argument('-i',type=int,dest='notshown1')
parser.add_argument('-f',type=float,dest="notshown2")

parser.print_help()

并不是显示dest值,而是会打印与选项关联的类型名。
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43193719/article/details/93116438