Python 异步 : yield from wasn't used with future?

标签 python python-asyncio

我正在尝试使用 asyncio 进行异步客户端/服务器设置。

出于某种原因,我在运行客户端时收到 AssertionError: yield from wasn't used with future

搜索此错误的结果并不多。
这个错误是什么意思,是什么原因造成的?

#!/usr/bin/env python3

import asyncio
import pickle
import uuid

port = 9999

class ClientProtocol(asyncio.Protocol):
    def __init__(self, loop):
        self.loop = loop
        self.conn = None
        self.uuid = uuid.uuid4()
        self.other_clients = []

    def connection_made(self, transport):
        print("Connected to server")
        self.conn = transport

        m = "hello"
        self.conn.write(m)

    def data_received(self, data):
        print('Data received: {!r}'.format(data))


    def connection_lost(self, exc):
        print('The server closed the connection')
        print('Stop the event loop')
        self.loop.stop()



# note that in my use-case, main() is called continuously by an external game engine
client_init = False
def main():
    # use a global here only for the purpose of providing example code runnable outside of aforementioned game engine
    global client_init

    if client_init != True:
        loop = asyncio.get_event_loop()
        coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)
        task = asyncio.Task(coro)

        transport, protocol = loop.run_until_complete(coro)

        client_init = True

    # to avoid blocking the execution of main (and of game engine calling it), only run one iteration of the event loop
    loop.stop()
    loop.run_forever()

    if transport:
        transport.write("some data")

if __name__ == "__main__":
    main()

回溯:

Traceback (most recent call last):
  File "TCPclient.py", line 57, in <module>
    main()
  File "TCPclient.py", line 45, in main
    transport, protocol = loop.run_until_complete(coro)
  File "/usr/lib/python3.5/asyncio/base_events.py", line 337, in run_until_complete
    return future.result()
  File "/usr/lib/python3.5/asyncio/futures.py", line 274, in result
    raise self._exception
  File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
    result = coro.send(None)
  File "/usr/lib/python3.5/asyncio/base_events.py", line 599, in create_connection
    yield from tasks.wait(fs, loop=self)
  File "/usr/lib/python3.5/asyncio/tasks.py", line 341, in wait
    return (yield from _wait(fs, timeout, return_when, loop))
  File "/usr/lib/python3.5/asyncio/tasks.py", line 424, in _wait
    yield from waiter
  File "/usr/lib/python3.5/asyncio/futures.py", line 359, in __iter__
    assert self.done(), "yield from wasn't used with future"
AssertionError: yield from wasn't used with future

最佳答案

问题似乎是您从协程创建了一个任务,但随后将协程传递给 run_until_complete:

    coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)
    task = asyncio.Task(coro)

    transport, protocol = loop.run_until_complete(coro)

要么通过任务:

    coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)
    task = asyncio.Task(coro)

    transport, protocol = loop.run_until_complete(task)

或者不创建任务,传递协程。 run_until_complete 将为您创建一个任务

    coro = loop.create_connection(lambda: ClientProtocol(loop), '127.0.0.1', port)

    transport, protocol = loop.run_until_complete(coro)

另外,你需要保证你写的字符串是字节串。 Python 3 中的字符串文字默认为 unicode。您可以对这些进行编码,也可以首先编写字节字符串

    transport.write("some data".encode('utf-8'))
    transport.write(b"some data")

编辑 我不清楚为什么这是个问题,但是 run_until_complete 的来源是这样说的:

WARNING: It would be disastrous to call run_until_complete() with the same coroutine twice -- it would wrap it in two different Tasks and that can't be good.

我想创建一个任务然后传入协程(这会导致创建一个任务)具有相同的效果。

关于Python 异步 : yield from wasn't used with future?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37404234/

相关文章:

列表中的 Python 正则表达式

python - django-admin.py startproject mysite 在 Windows 7 上运行不正常

java - Python 相当于 Java 的 statement.getGeneratedKeys()?

python - 使用 etree Python 解析 xml

python - 使用信号量限制并发 AsyncIO 任务数量不起作用

python - 如何使用异步请求保存 JSON 响应?

python - 为什么我不能在 asyncio 事件循环中使用并发.futures?

python - 类型错误 : '<' not supported between instances of 'PrefixRecord' and 'PackageRecord' while updating Conda

python - 如果任务完成并获得所需结果,则取消挂起的异步任务

python - 如何使用 ProcessPoolExecutor 优雅地终止 loop.run_in_executor?