gpt4 book ai didi

python - 如何检查 Python 中是否存在原始(未安装的)Windows 驱动器

转载 作者:可可西里 更新时间:2023-11-01 11:50:36 27 4
gpt4 key购买 nike

我如何检查 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")

最佳答案

作为eryksun评论中指出,ctypes.windll.kernel32.QueryDosDeviceW 可用于检测设备符号链接(symbolic link)是否存在(PhysicalDrive1 是指向实际设备位置的符号链接(symbolic link)).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 用于字节字符串。

关于python - 如何检查 Python 中是否存在原始(未安装的)Windows 驱动器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30856735/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com