3

我正在尝试连续运行 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)
4

1 回答 1

2

我认为这种情况下的问题是您正在比较一个字符串,而不是一个浮点数。

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

你需要改变get_price函数来返回一个浮点数,或者用float()

我什至做了一个小测试功能来确保它与睡眠功能一样正常工作。

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

编辑: 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)
于 2013-03-25T01:52:02.223 回答