Python 3:使用asyncio通过输入命令清除退出

Python 3:使用asyncio通过输入命令清除退出,python,exit,Python,Exit,在执行使用asyncio的Python脚本时,我很难通过输入命令将干净的出口返回到终端 该脚本做了大量工作,但也提供了用于输入的CLI。 键入“done”并按enter键将关闭整个脚本。 我试着用下面的代码来实现,但它似乎不起作用 脚本的代码: try: cm_cli = CmCli(iot_net, loop, logger) cm_cli.start() loop.run_forever() except KeyboardInterrupt: print("

在执行使用asyncio的Python脚本时,我很难通过输入命令将干净的出口返回到终端

该脚本做了大量工作,但也提供了用于输入的CLI。 键入“done”并按enter键将关闭整个脚本。 我试着用下面的代码来实现,但它似乎不起作用

脚本的代码:

try:
    cm_cli = CmCli(iot_net, loop, logger)
    cm_cli.start()

    loop.run_forever()
except KeyboardInterrupt:
    print("[CerberOS_Manager] Shutting everything down.")
    for task in asyncio.Task.all_tasks():
        task.close()
    loop.stop()
    sys.exit()
键入“完成”时在cm_cli中执行的代码:

def run(self):
    print("[CM_CLI] Type 'help' for available commands, 'test' to run test.")
    while True:
        print('\033[0m', end=' ')     # stop printing yellow
        params = (input('>> '))
        print('\033[1;33m', end=' ')  # start printing yellow

        params = params.split()
        if len(params) < 1:
            continue

        if  params[0] == "help":
            print("[CM_CLI] Available commands are:")
        elif  params[0] == "":
            continue
        elif  params[0] == "done":
            print("[CM_CLI] Exiting.")
            raise KeyboardInterrupt
        else:
            print("[CM_CLI] Unknown command.")

因此,它会引发中断,但无法到达另一部分的打印输出。我尝试过在cm_cli中关闭循环,但没有更接近。有没有关于干净地返回航站楼的建议?

看看这个例子:

import asyncio

def hello_world(loop):
    print('Hello World')
    loop.stop()

loop = asyncio.get_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
loop.run_forever()
loop.close()

您应该在回调函数(
run()
)中捕获异常,并在其中激发
loop.stop()
。然后在主模块中使用
loop.close()

看看这个例子:

import asyncio

def hello_world(loop):
    print('Hello World')
    loop.stop()

loop = asyncio.get_event_loop()

# Schedule a call to hello_world()
loop.call_soon(hello_world, loop)

# Blocking call interrupted by loop.stop()
loop.run_forever()
loop.close()
您应该在回调函数(
run()
)中捕获异常,并在其中激发
loop.stop()
。然后在主模块中使用
loop.close()