0
試圖在Windows機器上使用pyserial和asyncio。Pyserial和asyncio
受https://stackoverflow.com/a/27927704/1629704啓發我的代碼不斷地觀看傳入數據的串行端口。
# This coroutine is added as a task to the event loop.
@asyncio.coroutine
def get_from_serial_port(self):
while 1:
serial_data = yield from self.get_byte_async()
<doing other stuff with serial_data>
# The method which gets executed in the executor
def get_byte(self):
data = self.s.read(1)
time.sleep(0.5)
tst = self.s.read(self.s.inWaiting())
data += tst
return data
# Runs blocking function in executor, yielding the result
@asyncio.coroutine
def get_byte_async(self):
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
res = yield from self.loop.run_in_executor(executor, self.get_byte)
return res
串行數據返回後。在while循環中調用協程get_byte_async
以創建新的執行程序。我總是學會創建一個新的線程是昂貴的,所以我覺得我應該採取另一種方法,但我不知道如何做到這一點。 我一直在閱讀這篇文章https://hackernoon.com/threaded-asynchronous-magic-and-how-to-wield-it-bba9ed602c32#.964j4a5s7
我想我需要在另一個線程中讀取串口。但是如何讓串行數據返回到「主」循環?