在Python中搜索USB正在返回'驱动器中没有磁盘'

时间:2015-03-15 10:03:53

标签: python windows os.path

我在Python中编写了一个函数,它根据密钥标识符文件查找USB驱动器,但是在调用它时会返回“驱动器中没有磁盘”。请将磁盘插入驱动器D:/'(这是一个SD卡读卡器) - 有没有办法让它根据“准备好”的驱动器搜索驱动器号?

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中有一个修复,但是基于命令提示符不符合我的需要。

1 个答案:

答案 0 :(得分:3)

找到准备好的'驱动器可能更麻烦,它值得满足您的需求。您可以通过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()