python - 在 Python3.7 之前的版本中,应该如何在 argparse-module

当关注 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

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

相关文章:

linux - devtoolset-7 STL_vector.h 未定义对 `std::__thr

scala - 使用 AWS s3 的分段上传 API 时出现内存不足问题

c - 如何使用 DejaGnu 设置单元测试

visual-studio-code - 寻找用于 i18n 资源包编辑的 visual studi

google-kubernetes-engine - 无法将 gsutil 与 GKE 集群的工作负

python - 删除谷歌驱动器文件时权限不足错误

python - 有没有办法在 Windows 上使用 gradle 编译 python proto

amazon-web-services - 如何终止到 elb 的 HTTPS 流量并且容器正在运行

python-3.x - 如何在 Google Cloud Composer 中设置 chromed

amazon-web-services - 如何使用单例类解决 AWS 模拟测试