首页 > 解决方案 > 无法通过键盘中断 trio/asyncio 程序 (ctrl+c) 退出

问题描述

以下代码有效,但无法在 CTRL+c 时退出

谁能解释为什么,以及如何解决?

这是 asyncio 代码,但我使用 trio-asyncio(前瞻性规划)来允许我也使用 trio 代码。

#!.venv/bin/python

import asyncio

import trio
import trio_asyncio


from binance import AsyncClient, BinanceSocketManager

as_trio = trio_asyncio.aio_as_trio
as_aio = trio_asyncio.trio_as_aio

from contextlib import asynccontextmanager

@asynccontextmanager
async def AClient():
    client = await AsyncClient.create()
    try:
        yield client
    except KeyboardInterrupt:
        print('ctrl+c')
        exit(0)
    finally:
        await client.close_connection()

async def kline_listener(client):
    print(1)
    bm = BinanceSocketManager(client)
    async with bm.kline_socket(symbol='BNBBTC') as stream:
        while True:
            try:
                res = await stream.recv()
                print(res)
            except KeyboardInterrupt:
                break
@as_trio
async def aio_main():
    async with AClient() as client:
        exchange_info = await client.get_exchange_info()
        tickers = await client.get_all_tickers()
        print(client, exchange_info.keys(), tickers[:2])

        kline = asyncio.create_task(kline_listener(client))
        await kline

if __name__ == "__main__":
    trio_asyncio.run(aio_main)

我已经放置except KeyboardInterrupt在 2 个地方,尽管它似乎什么也没做。

标签: pythonpython-asynciokeyboardinterruptpython-trio

解决方案


推荐阅读