我正在嘗試連接到GPS藍牙設備。我的Python 2.7代碼最初工作正常,但我現在試圖將我的代碼實現到while循環中,以便在我的設備不可用時,它將繼續保持循環。不幸的是,我的代碼似乎陷入了一個循環,並重復打印出錯誤消息「無法找到藍牙GPS設備。重試...」我使用的是來自PyBluez的藍牙模塊。While Loop Breaking Problem(Python)
這裏是我的代碼: -
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場合但無濟於事之後,我希望代碼結束並顯示錯誤消息的程序。有關於此的任何指導?
感謝
如果您正在進行任何睡眠以減慢while循環,請務必在'continue'之前的'else'子句中執行,而不要在'continue'之下執行。另外,我認爲Simon是正確的 - 設備發現應該位於while循環的頂部,否則每次迭代都是一樣的。 – agf