1

我有一个 Python 脚本,它设计为从 USB 闪存驱动器运行,如果从 PC 硬盘驱动器运行,则无法运行,因此可以安全地假设所有副本都存在于连接的 USB 上。

我有另一个脚本设计为从计算机硬盘驱动器上运行,它寻找这些 USB 脚本并以某种方式配置它们。显然,为了节省时间,当我知道它们仅在 USB 上时,我不想搜索整个硬盘驱动器。有没有办法只搜索连接的 USB 上的文件,跳过搜索本地驱动器,通过检查驱动器号等?

4

2 回答 2

3

这是一些示例代码,用于确定 Windows 上每个活动逻辑驱动器的驱动器类型,使用ctypes...

import ctypes

# Drive types
DRIVE_UNKNOWN     = 0  # The drive type cannot be determined.
DRIVE_NO_ROOT_DIR = 1  # The root path is invalid; for example, there is no volume mounted at the specified path.
DRIVE_REMOVABLE   = 2  # The drive has removable media; for example, a floppy drive, thumb drive, or flash card reader.
DRIVE_FIXED       = 3  # The drive has fixed media; for example, a hard disk drive or flash drive.
DRIVE_REMOTE      = 4  # The drive is a remote (network) drive.
DRIVE_CDROM       = 5  # The drive is a CD-ROM drive.
DRIVE_RAMDISK     = 6  # The drive is a RAM disk.

# Map drive types to strings
DRIVE_TYPE_MAP = { DRIVE_UNKNOWN     : 'DRIVE_UNKNOWN',
                   DRIVE_NO_ROOT_DIR : 'DRIVE_NO_ROOT_DIR',
                   DRIVE_REMOVABLE   : 'DRIVE_REMOVABLE',
                   DRIVE_FIXED       : 'DRIVE_FIXED',
                   DRIVE_REMOTE      : 'DRIVE_REMOTE',
                   DRIVE_CDROM       : 'DRIVE_CDROM',
                   DRIVE_RAMDISK     : 'DRIVE_RAMDISK'}


# Return list of tuples mapping drive letters to drive types
def get_drive_info():
    result = []
    bitmask = ctypes.windll.kernel32.GetLogicalDrives()
    for i in range(26):
        bit = 2 ** i
        if bit & bitmask:
            drive_letter = '%s:' % chr(65 + i)
            drive_type = ctypes.windll.kernel32.GetDriveTypeA('%s\\' % drive_letter)
            result.append((drive_letter, drive_type))
    return result


# Test
if __name__ == '__main__':
    drive_info = get_drive_info()
    for drive_letter, drive_type in drive_info:
        print '%s = %s' % (drive_letter, DRIVE_TYPE_MAP[drive_type])
    removable_drives = [drive_letter for drive_letter, drive_type in drive_info if drive_type == DRIVE_REMOVABLE]
    print 'removable_drives = %r' % removable_drives

...打印...

C: = DRIVE_FIXED
D: = DRIVE_FIXED
E: = DRIVE_CDROM
removable_drives = []

...在插入 U 盘之前...

C: = DRIVE_FIXED
D: = DRIVE_FIXED
E: = DRIVE_CDROM
F: = DRIVE_REMOVABLE
removable_drives = ['F:']

...然后。

获得可移动驱动器列表后,您可以简单地os.walk()在每个驱动器上使用。

于 2013-06-10T18:51:29.673 回答
0

我想你可以在这篇文章中找到答案

他使用 pyUsb 来操作 USB 文件。希望这会有所帮助。

于 2013-06-10T16:58:19.110 回答