简体   繁体   中英

How to run two functions with asyncio?

I'm very confused by asyncio . My applications work fine separately, but when I try to combine them into one file, they fail.

  1. I want my chess engine to run: start_engine()

  2. I also want my websockets server to run: hello()

I want to communicate with my chess engine using websockets over the lan, so I need them both running at the same time.

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())

I believe the error is in the last few lines. In this case, the websockets server runs fine, but the chess engine never runs.

I'm assuming this is because asyncio.get_event_loop().run_forever() is above asyncio.run(main())

If I comment out the asyncio run_forever() lines from the bottom, the chess engine runs fine but the websockets server does not run.

How can I have both services running?

(I'm literally using the tutorial code for both services: websockets , and the chess engine )

I believe the error is in the last few lines.

Yes. In particular the function run_forever() , as its name implies, runs forever, so the next line is never executed.

The fix is to avoid run_forever , move all top-level logic to main , and issue a single asyncio.run at top-level. Inside async code run_until_complete can be replaced with await . For example (untested):

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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