L.S,
我正在尝试学习python(3),并且对time.sleep()的行为感到困惑,我在rpi3b上运行raspbian。
#!/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。
我哪里出错了?
发布于 2020-06-25 12:09:00
6秒间隔是因为当查找失败时,while True的每个循环都会执行两个耗时的操作:
bluetooth.lookup_name(_shuttermac, timeout=5)有5秒的超时时间。如果快速找到它,它应该完成fastertime.sleep(1)暂停整个Python程序1秒的。
您可以缩短bluetooth.lookup_name的超时时间和sleep()持续时间。这可能会给查找的准确性带来意想不到的后果(我对它不太熟悉)。
https://stackoverflow.com/questions/62574671
复制相似问题