简体   繁体   English

为什么这个使用yield from的Python程序不起作用?

[英]Why does this Python program using yield from not work?

I started with the following base code that works (Like the sample code at http://aaugustin.github.io/websockets/ ): 我从下面的基本代码开始工作(例如http://aaugustin.github.io/websockets/的示例代码):

import asyncio
import websockets

@asyncio.coroutine
def servePlayer(websocket, path):
    yield from websocket.send("Hello World")

start_server = websockets.serve(servePlayer, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

I modified this a bit to something similar but which no longer works. 我对此做了一些修改,但不再起作用。 I don't know why. 我不知道为什么 Here's the modified version: 这是修改后的版本:

import asyncio
import websockets

class Player:
    def __init__(self, connection):
        self.connection = connection
    def send(self, data):
        print("sending")
        yield from self.connection.send(data)

@asyncio.coroutine
def servePlayer(websocket, path):
    player = Player(websocket)
    player.send("Hello World")

start_server = websockets.serve(servePlayer, 'localhost', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()

The code does not even reach the "sending" line. 该代码甚至没有到达“发送”行。

Your player.send() method is a generator too; 您的player.send()方法也是生成器; you need to delegate to that generator: 您需要委派给该生成器:

@asyncio.coroutine
def servePlayer(websocket, path):
    player = Player(websocket)
    yield from player.send("Hello World")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM