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上不起作用,我需要我的解决方案与平台无关.

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

解决方法:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值