gpt4 book ai didi

python - 使用 `with Pool() as p`进行错误处理

转载 作者:行者123 更新时间:2023-12-03 08:39:15 25 4
gpt4 key购买 nike

我有一个函数被分配给一个多处理pool:

with Pool(os.cpu_count() - 1) as p:
N = len(fpaths)
p.starmap(resample, zip(fpaths, new_paths, [sr] * N, ['WAV'] * N, [manifest] * N))
它正在更改一些音频文件。一个或两个文件已损坏,采样率为零。这将导致除以零的错误,如下所示:
multiprocessing.pool.RemoteTraceback: 
"""
Traceback (most recent call last):
File "/opt/conda/lib/python3.7/multiprocessing/pool.py", line 121, in worker
result = (True, func(*args, **kwds))
File "/opt/conda/lib/python3.7/multiprocessing/pool.py", line 47, in starmapstar
return list(itertools.starmap(args[0], args[1]))
File "/home/jupyter/jn-kaggle/birdsong/who-said-what/wsw/preprocessing.py", line 35, in resample
audio, sr = librosa.load(old_path, sr=sr)
File "/opt/conda/lib/python3.7/site-packages/librosa/core/audio.py", line 172, in load
y = resample(y, sr_native, sr, res_type=res_type)
File "/opt/conda/lib/python3.7/site-packages/librosa/core/audio.py", line 553, in resample
ratio = float(target_sr) / orig_sr
ZeroDivisionError: float division by zero
"""
我想处理此错误,但是,我尝试过的似乎不起作用:
def resample(old_path, new_path, sr, ext='WAV', manifest=None):
try:
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
print(f'Loading {old_path}',)
audio, sr = librosa.load(old_path, sr=sr)
except ZeroDivisionError:
audio, sr = librosa.load(old_path, sr=None)
print(f'Error loading file at {old_path}. file=sys.stderr)
我知道ZeroDivisionError是由 librosa.load()函数直接引起的,该函数从其自身的依赖项中获取了不正确的采样率0。我有一个修复程序,但我需要捕获错误。我怎么做?

最佳答案

这不是最终的答案,但是我不想在注释中压缩很多代码:
将异常设为一般,然后重试。我想确保除外块被调用。
试试这个代码:

def resample(old_path, new_path, sr, ext='WAV', manifest=None):
try:
print("Start Resample: ", old_path)
with warnings.catch_warnings():
warnings.simplefilter("ignore", UserWarning)
print(f'Loading {old_path}',)
audio, sr = librosa.load(old_path, sr=sr) # maybe error here
print("Done Resample: ", old_path)
except Exception as ex: # any exception
# audio, sr = librosa.load(old_path, sr=None) # remove for now
print('Error: ', ex)

关于python - 使用 `with Pool() as p`进行错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63474660/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com