Python 常用模块大全(分场景整理,新手 & 职场高频)

分为:内置标准库 + 测试岗位必备第三方模块,代码均可直接运行,简洁好记

一、内置模块(无需安装)

1. os 目录文件操作

python
 
运行
 
 
import os

# 获取当前工作目录
print(os.getcwd())
# 列出文件夹内所有文件
print(os.listdir("."))
# 创建文件夹
if not os.path.exists("demo"):
    os.mkdir("demo")
# 删除文件夹
# os.rmdir("demo")
 

2. pathlib 现代路径处理(推荐)

python
 
运行
 
 
from pathlib import Path

p = Path("./demo/test.txt")
# 创建父级文件夹
p.parent.mkdir(exist_ok=True)
# 判断文件是否存在
print(p.exists())
# 拼接路径
new_path = Path("./") / "demo" / "1.txt"
print(new_path)
 

3. sys 解释器参数

python
 
运行
 
 
import sys

# 获取命令行传入参数
print(sys.argv)
# 退出程序
# sys.exit(0)
 

4. time 时间戳、休眠

python
 
运行
 
 
import time

# 时间戳
print(time.time())
# 程序暂停1秒
time.sleep(1)
# 格式化本地时间
print(time.strftime("%Y-%m-%d %H:%M:%S"))
 

5. datetime 日期计算(最常用)

python
 
运行
 
 
from datetime import datetime, timedelta

# 当前时间
now = datetime.now()
print(now)
# 三天前时间
three_day_ago = now - timedelta(days=3)
print(three_day_ago)
# 字符串转日期
dt = datetime.strptime("2026-07-21", "%Y-%m-%d")
 

6. random 随机数

python
 
运行
 
 
import random

# 1~10随机整数
print(random.randint(1, 10))
# 随机抽取列表一个元素
lst = [1,2,3,4]
print(random.choice(lst))
# 打乱列表
random.shuffle(lst)
 

7. re 正则表达式(文本提取)

python
 
运行
 
 
import re

text = "手机号:13800138000"
# 提取手机号
res = re.search(r"1[3-9]\d{9}", text)
if res:
    print(res.group())
 

8. json 字典和 json 字符串互转(接口测试必备)

python
 
运行
 
 
import json

data = {"name":"test","age":30}
# 字典转json字符串
json_str = json.dumps(data, ensure_ascii=False)
# json字符串转回字典
dict_data = json.loads(json_str)
print(json_str, dict_data)
 

9. logging 日志模块(项目必用)

python
 
运行
 
 
import logging

# 基础日志配置
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logging.debug("调试信息")
logging.info("普通日志")
logging.error("错误日志")
 

10. hashlib MD5 加密(密码加密)

python
 
运行
 
 
import hashlib

pwd = "123456"
md5 = hashlib.md5(pwd.encode("utf-8"))
print(md5.hexdigest())
 

11. csv 读写表格

python
 
运行
 
 
import csv

# 写入csv
with open("test.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(["姓名","年龄"])
    writer.writerow(["张三",25])
 

二、第三方模块(pip install xxx 安装)

1. requests 接口请求(接口自动化核心)

python
 
运行
 
 
# pip install requests
import requests

# get请求
resp = requests.get("https://httpbin.org/get")
print(resp.status_code)  # 响应状态码
print(resp.json())       # 返回json字典
 

2. pytest 测试框架 + 用例编写

python
 
运行
 
 
# pip install pytest
# 文件名必须以test_开头
def test_add():
    assert 1 + 1 == 2
 
终端执行:pytest test_demo.py -v

3. allure 生成精美测试报告

搭配 pytest 使用,执行命令:
 
pytest test_demo.py --alluredir=report
 
allure generate report -o html_report --clean

4. pandas 数据处理、读写 Excel

python
 
运行
 
 
# pip install pandas openpyxl
import pandas as pd

# 写入Excel
df = pd.DataFrame([["张三",22],["李四",24]], columns=["姓名","年龄"])
df.to_excel("user.xlsx", index=False)

# 读取Excel
data = pd.read_excel("user.xlsx")
print(data)
 

5. pymysql 操作 MySQL 数据库

python
 
运行
 
 
# pip install pymysql
import pymysql

# 连接数据库
conn = pymysql.connect(host="localhost",user="root",password="xxx",database="test")
cur = conn.cursor()
# 查询
cur.execute("select * from user limit 2;")
print(cur.fetchall())
cur.close()
conn.close()
 

6. selenium UI 自动化测试

python
 
运行
 
 
# pip install selenium webdriver-manager
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager

# 打开谷歌浏览器
driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))
driver.get("https://www.baidu.com")
print(driver.title)
driver.quit()
 

7. Pillow 图片处理

python
 
运行
 
 
# pip install pillow
from PIL import Image

# 打开图片缩放
img = Image.open("test.jpg")
img_resize = img.resize((300, 300))
img_resize.save("new.jpg")
 

8. schedule 定时任务

python
 
运行
 
 
# pip install schedule
import schedule
import time

def job():
    print("定时任务执行了")

# 每10秒运行一次
schedule.every(10).seconds.do(job)

while True:
    schedule.run_pending()
    time.sleep(1)
 

三、并发常用

threading 多线程(IO 密集型:爬虫、请求)

python
 
运行
 
 
import threading
import time

def task(n):
    print(f"线程{n}开始")
    time.sleep(2)
    print(f"线程{n}结束")

t1 = threading.Thread(target=task, args=(1,))
t2 = threading.Thread(target=task, args=(2,))
t1.start()
t2.start()


posted @ 2026-07-21 16:05  sjxm2017  阅读(0)  评论(0)    收藏  举报