from ctypes import windll import locale import os import sys KERNEL32 = windll.kernel32 def tests(): print("ANSI CP: %s, OEM CP: %s" % (KERNEL32.GetACP(), KERNEL32.GetOEMCP())) print("GetConsoleCP: %s, GetConsoleOutputCP: %s" % (KERNEL32.GetConsoleCP(), KERNEL32.GetConsoleOutputCP())) print("device_encoding(0=stdin): %s, tty? %s" % (os.device_encoding(0), os.isatty(0))) print("device_encoding(1=stdout): %s, tty? %s" % (os.device_encoding(1), os.isatty(1))) print("device_encoding(2=stderr): %s, tty? %s" % (os.device_encoding(2), os.isatty(2))) print("sys encoding: stdin=%s, stdout=%s, stderr=%s" % (sys.stdin.encoding, sys.stdout.encoding, sys.stderr.encoding)) print("locale.getpreferredencoding(): %s" % (locale.getpreferredencoding())) cp = KERNEL32.GetConsoleOutputCP() encoding = "cp%s" % cp print("Use encoding %s" % encoding) chars = ('A', '\xE9', '\u0141', '\u20ac') print(ascii(sys.stdout)) print(ascii(sys.stdout.buffer)) print(ascii(sys.stderr)) print(ascii(sys.stderr.buffer)) print() for ch in chars: try: print('Write U+%04x as unicode: %s' % (ord(ch), ch)) except UnicodeEncodeError: print('Write U+%04x as unicode: ' % ord(ch)) except IOError: print('Write U+%04x as unicode: ' % ord(ch)) sys.stdout.flush() for ch in chars: try: data = ('Write U+%04x as bytes: %s' % (ord(ch), ch)).encode(encoding) except UnicodeEncodeError: data = ('Write U+%04x as bytes: ' % ord(ch)).encode(encoding) except IOError: print('Write U+%04x as unicode: ' % ord(ch)) sys.stdout.buffer.write(data + b'\r\n') sys.stdout.buffer.flush() sys.stdout.flush() def main(): old_console_cp = KERNEL32.GetConsoleCP() old_console_output_cp = KERNEL32.GetConsoleOutputCP() try: console_cp = console_output_cp = None #console_cp = 65001 #console_output_cp = 65001 if console_cp is not None: x = KERNEL32.SetConsoleCP(console_cp) if x!= 1: print("SetConsoleCP returned ", x ) exit( 1 ) if console_output_cp is not None: x = KERNEL32.SetConsoleOutputCP(console_output_cp) if x != 1: print("SetConsoleOutputCP returned ", x ) exit( 1 ) tests() finally: KERNEL32.SetConsoleCP(old_console_cp ) KERNEL32.SetConsoleOutputCP(old_console_output_cp ) if __name__ == "__main__": main()