七、 Python第三方包
1 优化代码异常输出包
一行代码优化输出的异常信息
pip install pretty-errors
写一个函数测试:
def divided_zero():
for i in range(10, -1, -1):
print(10/i)
divided_zero()
在没有import这个pretty-errors
前,输出的错误信息有些冗余:
Traceback (most recent call last):
File "c:\Users\HUAWEI\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\ptvsd_launcher.py", line 43, in <module>
main(ptvsdArgs)
File "c:\Users\HUAWEI\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py",
line 432, in main
run()
File "c:\Users\HUAWEI\.vscode\extensions\ms-python.python-2019.11.50794\pythonFiles\lib\python\old_ptvsd\ptvsd\__main__.py",
line 316, in run_file
runpy.run_path(target, run_name='__main__')
File "D:\anaconda3\lib\runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "D:\anaconda3\lib\runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "D:\anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "d:\source\sorting-visualizer-master\sorting\debug_test.py", line 6, in <module>
divided_zero()
File "d:\source\sorting-visualizer-master\sorting\debug_test.py", line 3, in divided_zero
print(10/i)
ZeroDivisionError: division by zero
我们使用刚安装的pretty_errors
,import
下:
import pretty_errors
def divided_zero():
for i in range(10, -1, -1):
print(10/i)
divided_zero()
此时看看输出的错误信息,非常精简只有2行,去那些冗余信息:
ZeroDivisionError:
division by zero
完整的输出信息如下图片所示:
2 图像处理包pillow
两行代码实现旋转和缩放图像
首先安装pillow:
pip install pillow
旋转图像下面图像45度:
In [1]: from PIL import Image
In [2]: im = Image.open('./img/plotly2.png')
In [4]: im.rotate(45).show()
旋转45度后的效果图
等比例缩放图像:
im.thumbnail((128,72),Image.ANTIALIAS)
缩放后的效果图:
过滤图像后的效果图:
from PIL import ImageFilter
im.filter(ImageFilter.CONTOUR).show()