简体   繁体   English

Python等待100秒并返回True或False

[英]Python while wait 100 seconds and return True or False

I have python script below, which checks whether ping is success, If it success within 100 Seconds it will return True. 我下面有python脚本,该脚本检查ping是否成功,如果在100秒内成功,它将返回True。 If ping is failed it should return False but it is not returning False and when ping is success it is returning True. 如果ping失败,则应返回False,但不返回False,当ping成功时,它将返回True。

Can anyone fix below code why it is not return False 任何人都可以修复下面的代码,为什么它不返回False

Code: 码:

def ping(self,hostname):
        time_check = datetime.now()
        data = ""
        while not "Success" in data:
            time.sleep(1)
            data = self.pingCheck("ping 10.10.10.1 count 5")
            if (datetime.now()-time_check).seconds > 100:
                return False
        return True

The code below will work for you: 以下代码将为您工作:

import time

def ping(self, hostname, try_for=100):
    t_end = time.time() + try_for
    is_succeed = False
    while time.time() < t_end or is_succeed:
        time.sleep(1)
        data = self.pingCheck("ping 10.10.10.1 count 5")
        is_succeed = "Success" in data
    return is_succeed

I've defined wait time as parameter called try_for , which default value is set to 100 , but you can pass any other amount of seconds which you want spend waiting for host availability. 我已经将等待时间定义为名为try_for参数,该参数的默认值设置为100 ,但是您可以传递任何其他希望用于等待主机可用性的秒数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM