-->

Searching for a USB in Python is returning 'th

2019-09-09 22:50发布

问题:

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()