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

3 投票
1 回答
8947 浏览
提问于 2025-04-17 20:11

我想要每十五分钟检查一次某个条件,所以我打算一直运行一个WHILE循环。但是当我用time.sleep(900)时,它会先等十五分钟才开始执行WHILE循环,然后一旦条件满足就停止运行。

我记得Python 2是这样用这个函数的,Python 3.3是不是不再这样了?如果是的话,我该怎么做才能让WHILE循环一直运行,即使条件已经满足了呢?

下面是我目前的代码片段:

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

编辑: 根据eandersson的反馈进行了更新。

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

这个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)

1 个回答

2

我觉得这个问题的关键在于,你在比较一个字符串,而不是一个浮点数。

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

你需要把 get_price 这个函数改成返回一个浮点数,或者用 float() 把它包裹起来。

我甚至做了一个小测试函数来确认这一点,结果它和 sleep 函数一起工作得很好。

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

编辑: 根据评论进行了更新。

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)

撰写回答