【问题标题】:On Mac OS with python how to list only writable volumes?在带有 python 的 Mac OS 上,如何仅列出可写卷?
【发布时间】:2021-12-12 19:31:20
【问题描述】:

在带有 python 的 Mac OS 上如何仅列出可写卷?换句话说,在 /Volumes 文件夹中,我只想列出(分区和 pendrive)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 上做同样的事情?

【问题讨论】:

标签: python macos mounted-volumes cd-rom


【解决方案1】:

对于比解析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}

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

【讨论】:

    猜你喜欢
    • 2011-03-27
    • 2011-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 2017-10-07
    • 2019-02-12
    • 2014-01-09
    • 1970-01-01
    相关资源
    最近更新 更多