[英]How to run two functions with asyncio?
我对asyncio
很困惑。 我的应用程序单独工作正常,但是当我尝试将它们组合到一个文件中时,它们会失败。
我希望我的国际象棋引擎运行: start_engine()
我还希望我的websockets
服务器运行: hello()
我想通过局域网使用websockets
与我的国际象棋引擎通信,所以我需要它们同时运行。
import asyncio
import chess
import chess.engine
import websockets
async def hello(websocket, path):
fen = await websocket.recv()
print(f"< {fen}")
response = f"Got: {fen}"
await websocket.send(response)
print(f"> {response}")
async def start_engine(engine, board):
fen = "2k1r3/pR2bp2/2p1p3/N3P1p1/1PP2n2/P4P2/7r/2K2BR1 b - - 0 28"
board = chess.Board(fen)
print(board)
with await engine.analysis(board, multipv=1) as analysis:
async for info in analysis:
try:
score = info.get("score")
pv = info.get("pv")[0]
depth = info.get("seldepth")
# I want to stream this data infinitely to the websocket client
print(score, pv, depth)
except:
continue
if info.get("seldepth", 0) > 15:
break
await engine.quit()
async def main():
engine_path = "/usr/local/bin/stockfish"
transport, engine = await chess.engine.popen_uci(engine_path)
board = chess.Board()
await start_engine(engine, board)
start_server = websockets.serve(hello, "localhost", 11111)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
asyncio.run(main())
我相信错误出现在最后几行。 在这种情况下,websockets 服务器运行良好,但国际象棋引擎从未运行。
我假设这是因为asyncio.get_event_loop().run_forever()
高于asyncio.run(main())
如果我从底部注释掉 asyncio run_forever()
行,则国际象棋引擎运行良好,但 websockets 服务器不运行。
我怎样才能同时运行这两个服务?
(我实际上是在使用这两种服务的教程代码: websockets和chess engine )
我相信错误出现在最后几行。
是的。 特别是 function run_forever()
,顾名思义,永远运行,所以下一行永远不会执行。
解决方法是避免run_forever
,将所有顶级逻辑移至main
,并在顶级发出单个asyncio.run
。 内部异步代码run_until_complete
可以替换为await
。 例如(未经测试):
async def main():
await websockets.serve(hello, "localhost", 11111)
engine_path = "/usr/local/bin/stockfish"
transport, engine = await chess.engine.popen_uci(engine_path)
board = chess.Board()
await start_engine(engine, board)
asyncio.run(main())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.