【发布时间】:2016-03-08 23:40:00
【问题描述】:
我有一个使用asyncio 运行的进程,它应该永远运行。
我可以使用 ProcessIterator 与该进程交互,它可以(此处省略)将数据发送到标准输入并从标准输出获取。
我可以通过async for fd, data in ProcessIterator(...):访问数据。
现在的问题是这个异步迭代器的执行必须是有时间限制的。如果时间用完,则调用timeout() 函数,
但该异常并非源自__anext__ 通知超时的函数。
如何在异步迭代器中引发此异常?
我发现没有办法为此打电话给awaitable.throw(something) 或类似的电话。
class ProcessIterator:
def __init__(self, process, loop, run_timeout):
self.process = process
self.loop = loop
self.run_timeout = run_timeout
# set the global timer
self.overall_timer = self.loop.call_later(
self.run_timeout, self.timeout)
def timeout(self):
# XXX: how do i pass this exception into the iterator?
raise ProcTimeoutError(
self.process.args,
self.run_timeout,
was_global,
)
async def __aiter__(self):
return self
async def __anext__(self):
if self.process.exited:
raise StopAsyncIteration()
else:
# fetch output from the process asyncio.Queue()
entry = await self.process.output_queue.get()
if entry == StopIteration:
raise StopAsyncIteration()
return entry
现在异步迭代器的用法大致如下:
async def test_coro(loop):
code = 'print("rofl"); time.sleep(5); print("lol")'
proc = Process([sys.executable, '-u', '-c', code])
await proc.create()
try:
async for fd, line in ProcessIterator(proc, loop, run_timeout=1):
print("%d: %s" % (fd, line))
except ProcessTimeoutError as exc:
# XXX This is the exception I'd like to get here! How can i throw it?
print("timeout: %s" % exc)
await proc.wait()
tl;dr:如何抛出一个定时异常,使其源自异步迭代器?
【问题讨论】:
标签: python python-3.5 python-asyncio