【问题标题】:time.sleep() function in Python 3.3?Python 3.3 中的 time.sleep() 函数?
【发布时间】:2013-03-25 01:47:18
【问题描述】:

我正在尝试连续运行 WHILE 循环以每十五分钟检查一次条件。当使用 time.sleep(900) 时,它最初会推迟执行 WHILE 循环十五分钟,然后在满足条件后停止运行。

我相信 Python 2 出于这个原因使用了这个功能,Python 3.3 不再遵循这个功能了吗?如果不是,即使条件已经满足,我如何无限期地运行一个while循环?

下面是我当前代码的 sn-p:

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)

【问题讨论】:

  • 更新了您的问题以包含原始代码以防止任何混淆。 :)

标签: python python-3.x


【解决方案1】:

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

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)

【讨论】:

  • 嘿,谢谢!我将 get_price() 函数更改为包含浮点换行而不是字符串比较,并将 price = 和 while price > 更改为整数而不是字符串。我通过 make time.sleep(5) 测试了代码,但它似乎仍然运行一次然后退出循环。
  • 和@KMcK get_price() 现在在测试期间返回什么?
  • 我更新了代码以包含 get_price() 代码,并在测试时从它提取数据的位置返回当前 (int) 价格。
  • 好的@KMcK。请记住,price &gt; 7.74 表示 while 语句将在数据高于 7.74 时运行。如果 get_price() 返回的值低于该值,它只会执行一次。你确定不想要price &lt; 7.74
  • 这就是为什么我问你,你目前除了 get_price() 返回什么值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多