问题描述
在对asyncio进行了相当多的阅读之后(我对此完全一无所知),我设法编写了一些简单的程序,这些程序可以满足我的要求。
但是,我对as_completed方法有一些疑问:我应该如何正确处理SIGINT信号。
因此,请提供以下代码段:
#as_completed_example.py
import asyncio
import tqdm
import datetime
import sys
import signal
import random
#--------------------------------------------------------------------------------------
async def heavy_load(i):
#tqdm.tqdm.write('#DEBUG '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' '+str(i))
await asyncio.sleep(random.random())
return None
#--------------------------------------------------------------------------------------
async def main():
length = int(sys.argv[1])
inputs = list(range(length))
pbar = tqdm.tqdm(total=len(inputs),position=0,leave=True,bar_format='#PROGRESS {desc}: {percentage:.3f}%|{bar}| {n_fmt}/{total_fmt} [{elapsed}<{remaining}')
tasks = [heavy_load(i) for i in inputs]
for future in asyncio.as_completed(tasks):
_ = await future
pbar.update(1)
pbar.refresh()
#---------------------------------------------------------------------------
def sigint_handler(signum,frame):
tqdm.tqdm.write('#INFO '+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+' user aborted execution!')
sys.exit(0)
#---------------------------------------------------------------------------
if(__name__=='__main__'):
signal.signal(signal.SIGINT,sigint_handler)
asyncio.run(main())
如果将其称为python3 as_completed_example.py 10000 (large number)
,则进度条在一段时间内会停留在0.00%的时间,而asyncio.as_completed正在准备其输入参数。没关系。
但是,如果在进度栏停留在0.00%的情况下发送SIGINT,则会收到大量未处理的异常。
我应该如何修改代码以使其能够被捕获?
提前谢谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)