psutil 磁盘分区:循环取值流程笔记

一、返回的数据长什么样 psutil.disk_partitions() 返回一个列表,列表里每个元素是一个具名元组 namedtuple: [ sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='D:\\', mountpoint='D:\\', fstype='NTFS', opts='rw,fixed'), sdiskpart(device='E:\\', mountpoint='E:\\', fstype='FAT32', opts='rw,removable'), sdiskpart(device='F:\\', mountpoint='F:\\', fstype='NTFS', opts='rw,fixed'), ] 外层 []:列表,装了 4 个分区 内层 sdiskpart(...):具名元组,本质是 tuple 子类,不是字典 二、完整代码 import psutil # 1. 查看磁盘的分区挂载情况 print("磁盘的分区挂载情况如下:") results = psutil.disk_partitions() print(results) for result in results: print(f"磁盘的设备路径是:{result[0]}, 磁盘的挂载点是:{result[1]}, 磁盘的文件系统是:{result[2]}") 三、循环流程逐步拆解 results = psutil.disk_partitions() 拿到外层列表,里面是 4 个 sdiskpart 元组。 for result in results: 第 1 次循环:result = 第 1 个元组(C 盘) 第 2 次循环:result = 第 2 个元组(D 盘) 第 3 次循环:result = 第 3 个元组(E 盘) 第 4 次循环:result = 第 4 个元组(F 盘) 每次循环内部取值 ...

November 21, 2026 · 1 分钟 · 150 字

Python 后台跑,日志文件一直是空的?搞懂 -u 和 flush=True

摘要:nohup python test.py & 跑起来了,ps 里能看到进程,可日志文件一直是 0 字节。等你按了 Ctrl+C,数据突然"哗"地全涌出来。这不是 bug,是 Python 的输出缓冲。本文讲清"终端行缓冲 vs 文件块缓冲"的差别,给出三种解法,并回答一个容易被忽略的问题:为什么 tree / 不加 -u 也像是实时的? 适合人群:Python 初学者 / 运维 / 任何用 nohup、systemd 跑过 Python 脚本的人 关键词:Python、缓冲、-u、flush、PYTHONUNBUFFERED、nohup、后台任务 一、现象:进程活着,日志是空的 nohup python test.py & ps -ef | grep test.py # 进程明明在跑 ls -l nohup.out # 0 字节 tail -f nohup.out # 什么都没有 脚本很简单: import time while True: print("test running!") time.sleep(1) 每秒打印一行,跑了半天,文件却是 0 字节。一按 Ctrl+C(或 kill 触发正常退出),日志瞬间涌出 134 行。 二、原理:两种缓冲模式 输出目标 缓冲方式 表现 终端(tty) 行缓冲 每行立刻可见 文件 / 管道 块缓冲(4~8KB) 攒满一整块才写盘,或进程退出时才写 你一旦 > file 或交给 nohup,stdout 就不再是终端 —— Python 立刻切换到块缓冲: ...

October 3, 2026 · 2 分钟 · 352 字
本站访客 · 访问量