【问题标题】:Python Argparse - How can I add text to the default help message?Python Argparse - 如何将文本添加到默认帮助消息?
【发布时间】:2018-10-05 20:55:46
【问题描述】:

我正在使用 python 的 argparse 来处理参数解析。 我收到一条结构如下的默认帮助消息:

usage: ProgramName [-h] ...

Description

positional arguments:
  ...

optional arguments:
  -h, --help            show this help message and exit
  ...

我想要在此消息中添加一个全新的部分,例如:

usage: ProgramName [-h] ...

Description

positional arguments:
  ...

optional arguments:
  -h, --help            show this help message and exit
  ...

additional information:
  This will show additional information relevant to the user.
  ....

有没有办法实现这种行为? 首选 python 2.7 和 3.x 都支持的解决方案。

编辑: 我还希望有一个解决方案,将在帮助消息底部添加新的部分/部分。

【问题讨论】:

    标签: python argparse


    【解决方案1】:

    您可以通过多种方式将add a description 发送到您的命令。 推荐的方法是在源代码文件的顶部添加一个模块文档,如下所示:

    """ This is the description, it will be accessible within the variable
        __doc__
    """
    

    然后:

    parser = argparse.ArgumentParser(description=__doc__)
    

    要在参数说明下方添加文本,请使用 Epilog,如以下示例所示,摘自文档:

    >>> parser = argparse.ArgumentParser(description='A foo that bars',  
                                         epilog="And that's how you'd foo a bar")
    >>> parser.print_help() 
    
    usage: argparse.py [-h]
    
    A foo that bars
    
    optional arguments:  -h, --help  show this help message and exit
    
    And that's how you'd foo a bar
    

    有关详细信息,请参阅文档(上面链接)。

    【讨论】:

    • 有没有办法在不使用描述的情况下插入它?我实际上是在尝试将其添加到帮助消息的底部。
    • 是的,如果您打开文档,您会在“说明”下方看到“结语”选项。
    【解决方案2】:

    使用epilog 完全可以做到这一点。 下面是一个例子:

    import argparse
    import textwrap
    parser = argparse.ArgumentParser(
          prog='ProgramName',
          formatter_class=argparse.RawDescriptionHelpFormatter,
          epilog=textwrap.dedent('''\
             additional information:
                 I have indented it
                 exactly the way
                 I want it
             '''))
    parser.add_argument('--foo', nargs='?', help='foo help')
    parser.add_argument('bar', nargs='+', help='bar help')
    parser.print_help()
    

    结果:

    usage: ProgramName [-h] [--foo [FOO]] bar [bar ...]
    
    positional arguments:
      bar          bar help
    
    optional arguments:
      -h, --help   show this help message and exit
      --foo [FOO]  foo help
    
    additional information:
        I have indented it
        exactly the way
        I want it
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 2015-07-26
      • 2016-06-21
      • 2021-09-16
      相关资源
      最近更新 更多