【发布时间】:2017-02-17 13:46:15
【问题描述】:
尝试在 Windows 机器上使用 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
我想我需要在另一个线程中读取串行端口。但是如何将串行数据返回到“主”循环?
【问题讨论】:
-
检查aioserial的实现。 github.com/changyuheng/aioserial
标签: python python-asyncio