Python中的While循环中断问题
我现在正在尝试连接一个蓝牙GPS设备。我的Python 2.7代码最开始运行得很好,但我现在想把代码放进一个循环里,这样在设备不可用的时候,它可以一直尝试连接。不幸的是,我的代码似乎卡在了循环里,不停地打印出错误信息“无法找到蓝牙GPS设备。正在重试...”。我使用的是PyBluez的蓝牙模块。
这是我的代码:
import bluetooth
target_address = "00:11:22:33:44:55:66"
discovered_devices = discover_devices() # Object to discover devices from Bluetooth module
while True:
print "Attempting to locate the correct Bluetooth GPS Device..."
for address in discovered_devices:
if address != target_address:
print "Unable to Locate Bluetooth GPS Device. Retrying..."
else:
print "Bluetooth GPS Device Located: ", target_address
break
# move on to next statement outside of loop (connection etc...)
简单来说,我想实现的是让设备搜索功能启动,并在控制台上显示一条消息,表示它正在寻找一个发送特定设备地址的设备(比如“00:11:22:33:44:55:66”)。如果没有设备有这个地址,我希望代码能显示一个错误消息,说明无法找到设备,然后继续寻找。
另外,我还想最终修改这段代码,让它在尝试定位设备一段时间后,或者尝试了多次但都没有找到的情况下,结束程序并显示一个错误消息。对此有什么建议吗?
谢谢!
2 个回答
4
你是在中断for
循环,而不是外面的while
循环。如果在for
循环之后没有其他操作,你可以通过添加以下内容来让break
继续生效:
while True:
print "Attempting to locate the correct Bluetooth GPS Device..."
for address in discovered_devices:
if address != target_address:
print "Unable to Locate Bluetooth GPS Device. Retrying..."
else:
print "Bluetooth GPS Device Located: ", target_address
break
else:
# if we don't break, then continue the while loop normally
continue
# otherwise, break the while loop as well
break
5
这一行
discovered_devices = discover_devices()
应该放在你的 while
循环里面,进入 for
循环之前。
然后把你的 while
循环换成 for
循环,这样可以限制尝试的次数。
为了正确退出里面的 for
循环,按照 @Jeremy 的说法:在它的最后加上
else:
continue
break
。
你可能还想在每次尝试之间 等待,可以在外层循环的每次迭代中使用 sleep()
。