gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 07:21:54 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com