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

心不动则不痛 提交于 2019-12-25 14:04:33

问题


I wrote up a function in Python that looks for a USB drive based on a key identifier file, however when called upon it returns 'There is no disk in the drive. Please insert a disk into drive D:/' (which is an SD card reader) - is there a way to have it search drive letters based on drives that are '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()

Had a fix in cmd here however turned out command-prompt based didn't suit my needs.


回答1:


Finding 'ready' drives may be more trouble that it's worth for your needs. You can probably get away with just temporarily disabling the error message dialog box via 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()


来源:https://stackoverflow.com/questions/29059399/searching-for-a-usb-in-python-is-returning-there-is-no-disk-in-drive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!