python - 在 Python 中,如何检查驱动器是否存在而不对可移动驱动器抛出错误?

标签 python windows error-handling path disk

这是我目前所拥有的:

import os.path as op
for d in map(chr, range(98, 123)): #drives b-z
    if not op.isdir(d + ':/'): continue

问题是在Windows中弹出“No Disk”错误框:

maya.exe - No Disk: There is no disk in the drive. Please insert a disk into drive \Device\Harddisk1\DR1 [Cancel, Try Again, Continue]

我无法捕获异常,因为它实际上并没有抛出 Python 错误。

显然,这只发生在分配了字母但未插入驱动器的可移动驱动器上。

有没有办法在不明确告诉脚本要跳过哪些驱动器的情况下解决这个问题?

在我的场景中,我在学校实验室,驱动器号根据我所在的实验室计算机而变化。此外,我访问磁盘管理的安全权限为零。

最佳答案

使用 ctypes包访问 GetLogicalDrives功能。这不需要诸如 pywin32 之类的外部库,因此它是可移植的,尽管使用起来有点笨拙。例如:

import ctypes
import itertools
import os
import string
import platform

def get_available_drives():
    if 'Windows' not in platform.system():
        return []
    drive_bitmask = ctypes.cdll.kernel32.GetLogicalDrives()
    return list(itertools.compress(string.ascii_uppercase,
               map(lambda x:ord(x) - ord('0'), bin(drive_bitmask)[:1:-1])))

itertools.compress 是在 Python 2.7 和 3.1 中添加的;如果您需要支持 <2.7 或 <3.1,这里是该功能的实现:

def compress(data, selectors):
    for d, s in zip(data, selectors):
        if s:
            yield d

关于python - 在 Python 中,如何检查驱动器是否存在而不对可移动驱动器抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4188326/

相关文章:

error-handling - 如何正确执行错误处理?

python - Pandas 数据帧 : apply function to all columns

python - 在 Windows 上用 Python 演示多核加速的一些示例代码是什么?

python - 如何覆盖二进制数据的 JSONEncoder 行为?

C++ 只有最后一次调用 SetConsoleCursorPosition() 有效

windows - 如何向我的 schtask 命令添加随机时间偏移量?

c++ - 如何使用 ShellExecute 在 Windows 中使用 C++ 打开 html 文件?

error-handling - 执行 strtol 后的错误处理

python - 如何从更深的目录中的文件导入模块?

error-handling - 为什么我不能把左大括号放在下一行?