[英]While Loop Breaking Problem (Python)
我目前正在尝试连接到GPS蓝牙设备。 我的Python 2.7代码最初可以正常工作,但是现在我尝试将代码实现为while循环,这样,尽管我的设备不可用,它仍会继续循环运行。 不幸的是,我的代码似乎陷入了循环,并反复打印出错误消息“无法找到蓝牙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“)。 如果没有设备具有此地址,我希望代码显示与无法找到设备有关的错误消息,然后希望它继续查找。
一方面,我最终还是希望编辑此代码,以便在X次尝试定位设备后/在X多次但无济于事的情况下,我希望代码结束并编写程序显示错误消息。 有什么指导吗?
谢谢
线
discovered_devices = discover_devices()
应该去你的内部while
循环,在进入之前for
循环。
然后用for
循环替换while
循环以限制尝试次数。
并正确退出内部for
循环,请按照@Jeremy的说明进行操作:添加
else:
continue
break
在它的结尾。
您可能还希望在外循环的每次迭代中使用sleep()
在每次尝试之间等待 。
您正在打破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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.