def write(self, b): bytes_to_be_written = len(b) buffer = get_buffer(b) code_units_to_be_written = min(bytes_to_be_written, MAX_BYTES_WRITTEN) // 2 code_units_written = c_ulong() retval = WriteConsoleW(self.handle, buffer, code_units_to_be_written, byref(code_units_written), None) bytes_written = 2 * code_units_written.value # fixes both infinite loop of io.BufferedWriter.flush() on when the buffer has odd length # and situation when WriteConsoleW refuses to write lesser that MAX_BYTES_WRITTEN bytes if bytes_written == 0 != bytes_to_be_written: raise OSError(self._error_message(GetLastError())) else: return bytes_written
def readinto(self, b): bytes_to_be_read = len(b) if not bytes_to_be_read: return 0 elif bytes_to_be_read % 2: raise ValueError("cannot read odd number of bytes from UTF-16-LE encoded console") buffer = get_buffer(b, writable=True) code_units_to_be_read = bytes_to_be_read // 2 code_units_read = c_ulong() retval = ReadConsoleW(self.handle, buffer, code_units_to_be_read, byref(code_units_read), None) if GetLastError() == ERROR_OPERATION_ABORTED: time.sleep(0.1) # wait for KeyboardInterrupt if not retval: raise OSError("Windows error {}".format(GetLastError())) if buffer[0] == EOF: return 0 else: return 2 * code_units_read.value
def readinto(self, b): bytes_to_be_read = len(b) if not bytes_to_be_read: return 0 elif bytes_to_be_read % 2: raise ValueError( "cannot read odd number of bytes from UTF-16-LE encoded console" ) buffer = get_buffer(b, writable=True) code_units_to_be_read = bytes_to_be_read // 2 code_units_read = c_ulong() retval = ReadConsoleW(self.handle, buffer, code_units_to_be_read, byref(code_units_read), None) if GetLastError() == ERROR_OPERATION_ABORTED: time.sleep(0.1) # wait for KeyboardInterrupt if not retval: raise OSError("Windows error {}".format(GetLastError())) if buffer[0] == EOF: return 0 else: return 2 * code_units_read.value