[Python] From entry to advanced—Basic applications of commonly used third-party modules (14)

Pillow

PIL: Python Imaging Library, has become the de facto image processing standard library for the Python platform. PIL is very powerful, but the API is very simple and easy to use.

Install

pip install pillow

Manipulate images

  • Image zoom
    from PIL import Image
    
    # 打开一个jpg图像文件,注意是当前文件同路径:
    im = Image.open('test.jpg')
    # 获得图像尺寸:
    w, h = im.size
    print('获得图像尺寸: %sx%s' % (w, h))
    # 缩放到50%:
    im.thumbnail((w//2, h//2))
    print('缩放到百分之50: %sx%s' % (w//2, h//2))
    # 把缩放后的图像用jpeg格式保存:
    im.save('thumbnail.jpg', 'jpeg')
    
  • Other functions such as slicing, rotation, filters, output text, color palette, etc. are all available.

The blur effect also only requires a few lines of code:

# 打开一个jpg图像文件,注意是当前路径:
im = Image.open('test2.jpg')
# 应用模糊滤镜:
im2 = im.filter(ImageFilter.BLUR)
im2.save('blur.jpg', 'jpeg')

Insert image description here

Drawing

  • PIL's ImageDraw provides a series of drawing methods that allow us to draw directly. For example, to generate a letter verification code image:
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import random


# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 4
height = 60
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
# font = ImageFont.truetype('Arial.ttf', 36)
# wPIL无法定位到字体文件的位置。可以通过提供绝对路径解决,比如
font = ImageFont.truetype('C:\Windows\Fonts\Arial.ttf', 36)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(4):
    draw.text((60 * t + 10, 10), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')

Insert image description here
To learn more about the powerful functions of PIL, please refer to the official Pillow documentation: https://pillow.readthedocs.org/

requests

For details, see [Python] From Getting Started to Top—Application Scenarios of Network Request Modules urlib and reuests (12)

psutil

Using Python to write scripts to simplify daily operation and maintenance work is an important use of Python. Under Linux, there are many system commands that allow us to monitor the running status of the system at all times, such as ps,top,freeetc. To get this system information, Python can subprocess模块call and get the results. But it seems very troublesome to do so, especially if you have to write a lot of parsing code.

Another great way to get system information in Python is to use psutilthis third-party module. As the name suggests, psutil = process and system utilities, it not only 通过一两行代码实现系统监控,还可以跨平台使用supports Linux/UNIX/OSX/Windows , etc., it is an indispensable module for system administrators and operation and maintenance partners.

Install psutil

  • If Anaconda is installed, psutil is already available. Otherwise, you need to install it through pip from the command line:
pip install psutil

Get CPU information

import psutil
a = psutil.cpu_count() # CPU逻辑数量
print(a)
#12
a = psutil.cpu_count(logical=False) # CPU物理核心
print(a)
#6
# 2说明是双核超线程, 4则是4核非超线程

Statistics of CPU user/system/idle time:

print(psutil.cpu_times())
print(psutil.cpu_times())
print(psutil.cpu_times())
# scputimes(user=1372121.3125, system=716571.5468749963, idle=27169086.359375, interrupt=14799.3125, dpc=13208.703125)
# scputimes(user=1372121.3125, system=716571.5468749963, idle=27169086.359375, interrupt=14799.3125, dpc=13208.703125)
# scputimes(user=1372121.3125, system=716571.5468749963, idle=27169086.359375, interrupt=14799.3125, dpc=13208.703125)

Then implement the CPU usage similar to the top command, refresh once every second, a total of 10 times:

for x in range(10):
  print(psutil.cpu_percent(interval=1, percpu=True))

Get memory information

  • Use psutil to obtain physical memory and swap memory information, respectively:

    print(psutil.virtual_memory())
    print(psutil.swap_memory())
    #svmem(total=8589934592, available=2866520064, percent=66.6, used=7201386496, free=216178688, active=3342192640, inactive=2650341376, wired=1208852480)
    #sswap(total=1073741824, used=150732800, free=923009024, percent=14.0, sin=10705981440, sout=40353792)
    
    • The returned unit is 字节an integer. You can see that the total memory size is 8589934592 = 8 GB, used 7201386496 = 6.7 GB, used 66.6%.

      • The swap area size is 1073741824 = 1 GB.

Get disk information

  • Disk partition, disk usage and disk IO information can be obtained through psutil:

    print(psutil.disk_partitions()) # 磁盘分区信息
    	#[sdiskpart(device='/dev/disk1', mountpoint='/', fstype='hfs', opts='rw,local,rootfs,dovolfs,journaled,multilabel')]
    print(psutil.disk_usage('/')) # 磁盘使用情况
    	#sdiskusage(total=998982549504, used=390880133120, free=607840272384, percent=39.1)
    print(psutil.disk_io_counters()) # 磁盘IO
    	#sdiskio(read_count=988513, write_count=274457, read_bytes=14856830464, write_bytes=17509420032, read_time=2228966, write_time=1618405)
    
  • As you can see, the total capacity of disk '/' is 998982549504 = 930 GBused 39.1%. The file format is HFS, included in opts rw表示可读写, and journaled, indicating support for logs.

Get network information

  • psutil can obtain network interface and network connection information:
print(psutil.net_io_counters() ) # 获取网络读写字节/包的个数
"""snetio(bytes_sent=3885744870, bytes_recv=10357676702, packets_sent=10613069, packets_recv=10423357, errin=0, errout=0, dropin=0, dropout=0)"""

print(psutil.net_if_addrs()) # 获取网络接口信息
"""
{'以太网': [snicaddr(family=<AddressFamily.AF_LINK: -1>, address='0C-9D-92-65-DA-98', netmask=None, broadcast=None, ptp=None), 
snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.0.127', netmask='255.255.255.0', broadcast=None, ptp=None), 
snicaddr(family=<AddressFamily.AF_INET6: 23>, address='fe80::984a:5a08:d9c7:24d0', netmask=None, broadcast=None, ptp=None)], 
'以太网 2': [snicaddr(family=<AddressFamily.AF_LINK: -1>, address='00-FF-EA-24-69-58', netmask=None, broadcast=None, ptp=None), 
snicaddr(family=<AddressFamily.AF_INET: 2>, address='169.254.172.226', netmask='255.255.0.0', broadcast=None, ptp=None), 
snicaddr(family=<AddressFamily.AF_INET6: 23>, address='fe80::28da:dd33:7222:ace2', netmask=None, broadcast=None, ptp=None)], 
'以太网 3': [snicaddr(family=<AddressFamily.AF_LINK: -1>, address='00-FF-59-16-91-C0', netmask=None, broadcast=None, ptp=None), 
snicaddr(family=<AddressFamily.AF_INET: 2>, address='169.254.74.155', netmask='255.255.0.0', broadcast=None, ptp=None), s
nicaddr(family=<AddressFamily.AF_INET6: 23>, address='fe80::ad95:d3e2:6f8a:4a9b', netmask=None, broadcast=None, ptp=None)], 'Loopback Pseudo-Interface 1': 
[snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 23>, address='::1', netmask=None, broadcast=None, ptp=None)]
}
"""


print(psutil.net_if_stats()) # 获取网络接口状态)

"""
{'以太网': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1000, mtu=1500, flags=''), 
'以太网 2': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500, flags=''),
 '以太网 3': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=10, mtu=1400, flags=''),
  'Loopback Pseudo-Interface 1': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1073, mtu=1500, flags='')
  }
"""

To obtain current network connection information, use net_connections():
Insert image description here

Get process information

  • Detailed information about all processes can be obtained through psutil:
print(psutil.pids()) # 所有进程ID)
#[3865, 3864, 3863, 3856, 3855, 3853, 3776, ..., 45, 44, 1, 0]

p = psutil.Process(3776) # 获取指定进程ID=3776,其实就是当前Python交互环境
print(p.name()) # 进程名称
#'python3.6'

print( p.exe())# 进程exe路径
#'/Users/michael/anaconda3/bin/python3.6'

print( p.cwd()) # 进程工作目录)
#'/Users/michael'

print(p.cmdline()) # 进程启动的命令行)
#['python3']

print( p.ppid()) # 父进程ID)
print( p.parent()) # 父进程
#<psutil.Process(pid=3765, name='bash') at 4503144040>

print(p.children())  # 子进程列表

print(p.status()) # 进程状态
'running'

print(p.username()) # 进程用户名)

print(p.create_time()) # 进程创建时间
#1511052731.120333

print(p.terminal() )# 进程终端)
'/dev/ttys002'

print(p.cpu_times()) # 进程使用的CPU时间)
#pcputimes(user=0.081150144, system=0.053269812, children_user=0.0, children_system=0.0)

print(p.memory_info()) # 进程使用的内存
#pmem(rss=8310784, vms=2481725440, pfaults=3207, pageins=18)

print(p.open_files() ) # 进程打开的文件
#[]
print(p.connections() )# 进程相关网络连接
#[]

print( p.num_threads()) # 进程的线程数量
#1
print(p.threads() )# 所有线程信息)
#[pthread(id=1, user_time=0.090318, system_time=0.062736)]

print(p.environ() )# 进程环境变量)
#{'SHELL': '/bin/bash', 'PATH': '/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:...', 'PWD': '/Users/michael', 'LANG': 'zh_CN.UTF-8', ...}

print(p.terminate() )# 结束进程
#Terminated: 15 <-- 自己把自己结束了
  • Similar to obtaining a network connection, obtaining a root user's process requires root permissions. When starting the Python interactive environment or .py file, sudo permissions are required.

psutil also provides a test() function, which can simulate the effect of the ps command:

print(psutil.test())

Insert image description here

  • psutil can also obtain user information, Windows services and many other useful system information. For details, please refer to the official website of psutil: https://github.com/giampaolo/psutil

Guess you like

Origin blog.csdn.net/qq877728715/article/details/132846394