在 Python 中搜索 USB 返回 'there is no disk in drive'

Searching for a USB in Python is returning 'there is no disk in drive'

我在 Python 中编写了一个基于密钥标识符文件查找 USB 驱动器的函数,但是当调用它时 returns 'There is no disk in the drive. Please insert a disk into drive D:/'(这是一张 SD 卡reader) - 有没有办法让它根据 'ready'?

的驱动器搜索驱动器号
def FETCH_USBPATH():
    for USBPATH in ascii_uppercase:
        if os.path.exists('%s:\File.ID' % USBPATH):
            USBPATH='%s:\' % USBPATH
            print('USB is mounted to:', USBPATH)
            return USBPATH + ""
    return ""

USBdrive = FETCH_USBPATH()
while USBdrive == "":
    print('Please plug in USB & press any key to continue', end="")
    input()
    FlashDrive = FETCH_USBPATH()

在此处的 cmd 中进行了修复,但事实证明基于命令提示符不适合我的需要。

寻找 'ready' 个驱动器可能比满足您的需要更麻烦。您可以通过 SetThreadErrorMode.

暂时禁用错误消息对话框
import ctypes

kernel32 = ctypes.WinDLL('kernel32')

SEM_FAILCRITICALERRORS = 1
SEM_NOOPENFILEERRORBOX = 0x8000
SEM_FAIL = SEM_NOOPENFILEERRORBOX | SEM_FAILCRITICALERRORS

def FETCH_USBPATH():
    oldmode = ctypes.c_uint()
    kernel32.SetThreadErrorMode(SEM_FAIL, ctypes.byref(oldmode))
    try:
        for USBPATH in ascii_uppercase:
            if os.path.exists('%s:\File.ID' % USBPATH):
                USBPATH = '%s:\' % USBPATH
                print('USB is mounted to:', USBPATH)
                return USBPATH
        return ""
    finally:
        kernel32.SetThreadErrorMode(oldmode, ctypes.byref(oldmode))

USBdrive = FETCH_USBPATH()
while USBdrive == "":
    print('Please plug in our USB drive and '
          'press any key to continue...', end="")
    input()
    USBdrive = FETCH_USBPATH()