Python argparse忽略无法识别的参数

问题:Python argparse忽略无法识别的参数

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

例如:

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

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

反正有覆盖吗?

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.

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?


回答 0

更换

args = parser.parse_args()

args, unknown = parser.parse_known_args()

例如,

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']

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']

回答 1

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

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


回答 2

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

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

$ program --foo BAR a b +cd e

我们将使用此具有命名空间的数据集合。

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

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

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

相同的命令将产生

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

把它放到你的烟斗里然后抽烟=)

欢乐!

Actually argparse does still “ignore” _unrecognized_args. As long as these “unrecognized” arguments don’t use the default prefix you will hear no complaints from the parser.

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

$ 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.

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!