1

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.

Eryk Sun
  • 33,190
  • 5
  • 92
  • 111
AxeSkull
  • 33
  • 6
  • The console's support for UTF-8 (codepage 65001) is a mess in Windows 7, and even in Windows 10 it limits input to 7-bit ASCII (characters 0-127). Use the console's wide-character API instead. Python 3.6+ already does this for you. In Python 2, install and enable the win_unicode_console package. – Eryk Sun Apr 30 '19 at 04:56

2 Answers2

2

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)
user3840170
  • 26,597
  • 4
  • 30
  • 62
-1
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.

jfhr
  • 687
  • 5
  • 13
  • 1
    Hi! While this may answer the question (untested), it is SO best practice to include why this is a solution to OP's question. It helps OP better understand their problem and benefits future visitors to the site. Please consider adding an explanation to your answer. Thanks! --From Review – d_kennetz Apr 29 '19 at 15:42
  • Ok, I added an explanation. Thanks for the tip! – jfhr Apr 29 '19 at 15:57