pythonwindowswindows-consolecodepages

Is there a way to change the console code page from within Python?


When I type

chcp 65001

in the command prompt it changes the active code page. How do I accomplish the same thing from within Python itself? For example, every time I run my .py program, it should automatically change the code page to 65001.


Solution

  • The chcp command uses the SetConsoleCP and SetConsoleOutputCP Windows API calls to perform its job. You can invoke those calls directly via ctypes:

    import ctypes
    import ctypes.wintypes
    
    
    # helper
    def _errcheck_bool(retval, func, args):
        if retval:
            return
        raise ctypes.WinError()
    
    
    # define SetConsoleCP
    SetConsoleCP = ctypes.windll.kernel32.SetConsoleCP
    SetConsoleCP.argtypes = (ctypes.wintypes.UINT,)
    SetConsoleCP.restype = ctypes.wintypes.BOOL
    SetConsoleCP.errcheck = _errcheck_bool
    
    
    # define SetConsoleOutputCP
    SetConsoleOutputCP = ctypes.windll.kernel32.SetConsoleOutputCP
    SetConsoleOutputCP.argtypes = (ctypes.wintypes.UINT,)
    SetConsoleOutputCP.restype = ctypes.wintypes.BOOL
    SetConsoleOutputCP.errcheck = _errcheck_bool
    
    
    # invoke
    SetConsoleCP(65001)
    SetConsoleOutputCP(65001)