如果只是为了显示选项,我能想到的一种方法是使用optparse的format_help,并将其放在argparse的epilog中,例如:
In [303]: foo = OptionParser()
In [304]: foo.add_option("-f", "--file", dest="filename",help="read data from FILENAME")
In [305]: foo.add_option("-v", "--verbose",action="store_true", dest="verbose")
In [311]: bar = ArgumentParser(epilog = foo.format_help(), formatter_class = RawTextHelpFormatter)
In [312]: bar.add_argument('integers', metavar='N', type=int, nargs='+',help='an integer for the accumulator')
In [313]: bar.add_argument('--sum', dest='accumulate', action='store_const',const=sum, default=max,help='sum the integers (default: find the max)')
In [314]: bar.print_help()
usage: ipython [-h] [--sum] N [N ...]
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
Usage: ipython [options]
Options:
-h, --help show this help message and exit
-f FILENAME, --file=FILENAME
read data from FILENAME
-v, --verbose
您当然可以根据需要设置结语的格式,包括对两个选项列表的一些说明。您还可以尝试使用不同的Formatter,尽管在这种情况下默认的Formatter 效果不佳,因为它会从结语中删除换行符。如果对布局感到绝望,您也可以尝试通过子类化 argparse.HelpFormatter 创建自己的格式化程序,但我不建议根据类文档这样做:
"""Formatter for generating usage messages and argument help strings.
Only the name of this class is considered a public API. All the methods
provided by the class are considered an implementation detail.
"""