You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac OS系统下如何使用Python仅列出可读写的存储卷?

macOS下Python实现枚举可读写存储卷方案

实现思路

macOS没有Linux的/proc文件系统,无法通过读取系统文件获取挂载信息,我们可以调用系统原生的diskutil工具获取所有存储卷的结构化属性,再按照规则过滤:

  • 保留挂载路径在/Volumes目录下的卷
  • 仅保留可读写属性为真的卷
  • 排除文件系统类型为cd9660的卷(CDROM、挂载的ISO镜像默认都是该文件系统类型)
  • 同Linux参考实现,默认包含当前用户的主目录

完整实现代码

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
import subprocess
import plistlib
from pathlib import Path
import getpass

def get_lst_writable_macos_disks():
    result = [str(Path.home())]
    # 调用diskutil获取所有卷的plist格式信息,方便结构化解析
    diskutil_output = subprocess.check_output(
        ["diskutil", "list", "-plist"],
        stderr=subprocess.DEVNULL
    )
    disk_info = plistlib.loads(diskutil_output)
    # 遍历所有存储卷
    for volume in disk_info.get("VolumesFromDisks", []):
        # 获取单个卷的详细属性
        vol_detail = plistlib.loads(
            subprocess.check_output(
                ["diskutil", "info", "-plist", volume],
                stderr=subprocess.DEVNULL
            )
        )
        # 过滤规则判断
        mount_point = vol_detail.get("MountPoint", "")
        if not mount_point.startswith("/Volumes/"):
            continue
        # 排除CD/ISO镜像
        if vol_detail.get("FilesystemType") == "cd9660":
            continue
        # 判断是否可读写
        if vol_detail.get("Writable", False):
            result.append(mount_point)
    return result

if __name__ == "__main__":
    print(get_lst_writable_macos_disks())

代码说明

  • 用diskutil的plist输出格式避免解析纯文本的兼容性问题,解析准确率更高
  • 自动过滤只读卷、CDROM、挂载的ISO镜像
  • 普通用户权限即可运行,无需sudo

内容的提问来源于stack exchange,提问作者Mrkalvin Bs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 22:24:05