问题描述
我正在使用多处理程序下载图像,并且我发现唯一的错误是您无法得到错误消息,除非有BaseException
。对于简单的情况,您可以运行循环并执行以下操作:
for i in range(start,start+end):
url = df.iloc[i,ind]
try:
load_save_image_from_url(url,DIR,str(i),resize=resize,resize_shape=resize_shape)
count+=1
except (KeyboardInterrupt,SystemExit):
sys.exit("Forced exit prompted by User: Quitting....")
except Exception as e:
print(f"Error at index {i}: {e}\n")
pass
它完全可以正常工作,但是当您使用Multiprocessing
时,既不能使用logging
也不能打印,因为仅描述了最后一个日志或打印。
try:
pool = Pool(workers)
pool.map(partial(load_save_image_from_url,OUT_DIR=DIR,resize_shape=resize_shape),lis_tups)
except (KeyboardInterrupt,SystemExit):
sys.exit("Forced exit prompted by User: Quitting....")
except ConnectionError:
logging.error(f"Connection Error for some URL")
pass
except Exception as e:
logging.error(f'Some Other Error most probably Image related')
pass
pool.close()
pool.join()
使用pool.get()
可以工作,但是必须处于循环状态,并且在程序结束时也必须如此。
解决方法
您可以在load_image函数本身内部捕获异常,并将其返回到主进程。
result = pool.map(load_image,...)
if result instanceof Exception:
# handle it
else:
# image loading succeded
def load_image():
try:
# make a get request
return image
except Exception as e:
return e