Windows 设备文件没有 return 使用 python win32API 的有效句柄

Windows device file does not return valid handle with python win32API

我正在尝试使用 python 打开 windows 中的设备文件。我听说我需要使用 win32 API。所以我正在使用它,打开我的文件我需要执行以下这个 Whosebug 问题:Opening a handle to a device in Python on Windows

import win32file as w32
self.receiver_handle = w32.CreateFile("\\.\xillybus_read_32",  # file to open

w32.GENERIC_READ,  # desired access
w32.FILE_ATTRIBUTE_READONLY,  # shared mode
None,  # security attribute
w32.OPEN_EXISTING,  # creation distribution
w32.FILE_ATTRIBUTE_READONLY,  #flags and attributes
None)  # no template file

这导致句柄总是返回 0。 这是 API 参考:http://winapi.freetechsecrets.com/win32/WIN32CreateFile.htm

驱动附带了一个准系统的C程序来测试它并且它可以完美地工作,所以不可能是驱动本身没有正常工作。

我做错了什么?

API 不应该 return 零。它应该 return 一个 PyHANDLE 对象。我没有你的设备,但可以打开现有文件。第三个参数应该是 w32.FILE_SHARE_READ(或类似的共享模式值),但是:

>>> import win32file as w32
>>> w32.CreateFile('blah.txt',w32.GENERIC_READ,w32.FILE_SHARE_READ,None,w32.OPEN_EXISTING,w32.FILE_ATTRIBUTE_READONLY,None)
<PyHANDLE:280>

如果文件不存在(或任何其他错误),Python 应该根据 Win32 API 编写的 GetLastError() 代码引发异常 return叫:

>>> w32.CreateFile('blah.txt',w32.GENERIC_READ,w32.FILE_SHARE_READ,None,w32.OPEN_EXISTING,w32.FILE_ATTRIBUTE_READONLY,None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
pywintypes.error: (2, 'CreateFile', 'The system cannot find the file specified.')

如果这没有帮助,请编辑您的问题以显示您的 确切 代码 运行 和 确切 运行 代码的结果。