python - 如何修复不起作用的 Python Try/Except 语句
问题描述
我正在尝试在我的 Python 程序中合并一些错误处理,以便每当我的图像转换代码块抛出一个不会停止程序但会继续运行的错误时,但每次我遇到错误时它都会停止程序。我究竟做错了什么?这是我的代码:
if file.lower().endswith('.tif'): # <-- If file is a TIFF file and there are no errors yet
try:
imwrite(filepath[:-4] + '.jpg', 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] + '.jpg') # <-- Using the Image.open function from the Pillow library, we are getting the newly created JPEG file and opening it.
img = img.convert('RGB') # <-- Using the convert function we are making sure to convert the JPEG file to RGB color mode.
imageResize = img.resize((2500, 2500)) # <-- Using the resize function we are resizing the JPEG to 2500 x 2500
imageResize.save(filepath[:-4] + '.jpg') # <-- Using the save function, we are saving the newly sized JPEG file over the original JPEG file initially created.
except ValueError:
print('There was an error with the Image')
解决方案
而不是except ValueError你应该做except Exception因为可能的问题是抛出的错误不是值错误,所以现在如果发生任何错误,它将进入 except 部分
try:
do something
except Exception:
do something else
推荐阅读
- python - Django-“python manage.py runserver”不工作
- python - 运行带有exec问题nltk的python脚本
- php - SQLSTATE[HY000] [1045] 用户 'root'@'localhost' 在 ../laravel/framework/src/Illuminate/Database/Connectors/Connector.php:70 的访问被拒绝
- sql - SQL Server SELECT 唯一日期范围
- node.js - res.cookie 未在某些帐户的浏览器中设置 cookie
- nlp - PolyAnalyst:有没有办法让多个用户修复一个项目?
- c# - 如何在不连接到 SQL Server 的情况下在网络上发现 SSIS(SQL Server 集成服务)
- ioc-container - 使用 serviceKey 作为 DryIoc 解析的类的构造函数参数
- c++ - Doxygen 将实例化误解为成员
- html - 如果在表单标签中使用 ngModel,则必须设置 name 属性