The following code unexpectedly raises an exception:, pywintypes.error: (6, 'GetFileInformationByHandle', 'The handle is invalid.')i.e. GetFileInformationByHandledoes not work.
It is strange that everything works fine with the Python debugger . Even stranger is that when I delete some_parameteror GetFileInformationByHandle, the error disappears. This tells me that maybe this is some kind of memory error, but I'm really at a loss.
Some of the code may not be necessary, but I can no longer compress the code without causing an exception.
I tested this on Python 3.4.1 x64 on Windows 7, pywin32 218.5 and 219.
import os
import win32file
import pywintypes
from ctypes import *
from ctypes.wintypes import *
class BY_HANDLE_FILE_INFORMATION(Structure):
_fields_ = [
('dwFileAttributes', DWORD),
('ftCreationTime', FILETIME),
('ftLastAccessTime', FILETIME),
('ftLastWriteTime', FILETIME),
('dwVolumeSerialNumber', DWORD),
('nFileSizeHigh', DWORD),
('nFileSizeLow', DWORD),
('nNumberOfLinks', DWORD),
('nFileIndexHigh', DWORD),
('nFileIndexLow', DWORD),
]
def GetFileInformationByHandle2(handle):
GetFileInformationByHandle(handle)
def GetFileInformationByHandle(handle):
bhfi = BY_HANDLE_FILE_INFORMATION()
res = windll.kernelbase.GetFileInformationByHandle(handle.handle, byref(bhfi))
if res == 0:
errno = GetLastError()
raise pywintypes.error(errno, 'GetFileInformationByHandle', FormatError(errno))
def open_file(path, param_1=False):
return win32file.CreateFile(path, win32file.GENERIC_READ, 0, None, win32file.OPEN_EXISTING, 0, None)
def main():
path = 'test.bin'
open(path, 'wb').close()
h_file = open_file(path)
GetFileInformationByHandle(h_file)
win32file.CloseHandle(h_file)
h_file = open_file(path)
GetFileInformationByHandle2(h_file)
win32file.CloseHandle(h_file)
os.remove(path)
if __name__ == '__main__':
main()