Python实用模块推荐3:Pillow、psutil

PIL即Python Image Library,是python图像处理的标准库,不过它仅仅支持python2,后来有人在原来版本的基础上增加了对python3的支持,就形成了Pillow这个库并且开源了,地址是https://github.com/python-pillow/Pillow
安装Pillow

pip install pillow

from PIL import Image, ImageFilter
# 测试图片大小为400×400
img = Image.open(‘test.jpg’)
# 图像的缩放
w, h = img.size
img.thumbnail((w/2, h/2))
img.save(‘thumbnail.jpg’)
# 图像的模糊,使用的是ImageFilter,它可以做很多事情,如高斯模糊ImageFilter.GaussianBlur、普通模糊ImageFilter.BLUR、边缘增强ImageFilter.EDGE_ENHANCE等等
img_blur = img.filter(ImageFilter.BLUR)
img_blur.save(‘blur.jpg’)
# 图像的裁剪
img_crop = img.crop((0, 0, 200, 200))
img_crop.save(‘crop.jpg’)
# 图像的粘贴,原图像已经变化
img.paste(img_crop, (200, 200))
img.save(‘paste.jpg’)
# 图像的旋转,原图像保持不变
img.rotate(90).save(‘rotate_90.jpg’)
img.rotate(180).save(‘rotate_180.jpg’)
img.rotate(270).save(‘rotate_270.jpg’)
img.rotate(50).save(‘rotate_50.jpg’)

psutils
psutil(process and system utilities)是一个跨平台的获取系统信息(CPU、内存、磁盘、网络等)的库。在linux系统中可以通过一些命令工具来查看系统信息,如top、dstat、vmstat等,如果使用subprocess调用也能实现目标,但是自己解析起来比较麻烦。
安装psutil

1pip install psutil

CPU相关实例

In [1]: import psutil
In [2]: psutil.cpu_times()
Out[2]: scputimes(user=12359.56, nice=30.75, system=2791.42, idle=105554.11, iowait=945.91, irq=0.0, softirq=94.67, steal=0.0, guest=0.0, guest_nice=0.0)
In [7]: psutil.cpu_count()
Out[7]: 4
In [8]: psutil.cpu_count(logical=False)
Out[8]: 2
In [9]: psutil.cpu_stats()
Out[9]: scpustats(ctx_switches=161457633, interrupts=43726924, soft_interrupts=34136310, syscalls=0)
In [10]: psutil.cpu_freq()
Out[10]: scpufreq(current=1829.73775, min=500.0, max=2700.0)

内存相关实例

In [2]: psutil.virtual_memory()
9Out[2]: svmem(total=12505137152, available=5109202944, percent=59.1, used=6563024896, free=887455744, active=7999864832, inactive=2919788544, buffers=939851776, cached=4114804736, shared=508735488, slab=418844672)
In [3]: psutil.swap_memory()
Out[3]: sswap(total=4154454016, used=0, free=4154454016, percent=0.0, sin=0, sout=0)

磁盘相关实例
psutil.disk_partitions()
网络相关实例
psutil.net_io_counters(pernic=True)
Popen封装
p = psutil.Popen([“python”, “-c”, “print(‘hello’)”], stdout=PIPE)

发表评论