【问题标题】:AttributeError: 'Namespace' object has no attribute 'x'AttributeError:“命名空间”对象没有属性“x”
【发布时间】:2021-11-14 03:45:47
【问题描述】:

我想捕获未定义的参数。怎么抓?

首先,我要定义解析器:

import argparse

parser.add_argument("--first", default='first', help='first argument')
args = parser.parse_args()

然后,我故意取一个不存在的论点:

args.x

出现错误:AttributeError: 'Namespace' object has no attribute 'x'

好吧,我不知道怎么处理,就说它不存在,所以我会设置一个变量为False例如。

【问题讨论】:

  • 您在什么情况下需要来处理它,而不是仅仅将其视为一个错误并确保x确实存在?也就是说,getattr(args, 'x', False).
  • 您可以使用hasattr 来检查一个值
  • 好的。感谢您的帮助

标签: python argparse python-3.8


【解决方案1】:

您可以使用try/except

try:
    x = args.x
except AttributeError:
    x = False

这样,如果 x 可从 args 获得,您可以指定它,否则回退到默认值。

【讨论】:

    猜你喜欢
    • 2015-04-09
    • 2018-09-03
    • 2020-10-01
    • 2017-11-30
    • 2021-03-11
    • 2020-05-17
    • 2022-12-15
    • 2017-01-12
    • 1970-01-01
    相关资源
    最近更新 更多