为什么这个使用 yield from 的 Python 程序不起作用?
Why does this Python program using yield from not work?
我从以下有效的基本代码开始(如 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()
我将其修改为类似但不再有效的内容。我不知道为什么。这是修改后的版本:
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()
代码甚至没有到达 "sending" 行。
您的 player.send()
方法也是一个生成器;您需要委托给该生成器:
@asyncio.coroutine
def servePlayer(websocket, path):
player = Player(websocket)
yield from player.send("Hello World")
我从以下有效的基本代码开始(如 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()
我将其修改为类似但不再有效的内容。我不知道为什么。这是修改后的版本:
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()
代码甚至没有到达 "sending" 行。
您的 player.send()
方法也是一个生成器;您需要委托给该生成器:
@asyncio.coroutine
def servePlayer(websocket, path):
player = Player(websocket)
yield from player.send("Hello World")