How to get the codepage currently used in local computer?

Question:

In a Python 3.8 script, I’m trying to retrieve the codepage which is currently used in my computer (OS: Windows 10).

Using sys.getdefaultencoding() will return the codepage used in Python (‘utf-8’), which is different from the one my computer uses.

I know I can get this information by sending the chcp command from a Windows Console:

Microsoft Windows [Version 10.0.18363.1316]
(c) 2019 Microsoft Corporation. All rights reserved.

C:UsersMe>chcp
Active code page: 850

C:UsersMe>

Wonder if there’s an equivalent in Python libraries, without need of spawning sub-processes, reading stdout and parsing the result string…

Asked By: Max1234-ITA

||

Answers:

Seems like chcp command uses GetConsoleOutputCP API under the hood to get the number of the active console code page. So you could get the same result by using windll.kernel32.GetConsoleOutputCP API.

>>> from ctypes import windll
>>> import subprocess
>>>
>>> def from_windows_api():
...     return windll.kernel32.GetConsoleOutputCP()
...
>>> def from_subprocess():
...     result = subprocess.getoutput("chcp")
...     return int(result.removeprefix("Active code page: "))
...
>>> from_windows_api() == from_subprocess()
True
Answered By: Abdul Niyas P M
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.