Python 常用库
🐲 掌握了python的基础语法以及常用全局函数后, 下一步我们就应当掌握常用的python库, 写出能干活的代码!
以下列举了一些我们在项目中常见的库, 可能有所缺失, 但是不紧要, python的学习资料真的是太多了, 没有问题的。
借助python的库, 我们可以编写出强大的自动化脚本🧞♂️
安全哈希与摘要运算库 hashlib
import hashlib
# 对文件进行md5摘要计算, 检查文件是否完整
def md5_file(path):
md5 = hashlib.md5()
f = open(path, mode="rb")
md5.update(f.read())
f.close()
md5_sum = md5.hexdigest()
return md5_sum
# 对文本进行md5摘要计算
def md5_str(text):
md5 = hashlib.md5()
md5.update(f.text.encode("utf-8"))
md5_sum = md5.hexdigest()
return md5_sum
正则匹配库 re
import re
# 正则匹配
line = "Cats are smarter than dogs"
m = re.match( r'(.*) are (.*?) .*', line, re.M|re.I)
if m:
print("m.group() : ", m.group())
print("m.group(1) : ", m.group(1))
print("mgroup(2) : ", m.group(2))
else:
print("No match!!")
堆栈回溯库 trackback
# 错误回索
import traceback
def func1():
a = 5 / 0
def fun2():
try:
func1()
except:
print("错误信息以及调用堆栈:", traceback.format_exec())
时间库 time
import time
time.time() # 获取时间戳, 单位秒(s)
int(time.time()*1000) # 获取时间戳, 单位毫秒(ms), 类似java中的 System.currenttimemillis()
日期库 datetime
# 日期处理
import time
import datetime
def tm2date(tm):
timeArray = time.localtime(int(tm))
return time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
print(tm2date(time.time())) # 输出 2023-02-21 12:06:05
BASE64编码 base64
import base64
# 对字符串进行base64
s = '我是字符串'
a = base64.b64encode(s.encode())
print(a) # ztLKx9fWt/u0rg==
print(base64.b64decode(a).decode()) # 我是字符串
# 对文件进行base64
with open("/sdcard/1.png", mode="rb") as f:
print(base64.b64encode(f.read()))
# python的base64库非常强大, 还有base85, base16。。。
HTTP客户端库 requests
import requests
response = requests.get("https://www.baidu.com")
print(type(response))
print(response.status_code)
print(type(response.text))
print(response.text)
print(response.cookies)
print(response.content)
print(response.content.decode("utf-8"))
随机库 random
import random
# 随机生成一串长度为10的字符串
ret = ""
for i in range(10):
ret += random.choice("zxcvbnmasdfghjklqwertyuiop01234566789")
print(ret)
zip压缩库 zlib
# 压缩
import zlib
# 压缩字符串
s = "123456789"
z = zlib.compress(s.encode()) # 输出 b'x\x9c3426153\xb7\xb0\x04\x00\t\x1e\x01\xde'
# 文件压缩与解压
def compress(infile, dst, level=9):
infile = open(infile, 'rb')
dst = open(dst, 'wb')
compress = zlib.compressobj(level)
data = infile.read(1024)
while data:
dst.write(compress.compress(data))
data = infile.read(1024)
dst.write(compress.flush())
def decompress(infile, dst):
infile = open(infile, 'rb')
dst = open(dst, 'wb')
decompress = zlib.decompressobj()
data = infile.read(1024)
while data:
dst.write(decompress.decompress(data))
data = infile.read(1024)
dst.write(decompress.flush())
JSON库 json
import json
data = [ { 'a' : 1, 'b' : 2, 'c' : 3, 'd' : 4, 'e' : 5 } ]
# 数据转json
data2 = json.dumps(data)
print(data2) # 输出 [{"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}]
print(type(data2)) # 输出 <class 'str'>
图片处理库 pillow
from PIL import Image
image = Image.open("/sdcard/1.png")
print('width: ', image.width)
print('height: ', image.height)
print('size: ', image.size)
print('mode: ', image.mode)
print('format: ', image.format)
print('category: ', image.category)
print('readonly: ', image.readonly)
print('info: ', image.info)
# 裁剪图片
crop = imgage.crop((100,200,300,400,))
crop.save("/sdcard/2.png")
长链接通讯 websockets
import websocket
def on_message(ws, message):
print('Received message:', message)
def on_error(ws, error):
print('Error:', error)
def on_close(ws):
print('Connection closed')
def on_open(ws):
print('Connection opened')
# 发送消息到服务器
ws.send('Hello, Server!')
# 创建WebSocket对象, 并设置回调函数
websocket.enableTrace(True)
ws = websocket.WebSocketApp('ws://localhost:8080/ws',
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.on_open = on_open
# 执行连接和消息处理
ws.run_forever()
数据库 sqlite
import sqlite3
con = sqlite3.connect('data.db')
图像颜色空间转换 colorsys
colorsys模块提供了用于RGB和YIQ/HLS/HSV颜色模式的双向转换的接口。它提供了六个函数,其中三个用于将RGB转YIQ/HLS/HSV,另外三个用于将YIQ/HLS/HSV转为RGB。
colorsys.rgb_to_yiq(r, g, b)
colorsys.rgb_to_hls(r, g, b)
colorsys.rgb_to_hsv(r, g, b)
colorsys.yiq_to_rgb(y, i, q)
colorsys.hls_to_rgb(h, l, s)
colorsys.hsv_to_rgb(h, s, v)
🧣在自动化脚本开发中, 颜色的空间转换为我们计算颜色相似度提供了便利.
import colorsys
print(colorsys.rgb_to_hsv(30/255, 50/255, 160/255)) # 输出: (0.6410256410256411, 0.8125, 0.6274509803921569)
print(colorsys.hsv_to_rgb(0.5, 0.5, 0.4)) # 输出: (0.2, 0.4, 0.4)