【问题标题】:Can I pass on options from optparse to argparse?我可以将选项从 optparse 传递到 argparse 吗?
【发布时间】:2014-08-09 15:00:07
【问题描述】:

我正在包装一个通过名为options_parser 的属性公开其OptionParser 的类。我将这个类包装在我编写的使用argparse 的“跑步者”中。我使用ArgumentParserparse_known_args() 方法来解析包装器的参数,以及我传递给包装类实例的任何剩余参数。

运行./wrapper.py --help 不会列出包装类中的选项。有没有一种方便的方法可以将 optparse 选项添加到包装器的 argparse 参数中?

【问题讨论】:

    标签: python argparse optparse


    【解决方案1】:

    如果只是为了显示选项,我能想到的一种方法是使用optparseformat_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.
    """
    

    【讨论】:

      猜你喜欢
      • 2012-07-24
      • 2012-04-22
      • 2015-05-16
      • 2015-06-23
      • 2017-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      相关资源
      最近更新 更多