Python 睡眠功能未按预期工作

问题描述 投票:0回答:2

我确信我错过了一些非常基本的东西......我有一个调用睡眠函数的Python脚本。我希望主线程(在本例中)休眠 1 小时(3600 秒)。

以下是相关代码转载:

import time
from datetime import datetime

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Sleep", flush=True)

time.sleep(3600)

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Done sleeping", flush=True)

2小时后的输出为:

Current Time = 08:45:45
Sleep

但是我的代码永远不会退出睡眠功能来打印完成时间或“完成睡眠”消息。

(我在打印语句中添加了flush参数以消除潜在的缓冲,但我认为这与这里无关)。

对于为什么我的代码在 1 小时后没有退出睡眠功能有什么想法吗?

谢谢。

python sleep
2个回答
0
投票

您可以尝试这样的循环来告诉您超时需要多长时间。

import time
from time import perf_counter
from datetime import datetime

start = perf_counter()
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Sleep", flush=True)

# time.sleep(3600)
for i in range(3600):
    print("Seconds sleeping:{}".format(i))
    time_elapsed = perf_counter() - start
    print("Elapsed Time =", time_elapsed)
    time.sleep(1)

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Done sleeping", flush=True)

0
投票

我添加了 @Jortega 建议的 perf_counter。

我运行了 1 小时 (3600) 秒,在本例中它完成了,但也显示睡眠函数在 1 小时内“漂移”了约 18 秒。输出如下:

Seconds sleeping:3597
Elapsed Time = 3615.837408959
Seconds sleeping:3598
Elapsed Time = 3616.842702875
Seconds sleeping:3599
Elapsed Time = 3617.847937667
Current Time = 15:20:32
Done sleeping

这很有趣,但不幸的是,我仍然不确定为什么以下代码不起作用:

import time
from datetime import datetime

now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Sleep", flush=True)

time.sleep(3600)

now = datetime.now()   <================== Code never executes.
current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)
print("Done sleeping", flush=True)

如果有人有任何建议,我们将不胜感激。

© www.soinside.com 2019 - 2024. All rights reserved.