首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如果在for内循环多个条件和计时器python

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

Stack Overflow用户
提问于 2017-07-30 11:18:03
回答 1查看 298关注 0票数 1

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

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

我只想打印一次行,或者在超时的情况下超时一次,并且在max_time_allowed中继续尝试前面的命令,因为它可能会在几秒钟后出现

代码语言:javascript
复制
#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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-30 12:35:02

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

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45396016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档