标签:python-3-x python-asyncio 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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。