Skip to content

🔧 常用标准库 ​

Python 自带"电池"——标准库里有几百个模块,涵盖了日常开发的方方面面。这一章介绍最常用、最实用的几个。

os — 操作系统接口 ​

python
import os

# 环境变量
print(os.environ.get("HOME"))     # /home/user
print(os.environ.get("PATH"))     # 系统 PATH
api_key = os.environ.get("API_KEY", "默认值")

# 路径操作(推荐用 pathlib,但 os.path 也要认识)
print(os.path.join("data", "users.csv"))  # data/users.csv
print(os.path.dirname("/a/b/c.txt"))      # /a/b
print(os.path.basename("/a/b/c.txt"))     # c.txt
print(os.path.exists("/tmp/test.txt"))    # True/False
print(os.path.getsize("bigfile.bin"))     # 文件大小(字节)

# 目录操作
os.makedirs("a/b/c", exist_ok=True)  # 递归创建目录
files = os.listdir(".")              # 列出当前目录

# 执行系统命令(简单)
os.system("echo hello")  # ⚠️ 有安全隐患,推荐用 subprocess

sys — 解释器交互 ​

python
import sys

# 命令行参数
# $ python script.py input.txt output.txt
print(sys.argv)        # ['script.py', 'input.txt', 'output.txt']
input_file = sys.argv[1] if len(sys.argv) > 1 else None

# 标准输入输出
sys.stdout.write("输出到标准输出\n")
sys.stderr.write("输出到错误输出\n")
# name = sys.stdin.readline().strip()  # 读一行

# 退出程序
if not input_file:
    print("用法:python script.py <文件路径>")
    sys.exit(1)  # 0=正常退出,非0=错误

# Python 路径
print(sys.version)     # 3.12.4
print(sys.platform)    # linux / darwin / win32
print(sys.path)        # 模块搜索路径

datetime — 日期时间操作 ​

python
from datetime import datetime, date, timedelta

# 现在
now = datetime.now()
print(now)                        # 2026-07-26 12:53:00.123456

# 创建指定时间
birthday = datetime(2000, 1, 1, 8, 0, 0)
print(birthday)                   # 2000-01-01 08:00:00

# 格式化 → 字符串
print(now.strftime("%Y-%m-%d"))           # 2026-07-26
print(now.strftime("%Y年%m月%d日 %H:%M"))  # 2026年07月26日 12:53

# 字符串 → datetime
d = datetime.strptime("2026-07-26", "%Y-%m-%d")
print(d.weekday())  # 6(周日=6,周一=0)

# 时间计算
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
half_hour = now + timedelta(hours=0.5)

# 日期差
delta = datetime(2027, 1, 1) - datetime.now()
print(f"距离元旦还有 {delta.days} 天")

# 时区(Python 3.9+)
from datetime import timezone, timedelta
beijing = timezone(timedelta(hours=8))
print(datetime.now(beijing))     # 北京时间

常用格式化代码:%Y 四位年、%m 月、%d 日、%H 时、%M 分、%S 秒。

re — 正则表达式 ​

正则表达式是文本处理的"瑞士军刀":

python
import re

text = "小雅的电话是 138-1234-5678,邮箱是 xiaoya@example.com"

# 搜索 — 找到第一个
match = re.search(r"\d{3}-\d{4}-\d{4}", text)
if match:
    print(match.group())  # 138-1234-5678

# 查找所有
phones = re.findall(r"\d{3}-\d{4}-\d{4}", text)
print(phones)  # ['138-1234-5678']
emails = re.findall(r"[\w.]+@\w+\.\w+", text)
print(emails)  # ['xiaoya@example.com']

# 替换
masked = re.sub(r"\d{3}-\d{4}-\d{4}", "***-****-****", text)
print(masked)  # 小雅的电话是 ***-****-****,邮箱是...

# 分组 — 提取子内容
match = re.search(r"(\d{3})-(\d{4})-(\d{4})", text)
if match:
    print(match.group(1))  # 138(第一组)
    print(match.group(2))  # 1234
    print(match.group(3))  # 5678

# 预编译(多次使用效率高)
pattern = re.compile(r"\d{3}-\d{4}-\d{4}")
print(pattern.findall(text))

# 常用模式
# \d 数字  \w 字母数字下划线  \s 空白字符  . 任意字符
# + 至少1个  * 0个或多个  ? 0或1个  {n} 恰好n个  {n,m} n到m个
# ^ 开头  $ 结尾  [abc] 字符集  | 或

random — 随机数 ​

python
import random

# 随机浮点数
print(random.random())        # [0.0, 1.0)
print(random.uniform(1, 10))  # [1, 10]

# 随机整数
print(random.randint(1, 6))   # [1, 6],包括6
print(random.randrange(1, 7)) # [1, 7),不包括7

# 序列操作
items = ["苹果", "香蕉", "橘子", "葡萄"]
print(random.choice(items))           # 随机选一个
print(random.sample(items, 2))        # 随机选2个不重复
random.shuffle(items)                 # 原地打乱
print(items)

# 设置种子 — 让"随机"可复现
random.seed(42)
print(random.randint(1, 100))  # 每次运行都一样

collections — 高级容器 ​

python
from collections import Counter, defaultdict, namedtuple, deque

# Counter — 计数器(统计利器)
words = ["apple", "banana", "apple", "orange", "banana", "apple"]
count = Counter(words)
print(count)                    # Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(count.most_common(2))     # [('apple', 3), ('banana', 2)]

# defaultdict — 带默认值的字典
dd = defaultdict(list)          # 访问不存在的 key 自动创建空列表
dd["fruits"].append("苹果")
dd["fruits"].append("香蕉")
print(dd)                       # {'fruits': ['苹果', '香蕉']}

# namedtuple — 命名的元组(轻量数据类)
Point = namedtuple("Point", ["x", "y"])
p = Point(3, 4)
print(p.x, p.y)  # 3 4

# deque — 双端队列(头尾插入删除 O(1))
dq = deque([1, 2, 3])
dq.appendleft(0)    # 左边加 → [0, 1, 2, 3]
dq.append(4)        # 右边加 → [0, 1, 2, 3, 4]
dq.popleft()        # 0
dq.pop()            # 4

subprocess — 执行外部命令 ​

python
import subprocess

# 执行命令、捕获输出(推荐方式)
result = subprocess.run(["ls", "-la"], capture_output=True, text=True)
print(result.stdout)      # 标准输出
print(result.returncode)  # 返回码,0=成功

# 检查返回码(非0抛异常)
subprocess.run(["git", "status"], check=True)

# 管道输入
result = subprocess.run(
    ["grep", "ERROR"],
    input="INFO: ok\nERROR: failed\nINFO: ok",
    capture_output=True,
    text=True
)
print(result.stdout)  # ERROR: failed

安全警告

永远不要用 shell=True + 用户输入拼接的命令。如果有人输入 rm -rf / 就完了。用列表形式传参始终更安全。

实战:系统信息采集脚本 ​

python
# /opt/kb/docs/python/sysinfo.py
"""系统信息采集脚本"""
import os
import sys
import platform
import datetime
from collections import OrderedDict

def collect_system_info():
    """采集当前系统的关键信息"""
    info = OrderedDict()
    info["采集时间"] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    info["主机名"] = platform.node()
    info["操作系统"] = f"{platform.system()} {platform.release()}"
    info["Python版本"] = sys.version.split()[0]
    info["当前用户"] = os.environ.get("USER", os.environ.get("USERNAME", "未知"))
    info["当前目录"] = os.getcwd()

    # 环境信息
    info["CPU核心数"] = os.cpu_count()
    info["PATH"] = os.environ.get("PATH", "未设置")[:80] + "..."

    return info

def print_report():
    """打印采集报告"""
    info = collect_system_info()
    print("=" * 50)
    print("        🖥  系统信息采集报告")
    print("=" * 50)
    for key, value in info.items():
        print(f"  {key: <10}: {value}")
    print("=" * 50)

if __name__ == "__main__":
    print_report()

练习题 ​

  1. 写脚本接受命令行参数,实现 python script.py --name 你的名字 --count 5 输出对应次数问候语
  2. 用 datetime 计算你出生到现在活了多少天
  3. 用 re 从一段文本中提取所有 URL(以 http:// 或 https:// 开头)
  4. 用 Counter 统计一个文件里单词频率的 TOP 20
  5. 用 subprocess 执行 ping -c 3 baidu.com 并解析通断结果

🔧 标准库是 Python 的底气。下节学 pip 与虚拟环境,管理项目依赖不打架。


🎯 本章要点 ​

  • os.environ.get(key, default) 安全读取环境变量,不存在时返回默认值
  • json 模块是 JSON 处理的标准选择。
加载练习题中...