windows 如何获取插入计算机的可移动驱动器列表?

iovurdzv  于 2023-10-22  发布在  Windows
关注(0)|答案(2)|浏览(144)

我想得到一个插入计算机的可移动驱动程序的列表。
如何在Python中使用pywin32模块?
注意:重要的是,我将能够从固定驱动器分离的可移动驱动器。

xdnvmnnf

xdnvmnnf1#

算法很简单:

这是它在 Python 中的样子(使用 * PyWin 32 * Package 器)。将任何 *win32con.DRIVE_**常量添加到 drive_types 元组以获得不同的驱动器类型组合:

  • code00.py*:
  1. #!/usr/bin/env python
  2. import sys
  3. import win32con as wcon
  4. from win32api import GetLogicalDriveStrings
  5. from win32file import GetDriveType
  6. def get_drives_list(drive_types=(wcon.DRIVE_REMOVABLE,)):
  7. drives_str = GetLogicalDriveStrings()
  8. drives = (item for item in drives_str.split("\x00") if item)
  9. return [item[:2] for item in drives if not drive_types or GetDriveType(item) in drive_types]
  10. def main(*argv):
  11. drive_filters_examples = (
  12. (None, "All"),
  13. ((wcon.DRIVE_REMOVABLE,), "Removable"),
  14. ((wcon.DRIVE_FIXED, wcon.DRIVE_CDROM), "Fixed and CDROM"),
  15. )
  16. for drive_types_tuple, display_text in drive_filters_examples:
  17. drives = get_drives_list(drive_types=drive_types_tuple)
  18. print("{:s} drives:".format(display_text))
  19. for drive in drives:
  20. print("{:s} ".format(drive), end="")
  21. print("\n")
  22. if __name__ == "__main__":
  23. print("Python {:s} {:03d}bit on {:s}\n".format(" ".join(elem.strip() for elem in sys.version.split("\n")),
  24. 64 if sys.maxsize > 0x100000000 else 32, sys.platform))
  25. rc = main(*sys.argv[1:])
  26. print("\nDone.")
  27. sys.exit(rc)

输出

  1. [cfati@CFATI-5510-0:e:\Work\Dev\StackOverflow\q041465580]> "e:\Work\Dev\VEnvs\py_pc064_03.09_test0\Scripts\python.exe" ./code00.py
  2. Python 3.9.9 (tags/v3.9.9:ccb0e6a, Nov 15 2021, 18:08:50) [MSC v.1929 64 bit (AMD64)] 064bit on win32
  3. All drives:
  4. C: D: E: F: G: H: I: L: M: N:
  5. Removable drives:
  6. H: I:
  7. Fixed and CDROM drives:
  8. C: D: E: F: G: L: M: N:
  9. Done.

作为旁注,在我的环境中(在这一点上):

  • D: 是外部(USBHDD 上的分区
  • H:I: 是可引导 USB 记忆棒(UEFI)上的分区
  • 其余的是(内部)SSD 和/或 HDD 磁盘上的分区
展开查看全部
mznpcxlj

mznpcxlj2#

我自己也有类似的问题。隔离@CristiFati的答案,只有可移动驱动器,我拼凑了这个快速(非常简单)的功能,任何新的游客这个问题:
基本上,只需调用该函数,它将向调用者返回所有可移动驱动器list

  1. import win32api
  2. import win32con
  3. import win32file
  4. def get_removable_drives():
  5. drives = [i for i in win32api.GetLogicalDriveStrings().split('\x00') if i]
  6. rdrives = [d for d in drives if win32file.GetDriveType(d) == win32con.DRIVE_REMOVABLE]
  7. return rdrives

**例如:**调用get_removable_drives()将输出:

  1. ['E:\\']

相关问题