Python的argh库:在帮助消息中保留docstring格式

nil*_*que 7 python argparse argh

在我的脚本中搜索更快的方法来解析命令行参数时,我遇到了argh库.

我非常喜欢argh的功能但是我遇到了一个阻止我使用它的缺点,这与我在调用-help选项时显示的默认帮助消息有关:默认情况下,函数的docstring是显示在参数列表的顶部.这很好,但初始格式丢失了.例如,请参阅以下示例脚本

import argh

def func(foo=1, bar=True):
    """Sample function.

        Parameters:
            foo: float
                An example argument.
            bar: bool
                Another argument.
    """
    print foo, bar

argh.dispatch_command(func, argv=['-h'])
Run Code Online (Sandbox Code Playgroud)

这将导致以下输出

usage: script.py [-h] [-f FOO] [-b]

Sample function. Parameters: foo: float An example argument. bar: bool Another
argument.

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO
  -b, --bar
Run Code Online (Sandbox Code Playgroud)

是否有(简单)方法获得如下输出?

usage: script.py [-h] [-f FOO] [-b]

Sample function.

    Parameters:
        foo: float
            An example argument.
        bar: bool
            Another argument.

optional arguments:
  -h, --help         show this help message and exit
  -f FOO, --foo FOO
  -b, --bar
Run Code Online (Sandbox Code Playgroud)

我宁愿不使用注释来定义参数帮助消息,因为这将要求我每次有变化时都改变函数的文档字符串和帮助文本.

hpa*_*ulj 6

我不熟悉argh,但显然它是一个包装argparse.我的猜测是它正在接受你的功能__doc__,并使它成为description一个解析器,例如

parser = argparse.ArgumentParser(description=func.__doc__)
Run Code Online (Sandbox Code Playgroud)

https://docs.python.org/2.7/library/argparse.html#argparse.RawDescriptionHelpFormatter

argparse有一个RawDescriptionHelpFormatter按原样显示描述.

parser = argparse.ArgumentParser(description=func.__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter)
Run Code Online (Sandbox Code Playgroud)

所以问题是,有没有办法argh使用这个格式化程序?

argparse脚本生成所需的帮助:

import argparse

def func(foo=1, bar=True):
    """Sample function.

        Parameters:
            foo: float
                An example argument.
            bar: bool
                Another argument.
    """
    print foo, bar

parser = argparse.ArgumentParser(prog='script.py',
    description=func.__doc__,
    formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-f', '--foo', type=float)
parser.add_argument('-b', '--bar', action='store_false')
parser.print_help()
Run Code Online (Sandbox Code Playgroud)

argh/dispatching.py

def dispatch_command(function, *args, **kwargs):
    ...
    parser = argparse.ArgumentParser(formatter_class=PARSER_FORMATTER)
    set_default_command(parser, function)
    dispatch(parser, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

所以你可以设置:

PARSER_FORMATTER = argparse.RawDescriptionHelpFormatter
Run Code Online (Sandbox Code Playgroud)

或编写自己的函数:

def raw_dispatch_command(function, *args, **kwargs):
    ...
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
    set_default_command(parser, function)
    dispatch(parser, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)