Serial port 如何对串行输入进行协同路由等待?
我有一个类似于中描述的结构 不同的是,我的“生产者”将打开一个串行行并异步解析输入,直到识别出一个“令牌”(而不是生成随机数)。令牌然后通过asyncio.Queue传递给“消费者” 暂定代码包括:Serial port 如何对串行输入进行协同路由等待?,serial-port,python-asyncio,Serial Port,Python Asyncio,我有一个类似于中描述的结构 不同的是,我的“生产者”将打开一个串行行并异步解析输入,直到识别出一个“令牌”(而不是生成随机数)。令牌然后通过asyncio.Queue传递给“消费者” 暂定代码包括: @asyncio.coroutine def produce(): with open('infile.cmd', 'r') as ifd: while True: cmd = yield from ifd.readline()
@asyncio.coroutine
def produce():
with open('infile.cmd', 'r') as ifd:
while True:
cmd = yield from ifd.readline()
if cmd is None:
break
print("received {}".format(cmd))
yield from q.put(cmd)
但这不起作用,因为在ifd.readline()
行上出现了“RuntimeError:Task得到了错误的结果:'p'”
我还尝试使用阅读器(cfr.::
但是这个炸弹有:
Traceback (most recent call last):
File "/home/mcon/trasmissione-telematica/Communications/prove/asio.py", line 32, in <module>
event_loop.add_reader(ifd, produce)
File "/usr/lib/python3.5/asyncio/selector_events.py", line 337, in add_reader
return self._add_reader(fd, callback, *args)
File "/usr/lib/python3.5/asyncio/selector_events.py", line 267, in _add_reader
(handle, None))
File "/usr/lib/python3.5/selectors.py", line 412, in register
self._epoll.register(key.fd, epoll_events)
PermissionError: [Errno 1] Operation not permitted
回溯(最近一次呼叫最后一次):
文件“/home/mcon/trasmissione telematica/Communications/prove/asio.py”,第32行,在
事件\循环。添加\读取器(ifd,生成)
文件“/usr/lib/python3.5/asyncio/selector\u events.py”,第337行,在add\u reader中
返回self.\u添加\u读取器(fd、回调、*args)
文件“/usr/lib/python3.5/asyncio/selector\u events.py”,第267行,在添加读取器中
(手柄,无)
寄存器中第412行的文件“/usr/lib/python3.5/selectors.py”
self.\u epoll.寄存器(key.fd,epoll\u事件)
PermissionError:[Errno 1]不允许进行操作
如何异步读取某些内容
注意:在本例中,我从文件中读取数据,但最终我必须从非阻塞串行线(或/dev/ttySx或命名管道)读取二进制数据,因此允许面向o行的输入;必须在数据可用时立即读取数据,“生产者”负责理解“cmd”何时完成。使用和python 3.5+以下代码非常有效:
async def produce():
async with aiofiles.open('test.cmd', mode = 'r') as ifd:
while True:
cmd = await ifd.readline()
#readlines ourput is not stripped
cmd = cmd.strip()
if not cmd or cmd=='stop':
print("finished")
break
print("cmd {}".format(cmd))
await q.put(cmd)
loop = asyncio.get_event_loop()
q = asyncio.Queue()
loop.run_until_complete(produce())
test.cmd
mv hello
cp world
stop
输出:
cmd mv hello
cmd cp world
finished
查看aioserial:
cmd mv hello
cmd cp world
finished