Search code examples
pythoncodepages

How to get the codepage currently used in local computer?


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...


Solution

  • chcp command uses GetConsoleOutputCP Windows API under the hood to get the number of active console code page. You could call the same function from python by using ctypes module(windll.kernel32.GetConsoleOutputCP).

    >>> 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