【发布时间】:2020-08-21 15:46:25
【问题描述】:
我有我要调用函数的主要 Python 脚本。我想捕获函数执行期间发生的任何错误,如果有任何错误,我想将错误变量设置为 true。主脚本中的 try/except 语句是否像这样:
try:
image_convert(filepath,'.jpg','RGB',2500,2500)
except:
error = true
还是像这样在函数内部完成:
def image_convert(filepath,imageType,colorMode,height,width):
try:
imwrite(filepath[:-4] + imageType, imread(filepath)[:,:,:3].copy()) # <-- using the imagecodecs library function of imread, make a copy in memory of the TIFF File.
# The :3 on the end of the numpy array is stripping the alpha channel from the TIFF file if it has one so it can be easily converted to a JPEG file.
# Once the copy is made the imwrite function is creating a JPEG file from the TIFF file.
# The [:-4] is stripping off the .tif extension from the file and the + '.jpg' is adding the .jpg extension to the newly created JPEG file.
img = Image.open(filepath[:-4] + imageType) # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
img = img.convert(colorMode) # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
imageResize = img.resize((height, width)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
imageResize.save(filepath[:-4] + imageType) # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.
return(imageResize)
except:
error = true
【问题讨论】:
-
第二个版本不会有太大用处,除非你让
error变量可以被调用上下文以某种方式访问。 -
我不会捕捉到函数中的错误。如果你这样做了,你的函数就会担心处理错误以及它的实际任务。如果它抛出,它就会抛出。任何想处理错误的人都可以抓住它。有时它是合适的,但我看不出这里有任何理由为什么该函数应该知道关于
error的任何信息。 -
可能是 both 的组合,具体取决于 可能 引发的异常。其中一些你可以在函数内部以某种方式处理,其他的可能更好地传播给其他人一个处理它们的机会。
标签: python python-3.x error-handling try-except