1

如何检查 python 中是否存在原始(Windows)驱动器?即 "\\.\PhysicalDriveN" 其中 N 在磁盘号中

现在我可以通过打开并立即关闭它来检查原始驱动器是否存在(以管理员身份)。如果出现异常,则原始设备可能不存在,否则存在。我知道这不是很pythonic。有没有更好的办法?

os.access(drive_name, os.F_OK)总是返回False。与 相同os.path.exists(drive_name)。我宁愿只使用 python 标准库。os.stat(drive_name)也找不到设备。

我的工作代码示例:

drive_name = r"\\.\PhysicalDrive1"
try:
    open(drive_name).close()
except FileNotFoundError:
    print("The device does not exist")
else:
    print("The device exists")
4

2 回答 2

3

正如eryksun在评论中指出的那样,ctypes.windll.kernel32.QueryDosDeviceW可用于测试设备符号链接是否存在(PhysicalDrive1是指向实际设备位置的符号链接)。该ctypes模块允许人们通过动态链接库访问此 API 功能。

QueryDosDeviceW要求驱动器名称为字符串、字符数组和字符数组的长度。字符数组存储驱动器名称映射到的原始设备。该函数返回存储在字符数组中的字符数,如果驱动器不存在,则该字符数为零。

import ctypes
drive_name = "PhysicalDrive1"
target = (ctypes.c_wchar * 32768)(); # Creates an instance of a character array
target_len = ctypes.windll.kernel32.QueryDosDeviceW(drive_name, target, len(target))
if not target_len:
     print("The device does not exist")
else:
     print("The device exists")

target字符数组对象可能具有"\Device\Harddisk2\DR10"存储在其中的值

注意 在 python 3 中,字符串默认是 unicode,这就是QueryDosDeviceW(上图)起作用的原因。对于 Python 2,ctypes.windll.kernel32.QueryDosDeviceA将代替QueryDocDeviceW字节字符串工作。

于 2015-06-16T22:01:19.040 回答
0

无需导入 ctypes 等。

os.path.exists("C:")

工作正常。驱动程序参数应该有一个尾随“:”字符。

>>> os.path.exists("C:")
True
>>> os.path.exists("D:")
True
>>> os.path.exists("A:")
False
>>> os.path.exists("X:")
True  # i have mounted a local directory here
>>> os.path.exists("C")
False  # without trailing ":"
于 2020-11-04T07:45:32.340 回答