简体   繁体   English

Python 3.3中的time.sleep()函数?

[英]time.sleep() function in Python 3.3?

I'm trying to continuously run through a WHILE loop to check for a condition every fifteen minutes. 我正在尝试连续运行WHILE循环,每15分钟检查一次条件。 When using time.sleep(900) it instead holds off on executing the WHILE loop initially for fifteen minutes and then ceases to run through once the condition is met. 当使用time.sleep(900)时,它会在最初执行WHILE循环时保持十五分钟,然后在满足条件后停止运行。

I believe Python 2 used this function for this reason, does Python 3.3 not follow this anymore? 我相信Python 2出于这个原因使用了这个函数,Python 3.3不再遵循这个了吗? If not, how would I indefinitely run through a while loop, even if the condition has been met? 如果没有,即使满足条件,我将如何无限期地执行while循环?

Below is a snippet of my code currently: 以下是我目前的代码片段:

if price_now == 'Y':
    print(get_price())
else:
    price = "99.99"
    while price > "7.74":
        price = get_price()
        time.sleep(5)

Edit: Updated based on eandersson feedback. 编辑: 根据eandersson反馈更新。

if price_now == 'Y':
    print(get_price())
else:
    price = 99.99
    while price > 7.74:
        price = get_price()
        time.sleep(5)

The get_price() function: get_price()函数:

def get_price():
    page = urllib.request.urlopen("link redacted")
    text = page.read().decode("utf8")
    where = text.find('>$')
    start_of_price = where + 2
    end_of_price = start_of_price + 4
    price = float(text[start_of_price:end_of_price])
    return(price)

I think the problem in this case is that you are comparing a string, and not an float. 我认为在这种情况下的问题是你正在比较一个字符串,而不是一个浮点数。

price = 99.99
while price > 7.74:
    price = get_price()
    time.sleep(5)

And you need to change the get_price function to return an float, or wrap it with float() 你需要改变get_price函数来返回一个浮点数,或用float()包装它

I even made a small test function to make sure and it works as intended with the sleep function. 我甚至做了一个小的测试功能,以确保它与睡眠功能一起工作。

price = 99.99
while price > 7.74:
    price += 1
    time.sleep(5)

Edit: Updated based on comments. 编辑: Updated based on comments.

if price_now == 'Y':
    print(get_price())
else:
    price = 0.0
    # While price is lower than 7.74 continue to check for price changes.
    while price < 7.74: 
        price = get_price()
        time.sleep(5)

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

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