Search code examples
pythonwindowsdriver

Windows device file does not return valid handle with python win32API


I am trying to open a device file in windows using python. I heard I needed to use win32 API. So I am using that, to open my file I need to perform the following this stackoverflow question : 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

This results in the handle always returning 0. Here is the API reference: http://winapi.freetechsecrets.com/win32/WIN32CreateFile.htm

The driver came with a barebones C program to test it and it works flawlessly, so it can't be the driver itself that is not properly working.

What am I doing wrong?


Solution

  • The API should not return zero. It should return a PyHANDLE object. I don't have your device, but opening an existing file works. The 3rd parameter should be w32.FILE_SHARE_READ (or similar share mode value), however:

    >>> 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>
    

    If the file does not exist (or any other error), Python should raise an exception based on the GetLastError() code returned by the Win32 API called:

    >>> 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.')
    
    

    If this doesn't help, edit your question to show the exact code you are running and the exact results of running the code.