如何获取本地计算机当前使用的代码页?

How to get the codepage currently used in local computer?

在 Python 3.8 脚本中,我正在尝试检索当前在我的计算机中使用的代码页 (OS: Windows 10)。

使用sys.getdefaultencoding()将returnPython('utf-8')中使用的代码页,这与我的计算机使用的代码页不同。

我知道我可以通过从 Windows 控制台发送 chcp 命令来获取此信息:

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>

想知道 Python 库中是否有等效项,无需生成子进程、读取标准输出并解析结果字符串...

似乎 chcp 命令使用 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

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