Python argparse忽略无法识别的参数 [英] Python argparse ignore unrecognised arguments

查看:696
本文介绍了Python argparse忽略无法识别的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如:

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

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

反正有覆盖它吗?

推荐答案

替换

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

这篇关于Python argparse忽略无法识别的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆