在 Mac OS 和 python 上如何仅列出可写卷?

On Mac OS with python how to list only writable volumes?

On Mac OS with python 如何只列出可写卷?换句话说,在 /Volumes 文件夹中我只想列出(分区和 pendrives)rw 我不想列出 CDROM 驱动器或安装的 ISO 映像。

在 linux 中有文件“/proc/mounts”,它显示已安装的驱动器以及分区类型和安装选项,在 mac OS 中有相似的东西? 在 linux 我这样使用它:

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

from pathlib import Path
import getpass

def get_lst_writable_linux_disks():
    this_user = getpass.getuser()

    lst_available_linux_disks = [str(Path.home())]
    with open('/proc/mounts','r') as f:
        data = f.readlines()

    for line in data:
        item = line.split(' ')
        mount_point = item[1]
        fs_type = item[2]
        options = item[3]
        if mount_point.startswith('/mnt') or (mount_point.startswith(f'/media/{this_user}') and fs_type != 'vfat' and 'rw' in options):
            lst_available_linux_disks.append(mount_point)

    return lst_available_linux_disks

print(get_lst_writable_linux_disks())

我如何在 Mac OS 上做同样的事情?

要获得比解析 diskutil info -all 的人类可读输出更可靠的方法,您可以这样做...(我不太喜欢 Apple 的 XML plist 格式; 你会认为有比简单的键-值-键-值-...结构更好的方式来表示字典...)

import subprocess
import xml.etree.ElementTree as ET
from typing import Tuple, List, Dict


def plist_dict_to_dict(node: ET.Element) -> Dict[str, ET.Element]:
    assert node.tag == "dict"
    dct = {}
    current_key = None
    for i, el in enumerate(node):
        if i % 2 == 0:
            assert el.tag == "key"
            current_key = el.text
        else:
            assert current_key
            dct[current_key] = el
    return dct


def get_volume_names() -> List[str]:
    command = ["/usr/sbin/diskutil", "list", "-plist"]
    volumes_xml = ET.fromstring(subprocess.check_output(command, encoding="utf-8"))
    volumes_info = plist_dict_to_dict(volumes_xml.find("dict"))
    vfd_array = volumes_info["VolumesFromDisks"]
    assert vfd_array.tag == "array"
    return [v.text for v in vfd_array.findall("string")]


def get_volume_info(volume_name: str) -> Dict[str, ET.Element]:
    command = ["/usr/sbin/diskutil", "info", "-plist", volume_name]
    vol_info_xml = ET.fromstring(subprocess.check_output(command, encoding="utf-8"))
    return plist_dict_to_dict(vol_info_xml.find("dict"))


def get_volume_flags(volume_name: str) -> Dict[str, bool]:
    vol_info = get_volume_info(volume_name)
    flags = {}
    for key, value in vol_info.items():
        if value.tag in ("true", "false"):
            flags[key] = value.tag == "true"
    return flags


if __name__ == "__main__":
    for volume_name in get_volume_names():
        print(volume_name, ":", get_volume_flags(volume_name))

在我的机器上,打印出来

Volume Macintosh HD : {'AESHardware': True, 'Bootable': True, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': True, 'FileVault': True, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': False, 'WritableMedia': True, 'WritableVolume': False}
Volume Macintosh HD - Data : {'AESHardware': True, 'Bootable': True, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': True, 'FileVault': True, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': True, 'WritableMedia': True, 'WritableVolume': True}
Volume Recovery : {'AESHardware': True, 'Bootable': False, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': False, 'FileVault': False, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': True, 'WritableMedia': True, 'WritableVolume': True}
Volume VM : {'AESHardware': True, 'Bootable': False, 'CanBeMadeBootable': False, 'CanBeMadeBootableRequiresDestroy': False, 'Ejectable': False, 'EjectableMediaAutomaticUnderSoftwareControl': False, 'EjectableOnly': False, 'Encryption': True, 'FileVault': False, 'Fusion': False, 'GlobalPermissionsEnabled': True, 'Internal': True, 'Locked': False, 'PartitionMapPartition': False, 'RAIDMaster': False, 'RAIDSlice': False, 'Removable': False, 'RemovableMedia': False, 'RemovableMediaOrExternalDevice': False, 'SolidState': True, 'SupportsGlobalPermissionsDisable': True, 'SystemImage': False, 'WholeDisk': False, 'Writable': True, 'WritableMedia': True, 'WritableVolume': True}

所以除了“可写”之外,您可能还想看看“内部”...