我正试图使用python在windows中打开一个设备文件。我听说我需要使用win32 API。因此,我正在使用它,为了打开我的文件,我需要执行以下stackerflow问题:在Windows 上用Python打开设备的句柄
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不应返回零。它应该返回一个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()
代码引发一个异常,称为:
>>> 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.')
如果这没有帮助,请编辑您的问题,以显示您正在运行的精确代码以及运行该代码的精确结果。