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

标签 python python-3.x

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

相关文章:

python-3.x - Pygame 脚本停止响应

python - 自动 int 到 float 转换

python - 如何在 Django 模型中传递带有字符串的类名

python - 如何使用mysql数据库作为机器学习的数据集

Python - 特征匹配关键点与 OpenCV 之间的距离

python - 使用列表理解映射列表中的项目?

python-3.x - PyTorch 运行自定义损失函数

python - 为什么x的内容消失了。关于 python 中正确性的推理?

parsing - 如何以 Python 方式处理 IIS 日志解析?

python - 图像颜色检测