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

标签 python argparse optparse

当关注 official documentation 时从 optparse 升级到 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-parlance 中)参数,即我们可以调用 successful for

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)

最佳答案

我听从了@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 模块无法处理 narg==SUPPRESS Python<3.7,补丁需要它。

关于python - 在 Python3.7 之前的版本中,应该如何在 argparse-module 中处理散布/混合参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56736631/

相关文章:

使用 jsonify 的 python flask 响应

python - 使用 parse_known_args() 时推迟退出 --help

Python argparse 第二选择

python - 在 Keras 中实现 Rprop 算法

python - 在 blobstore webapp2 上存储调整大小的图像

python - 互斥参数提示 Action 索引

Python Optparse 列表

Python optparse、默认值和显式选项

python - 在 Python 中使用 optparse 定义变量

python - 从 URL 获取协议(protocol)和域(没有子域)