Py学习  »  Python

在python中循环函数

Nirmal Gauda • 5 年前 • 1352 次点击  

我有一个用于列表中列出的多个设备的函数。如果它不能在特定设备上工作,并且脚本中断,则抛出错误。

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
  1. 在它进入“except”之前,我们是否可以循环它(重试多次)?或
  2. 如果下一个设备出现故障,我们可以跳过它并尝试下一个设备吗?
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39117
 
1352 次点击  
文章 [ 2 ]  |  最新文章 5 年前
John Gordon
Reply   •   1 楼
John Gordon    6 年前

对于第一个问题,可以重试多次。保留一个错误计数器,包装整个 try/except 在一个循环中,当您得到一个异常时,检查错误计数器,如果它小于(比如)5,则继续循环,否则会像您已经做的那样引发错误。

error_count = 0
while True:
    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)
        break
    except pexpect.TIMEOUT:
        ++error_count
        if error_count < 5:
            continue
        print child.before,child.after
        child.close()
        raise

对于第二个问题,是的,如果设备出现故障,只需将 return None 在“例外处理”中。但您还需要调整调用代码以正确处理 None 结果。

dwagnerkc
Reply   •   2 楼
dwagnerkc    6 年前

你需要打电话 macGrabber A内 try...except 封锁和呼叫 continue 如果您想继续循环而不让程序崩溃。

multiple_devices = [
    (child1, switch1, cat1),
    (child2, switch2, cat2),
    ...,
]

for device in multiple_devices:
    try:
        macGrabber(*device)

    except pexpect.TIMEOUT as e:
        print(f'{device} timed out')
        print(e)
        continue  #  <--- Keep going!