python - 如何使用 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())
如果我从底部注释掉 asynciorun_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())
推荐阅读
- java - 如何使用二维按钮数组刷新面板?
- javascript - 如何在 D3 Js 中将 y 轴(yDomain)值设置为最大值
- r - 从 R 中的数据框创建相关矩阵
- reactjs - 在同一个文件中同时添加命名组件和默认组件是否合法?
- r - 使用 pacman 在 Ubuntu 中安装 R 包时出现依赖项错误
- python - sqlite python - 从txt文件将记录读入表
- python - 如何从两个列表中创建堆叠条形图:考虑一个是集群,另一个是标志
- c# - 如果特定值在行内,则更改行中的背景颜色
- javascript - Express 服务器在使用大字符串进行 post/put 请求时发送 500 错误代码
- kubernetes - 普罗米修斯可以一起刮目标吗?