【问题标题】:catching exceptions with python easysnmp使用 python easysnmp 捕获异常
【发布时间】:2018-11-26 13:31:08
【问题描述】:

我似乎找不到有关如何使用 Python 的 easySNMP 库捕获异常的文档或示例

https://easysnmp.readthedocs.io/en/latest/exceptions.html 显示引发了哪些异常,但在尝试捕获它们时出现错误

简化代码:

from easysnmp import Session
try:
    session = Session(hostname=host,community=community, version=2)
except:
    print("ERROR - SNMP error:")
    sys.exit(3)    

def check_snmp(oid):
    try:
        ret = session.get(oid).value
    except easysnmp.EasySNMPNoSuchInstanceError:
        ## Return false if OID doesn't exists
        return 0
    except session.EasySNMPError as e:
        ## Print the error on general errors
        print("ERROR - SNMP error: {}".format(e))
    return 1

if check_snnp('ifalias.4'):
    print("SNMP returned true")

输出:

Traceback (most recent call last):
    File "./check_ip_route", line 72, in <module>
    if check_snmp(oid):
    File "./check_snmp", line 45, in check_snmp
        except easysnmp.EasySNMPNoSuchInstanceError:
    NameError: name 'easysnmp' is not defined

【问题讨论】:

    标签: python snmp easysnmp


    【解决方案1】:

    你的错误是name 'easysnmp' is not defined.

    那是因为你还没有导入它。

    您导入了from easysnmp import Session

    你需要做import easysnmp

    【讨论】:

    • 并将session = Session更改为session = easysnmp.Session
    • 他可以拥有他现有的导入,对吧,@TBurgis?
    • 他也使用easysnmp.EasySNMPNoSuchInstanceError。根据您的回答,如果有两个导入,则将有两个带有 Session 的命名空间。我要么导入整个模块,要么显式导入所需的位,而不是两者的混合。
    • 我明白了,两个命名空间是不必要的。明白了。
    • 谢谢你们,我怎么没看到我哪里出错了,我不知道!在星期一责备它
    猜你喜欢
    • 2017-12-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 1970-01-01
    • 2011-06-09
    • 2012-11-11
    • 1970-01-01
    • 2017-07-14
    相关资源
    最近更新 更多