簡體   English   中英

如何使用 asyncio 運行兩個函數?

[英]How to run two functions with asyncio?

我對asyncio很困惑。 我的應用程序單獨工作正常,但是當我嘗試將它們組合到一個文件中時,它們會失敗。

  1. 我希望我的國際象棋引擎運行: start_engine()

  2. 我還希望我的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 服務器不運行。

我怎樣才能同時運行這兩個服務?

(我實際上是在使用這兩種服務的教程代碼: websocketschess 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM