首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Pyserial和asyncio

Pyserial和asyncio
EN

Stack Overflow用户
提问于 2017-02-17 21:46:15
回答 1查看 1.2K关注 0票数 1

在windows机器上尝试使用带有asyncio的pyserial。

https://stackoverflow.com/a/27927704/1629704的启发,我的代码不断地监视串行端口以获取传入的数据。

代码语言:javascript
复制
# 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

我想我需要在另一个线程中读取串行端口。但是如何将串行数据返回到“主”循环呢?

EN

回答 1

Stack Overflow用户

发布于 2017-02-18 00:22:15

您可以使用默认的执行器,并使用asyncio lock锁定对get_byte的访问

代码语言:javascript
复制
async def get_byte_async(self):
    async with self.lock:
        return await self.loop.run_in_executor(None, self.get_byte)

或者只需创建一次自己的executor:

代码语言:javascript
复制
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)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42299555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档