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

Question:

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.

Asked By: AxeSkull

||

Answers:

import os
os.system('chcp 65001')

os.system lets you send any command to the operating system. So, running this is essentially the same as manually typing chcp 65001. See the docs for os.system for more information.

Answered By: jfhr

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)
Answered By: user3840170