Python argparse忽略无法识别的参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12818146/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:56:09  来源:igfitidea点击:

Python argparse ignore unrecognised arguments

pythonargparseoptparse

提问by joedborg

Optparse, the old version just ignores all unrecognised arguments and carries on. In most situations, this isn't ideal and was changed in argparse. But there are a few situations where you want to ignore any unrecognised arguments and parse the ones you've specified.

Optparse,旧版本只是忽略所有无法识别的参数并继续。在大多数情况下,这并不理想,并且在 argparse 中进行了更改。但是在某些情况下,您希望忽略任何无法识别的参数并解析您指定的参数。

For example:

例如:

parser = argparse.ArgumentParser()
parser.add_argument('--foo', dest="foo")
parser.parse_args()

$python myscript.py --foo 1 --bar 2
error: unrecognized arguments: --bar

Is there anyway to overwrite this?

反正有没有覆盖这个?

采纳答案by unutbu

Replace

代替

args = parser.parse_args()

with

args, unknown = parser.parse_known_args()

For example,

例如,

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo')
args, unknown = parser.parse_known_args(['--foo', 'BAR', 'spam'])
print(args)
# Namespace(foo='BAR')
print(unknown)
# ['spam']

回答by nickl-

Actually argparse does still "ignore" _unrecognized_args. As long as these "unrecognized" arguments don't use the default prefixyou will hear no complaints from the parser.

实际上 argparse 仍然“忽略” _unrecognized_args。只要这些“无法识别”的参数不使用默认前缀,您就不会听到解析器的抱怨。

Using @anutbu's configuration but with the standard parse.parse_args(), if we were to execute our program with the following arguments.

使用@anutbu 的配置但使用标准parse.parse_args(),如果我们要使用以下参数执行我们的程序。

$ program --foo BAR a b +cd e

We will have this Namespaced data collection to work with.

我们将使用这个命名空间数据集合。

Namespace(_unrecognized_args=['a', 'b', '+cd', 'e'], foo='BAR')

If we wanted the default prefix -ignored we could change the ArgumentParser and decide we are going to use a +for our "recognized" arguments instead.

如果我们希望-忽略默认前缀,我们可以更改 ArgumentParser 并决定我们将使用 a+作为我们“已识别”的参数。

parser = argparse.ArgumentParser(prefix_chars='+')
parser.add_argument('+cd')

The same command will produce

相同的命令将产生

Namespace(_unrecognized_args=['--foo', 'BAR', 'a', 'b'], cd='e')

Put that in your pipe and smoke it =)

把它放在你的烟斗里抽烟 =)

nJoy!

快乐!

回答by lichenbo

You can puts the remaining parts into a new argument with parser.add_argument('args', nargs=argparse.REMAINDER)if you want to use them.

parser.add_argument('args', nargs=argparse.REMAINDER)如果您想使用它们,您可以将其余部分放入一个新参数中。