我正在尝试连续运行 WHILE 循环以每十五分钟检查一次条件。当使用 time.sleep(900) 时,它会先暂停执行 WHILE 循环 15 分钟,然后在满足条件后停止运行。
我相信 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)
最佳答案
我认为这种情况下的问题在于您比较的是字符串,而不是 float 。
price = 99.99
while price > 7.74:
price = get_price()
time.sleep(5)
并且您需要更改 get_price
函数以返回一个 float ,或者用 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)
关于python - Python 3.3 中的 time.sleep() 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15606437/