【问题标题】:Python3 time.sleep() behaving erraticallyPython3 time.sleep() 行为异常
【发布时间】:2020-06-25 11:51:38
【问题描述】:

L.S,

我正在尝试学习 python(3),但对 time.sleep() 的行为感到困惑 我在 rpi3b 上运行 raspbian buster。

#!/usr/bin/python3
import bluetooth
import sys
import time
_shuttermac ="11:22:33:44:5D:6A"
while True:
    # check if the device is switched on by mac address lookup
    print("Checking " + time.strftime("%a, %d %b %Y %H:%M:%S - ", time.gmtime()),end ="")
    result = bluetooth.lookup_name(_shuttermac, timeout=5)
    #print(result)
    if (result != None):
        print("Device detected by bluetooth mac lookup")
    else:
        print("Device with MAC " + _shuttermac + " NOT detected")
    time.sleep(1)   # check every 5 secs if device comes online      
sys.exit()

输出

Checking Thu, 25 Jun 2020 11:21:02 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:08 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:14 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:20 - Device with MAC 11:22:33:44:5D:6A NOT detected
Checking Thu, 25 Jun 2020 11:21:26 - Device with MAC 11:22:33:44:5D:6A NOT detected

如您所见,输出语句间隔 6 秒,而不是 1 编码

我哪里做错了?

【问题讨论】:

    标签: python-3.x sleep


    【解决方案1】:

    之所以出现六秒间隔,是因为while True的每个循环在查找失败时都会做两件耗时的事情:

    1. bluetooth.lookup_name(_shuttermac, timeout=5) 有 5 秒超时。如果很快找到,应该会更快完成
    2. time.sleep(1) 将整个 Python 程序暂停 1 秒

    您可以缩短bluetooth.lookup_name 的超时时间和sleep() 的持续时间。这可能会对查找的准确性产生意想不到的后果(我不是很熟悉)。

    【讨论】:

      猜你喜欢
      • 2021-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多