【发布时间】:2016-10-09 18:54:39
【问题描述】:
在 python 3.5.1 中可以使用 await/async,但是,要使用它(我不明白),您需要有 awaitable 对象。
可等待对象是定义了返回迭代器的__await__() 方法的对象。更多信息here。
但我无法通过谷歌搜索出任何具有此功能的示例,因为大多数示例都有某种 asyncio.sleep(x) 来模拟等待对象。
我的最终目标是制作简单的 websocket 串行服务器,但是,我无法通过这第一步。 这是我的(非工作代码)。
import serial
import asyncio
connected = False
port = 'COM9'
#port = '/dev/ttyAMA0'
baud = 57600
timeout=1
class startser(object):
def __init__(self, port, baud):
self.port = port
self.baud = baud
def openconn(self):
self.ser = serial.Serial(port, baud)
async def readport(self):
#gooo= await (self.ser.in_waiting > 0)
read_byte = async self.ser.read(1).decode('ascii')
self.handle_data(read_byte)
print ("42")
def handle_data(self, data):
print(data)
serr=startser(port,baud)
serr.openconn()
loop = asyncio.get_event_loop()
#loop.run_forever(serr.readport())
loop.run_until_complete(serr.readport())
loop.close()
print ("finitto")
#with serial.Serial('COM9', 115200, timeout=1) as ser:
#x = ser.read() # read one byte
#s = ser.read(10) # read up to ten bytes (timeout)
#line = ser.readline() # read a '\n' terminated line`
【问题讨论】:
-
serial.Serial()不是等待对象。最终,您需要创建可等待的 I/O 原语,这些原语知道如何推迟执行直到数据可用。这不适合胆小的人。我认为还没有等待的串口。 -
@MartijnPieters 我认为串行的原理就像我们处理一些持久的数学算法一样。我不知道的是如何创建等待对象本身(如给出的文档链接中所述)。因为,虽然串行是不可等待的,但它可以“可能”被包装。我承认我不太了解 python,但我会尝试,我希望至少这第一步(创建等待对象)能在这里得到更多解释。
-
既然还没有建议,你应该看看:docs.python.org/3.5/library/…。我不完全确定您要实现什么,但是从文档中继承 Awaitable 抽象类将允许您创建自定义的“awaitable”对象。
标签: python websocket async-await pyserial python-3.5