While searching for faster ways to parse command-line arguments in my scripts I came across the argh library.
I really like the features of argh but I’ve encountered one drawback that stops me from using it, and this has to do with the default help message that gets displayed if I’m invoking the —help option:
per default the function’s docstring is displayed on top of the arguments list. This is great, however the initial formatting is lost. See, for example, the following example script
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'])
which would result in the following output
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
Is there an (easy) way to get an output like the following?
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
I'd prefer to not use annotations to define the argument help messages since that would require me to alter both the function's docstring AND the help text each time there is something to change.
解决方案
I'm not familiar with argh, but apparently it is a wrapper to argparse. My guess is that it is taking your function __doc__, and making it the description of a parser, e.g.
parser = argparse.ArgumentParser(description=func.__doc__)
argparse has a RawDescriptionHelpFormatter that displays the description as is.
parser = argparse.ArgumentParser(description=func.__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
So the question is, is there a way of getting argh to use this formatter?
This argparse script produces the help that you want:
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()
In 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)
So you could either set:
PARSER_FORMATTER = argparse.RawDescriptionHelpFormatter
or write your own function:
def raw_dispatch_command(function, *args, **kwargs):
...
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
set_default_command(parser, function)
dispatch(parser, *args, **kwargs)