在Python3.7之前的版本中,如何在argparse-module中处理散/杂参数?

时间:2019-06-24 12:28:58

标签: python argparse optparse

遵循official documentationoptparse升级到argparse时,以下简单解析器

import optparse
def parse_with_optparser(args):
    opt_parser = optparse.OptionParser()
    opt_parser.add_option('-a', action="store_true")
    return opt_parser.parse_args(args)

成为:

def parse_with_argparser(args):
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('-a', action="store_true")
    arg_parser.add_argument("sources", nargs='*')
    return arg_parser.parse_args(args) 

即添加了附加的位置参数sources

但是,optparse默认情况下支持散布的参数(或在argparse措辞中混合使用),即我们可以成功调用

args = ['file1', '-a', 'file2']
parse_with_optparser(args) 
# ({'a': True}, ['file1', 'file2'])

但是argparse不支持混合参数,使用它会导致错误:

parse_with_argparser(args) 
# error: unrecognized arguments: file2

从Python3.7开始,有了parse_intermixed_args(而不是parse_args),它以与optparse相同的方式处理散布/混合的参数。但是,该框架的目标是Python2.7和Pyton> = 3.3,因此使用parse_intermixed_args不会削减它。

在Python3.7之前的版本中,argparse中应该如何处理散布/混合的参数?


一些测试用例:

      Input                         Output

['file1', 'file2', '-a']       Namespace(a=True, sources=['file1', 'file2'])
['-a', 'file1', 'file2']       Namespace(a=True, sources=['file1', 'file2'])
['file1', '-a', 'file2']       Namespace(a=True, sources=['file1', 'file2'])
['file1', '-a', '-b']          error (-b is unknown option)

1 个答案:

答案 0 :(得分:0)

我遵循@hpaulj的建议,并使用parse_known_args能够在后期处理步骤中手动处理混合选项:

import argparse
def parse_with_argparser(args):
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument('-a', action="store_true")
    # thus, "sources" is also a part of the help-message:
    arg_parser.add_argument("sources", nargs='*')

    # collecting unknown-options for post processing,
    # rather than exiting directly:
    result, unknown = arg_parser.parse_known_args(args)

    # post processing:
    for x in unknown:
        # filter out unknown options (like -b)
        # exit with error
        if x.startswith('-'):
            arg_parser.error("unknown argument "+x)
        # that must be one of the remaining sources:
        getattr(result, 'sources').append(x)
    return result 

这似乎比复制和粘贴parse_intermixed_args的代码更容易,因为arparse模块无法在Python <3.7中处理narg==SUPPRESS,并且补丁程序需要它。 / p>