Python asyncio:未来还没有使用yield?

时间:2016-05-24 04:09:22

标签: 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

1 个答案:

答案 0 :(得分:8)

问题似乎是你从你的协同程序创建了一个任务,但是然后将协同程序传递给了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的来源有这样的说法:

  

警告:调用run_until_complete()会是灾难性的   使用相同的协程两次 - 它将它包装成两个   不同的任务,这可能是好的。

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