在 Python 中循环一个函数

我有一个功能用于列表中列出的多个设备。如果它不适用于特定设备并且脚本中断,则会引发错误。


def macGrabber(child,switch,cat = False):

    try:

        if cat is False:

            child.expect('.#')

            child.sendline('sh mac address-table | no-more')

        else:

            child.sendline('sh mac address-table dynamic | i Gi')

        child.expect('.#', timeout=3000)

    except pexpect.TIMEOUT:

        print child.before,child.after

        child.close()

        raise

    macs = child.before

    child.close()

    macs = macs.splitlines()

    print('Connection to %s CLOSED' % switch)

    return macs

我们可以在它转到“Except”之前循环它(重试多次)吗?或者

如果失败,我们可以跳过它并尝试下一个设备吗?


杨魅力
浏览 229回答 2
2回答

慕侠2389804

对于第一个问题,是的,您可以重试多次。保留一个错误计数器,将整个try/except循环包装起来,当您遇到异常时,检查错误计数器并继续循环,如果它小于(例如)5,否则会像您已经在做的那样引发错误。error_count = 0while True:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; if cat is False:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; child.expect('.#')&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; child.sendline('sh mac address-table | no-more')&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; child.sendline('sh mac address-table dynamic | i Gi')&nbsp; &nbsp; &nbsp; &nbsp; child.expect('.#', timeout=3000)&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; except pexpect.TIMEOUT:&nbsp; &nbsp; &nbsp; &nbsp; ++error_count&nbsp; &nbsp; &nbsp; &nbsp; if error_count < 5:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; print child.before,child.after&nbsp; &nbsp; &nbsp; &nbsp; child.close()&nbsp; &nbsp; &nbsp; &nbsp; raise对于第二个问题,是的,如果设备失败,您可以跳过该设备,只需放入return Noneexcept 处理即可。但是您还需要调整调用代码以正确处理None结果。

皈依舞

如果您想在程序不崩溃的情况下继续循环,您需要macGrabber在try...except块内调用并调用continue。multiple_devices = [&nbsp; &nbsp; (child1, switch1, cat1),&nbsp; &nbsp; (child2, switch2, cat2),&nbsp; &nbsp; ...,]for device in multiple_devices:&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; macGrabber(*device)&nbsp; &nbsp; except pexpect.TIMEOUT as e:&nbsp; &nbsp; &nbsp; &nbsp; print(f'{device} timed out')&nbsp; &nbsp; &nbsp; &nbsp; print(e)&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; #&nbsp; <--- Keep going!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python