在windows机器上尝试使用带有asyncio的pyserial。
受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
我想我需要在另一个线程中读取串行端口。但是如何将串行数据返回到“主”循环呢?
发布于 2017-02-18 00:22:15
您可以使用默认的执行器,并使用asyncio lock锁定对get_byte的访问
async def get_byte_async(self):
async with self.lock:
return await self.loop.run_in_executor(None, self.get_byte)或者只需创建一次自己的executor:
async def get_byte_async(self):
if self.executor is None:
self.executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
return await self.loop.run_in_executor(self.executor, self.get_byte)https://stackoverflow.com/questions/42299555
复制相似问题