编程语言
首页 > 编程语言> > 如何在执行程序任务仍在等待控制台输入的情况下干净退出python异步应用

如何在执行程序任务仍在等待控制台输入的情况下干净退出python异步应用

作者:互联网

我正在尝试将控制台输入侦听器添加到异步应用程序,但遇到了一个有趣的问题.

以下代码不会在应有的时候终止,而是在脚本终止后继续等待输入:

import asyncio


loop = asyncio.get_event_loop()

async def quit_after(timeout):
    await asyncio.sleep(timeout)
    print('main function terminating now') # this could simulate a crash, or a proper exit

async def print_input_loop():
    while True:
        # executor thread is daemon - should terminate when script ends, but doesn't
        text = await loop.run_in_executor(None, input, '> ')
        print(text)

if __name__ == '__main__':
    loop.create_task(print_input_loop())

    try:
        loop.run_until_complete(quit_after(5))
    finally:
        loop.close()

    print('reached end of file - script should now terminate')

我已经研究了其他异步获取输入的方法,例如在sys.stdin上使用add_reader(),但这在Windows上不起作用,我需要我的解决方案与平台无关.

有谁知道一种更好的异步获取控制台输入的方法,该方法可在应用程序暂停时正常停止运行,或者是一种修复现有代码以使其干净退出的方法?

解决方法:

可能的解决方法是为concurrent.futures中的线程禁用exit function

def disable_exit_for_threadpool_executor():
    import atexit
    import concurrent.futures
    atexit.unregister(concurrent.futures.thread._python_exit)

同样,aioconsole提供了一个跨平台功能来处理asyncio中的控制台输入:

import aioconsole

async def echo_loop():
    while True:
        text = await aioconsole.ainput('> ')
        print(text.strip())

标签:python-3-x,python-asyncio,python
来源: https://codeday.me/bug/20191111/2021745.html