Python标准库里Generic OS(python3 标准库)

想在Python里畅玩系统底层操作?不想自己重造轮子?Python标准库里Generic OS Services系列库 就有操纵操作系统接口、文件流、时间日志,还能跑到C里去打怪的利器。今天咱就来聊聊它们到底是个什么货,能帮你解决哪些痛点,还有实操代码,最后还给你优缺点盘点,一看就懂!

引子:为什么要懂这些?
你可能只会 os.listdir open time.sleep 这几招。可当项目复杂了,日志、配置、跨平台信息、C接口……一大堆坑等着你跳。Python标准库中的 Generic OS Services 帮你把底层接口、文件流、时间、日志、平台信息、errno、ctypes……全都揽进怀里,不再重写一堆重复代码。


os —— 神级文件和进程接口

代码示例:

import os

# 递归创建目录
os.makedirs('logs/2025/07', exist_ok=True)

# 列出当前目录下的所有文件
print(os.listdir('.'))

# 读取环境变量
db_url = os.getenv('DATABASE_URL', 'sqlite:///:memory:')
print('DB:', db_url)

io —— 流的掌控者

代码示例:

import io

# StringIO:当做文件写写读读
buf = io.StringIO()
buf.write('Hello, io!')
buf.seek(0)
print(buf.read()) # Hello, io!

# BytesIO:操作二进制
b = io.BytesIO(b'\xe4\xbd\xa0\xe5\xa5\xbd')
print(b.read().decode('utf-8')) # 你好

time —— 时间就是金钱?好好玩转它

代码示例:

import time

start = time.perf_counter()
time.sleep(1.5)
end = time.perf_counter()
print(f'耗时:{end - start:.3f}s')

# 格式化当前时间
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))

logging家族 —— 你的程序也该有日志小秘书


platform、errno、ctypes —— 底层信息和扩展大神

简单示例:

import platform, errno, ctypes

print('系统:', platform.system(), platform.release())
print('ARCH:', platform.machine())
print('ENOENT:', errno.ENOENT) # 文件不存在错误码

# ctypes 调用 C 的 printf
libc = ctypes.CDLL(None)
libc.printf(b'Hello %s!\n', b'ctypes')

模块总览表

模块
功能
典型函数/类
os
文件、目录、进程、环境变量
makedirs, listdir, fork, getenv
io
内存/文件流抽象
StringIO, BytesIO, TextIOWrapper
time
时间戳、睡眠、格式化/解析
time, perf_counter, sleep, strftime
logging
日志核心 API
Logger, Handler, Formatter
logging.config
日志配置
dictConfig, fileConfig
logging.handlers
日志处理器
RotatingFileHandler, SMTPHandler
platform
平台信息
system, release, machine
errno
错误码常量
ENOENT, EACCES, EEXIST
ctypes
调用 C 库
CDLL, POINTER, c_int

优缺点简单盘点
优点

缺点


总结:用好它,你就是Python老司鸡
Generic OS Services 看着乱,但用好了就是无敌。文件流、时间、日志、系统信息,甚至 C 库,一网打尽。别再在项目里到处抄代码、瞎造轮子了,善用这些标准库,代码既干净又高效。学会它们,你就从菜鸟迈向老司鸡,生产力直线上升!

赶紧动手试试,Pick 你最需要的模块,写写代码,马上就能感受到底层开挂的爽快!

原文链接:,转发请注明来源!