1

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:\Users\Me>chcp
Active code page: 850

C:\Users\Me>

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

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Max1234-ITA
  • 147
  • 1
  • 1
  • 8

1 Answers1

4

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
Abdul Niyas P M
  • 18,035
  • 2
  • 25
  • 46
  • 1
    Nicely done; a heads-up for those running Python v3.8 and below: replace `removeprefix("Active code page: ")` with `.replace("Active code page: ", "")` to make the sample code work. – mklement0 May 06 '22 at 14:47