如果在while循环内多个条件和计时器python

时间:2017-07-30 03:18:03

标签: python

我想读取(重复)输出命令的每一行,如果条件匹配打印行,如果没有重复循环直到超时并打印当前输出或消息

它在两种情况下都保持循环打印行或时间

我想只打印一次行或者如果超时则在timeup一次,并且在max_time_allowed中继续尝试上一个命令,因为它可能会在几秒后出现

#Import ConncetHandler feature from netmiko
from netmiko import ConnectHandler
import time
import re
import sys
import subprocess
import os
#Devices Details

iosv_l2_s1 = {
    'device_type': 'cisco_ios',
    'ip': '1.1.1.1',
    'username': 'sdf',
    'password': 'ss',
}

#SSH to the below devices
net_connect = ConnectHandler(**iosv_l2_s1)
#Apply commands
output = net_connect.send_command('show interface')
max_time_allowed = 15
start = time.time()

while True:
    for line in output.split(os.linesep):
        if re.search(("(?=.*FUlL|2way)(?=.*192.168.0.4)"),line , re.I):
            print line
            start = time.time()
            time.sleep(2)
        elif (time.time() - start) > max_time_allowed:
            print ("timeup")

net_connect.disconnect()

1 个答案:

答案 0 :(得分:0)

在达到时间或执行print语句时将while循环更改为停止

max_time_allowed = 15
start = time.time()
found = 0  

while time.time()-start < max_time_allow and found == 0:
    output = net_connect.send_command('show interface')
    for line in output.split(os.linesep):
        if re.search(("(?=.*FUlL|2way)(?=.*192.168.0.4)"),line , re.I):
            print line
            found = 1
            time.sleep(2)
            break
if found == 0:
    print('TimeOut)