Python 如何获取本地计算机中当前使用的代码页?
在Python3.8脚本中,我试图检索当前在我的计算机(OS:Windows10)中使用的代码页 使用Python 如何获取本地计算机中当前使用的代码页?,python,codepages,Python,Codepages,在Python3.8脚本中,我试图检索当前在我的计算机(OS:Windows10)中使用的代码页 使用sys.getdefaultencoding()将返回Python中使用的代码页('utf-8'),这与我的计算机使用的代码页不同 我知道我可以通过从Windows控制台发送chcp命令来获取此信息: Microsoft Windows [Version 10.0.18363.1316] (c) 2019 Microsoft Corporation. All rights reserved.
sys.getdefaultencoding()
将返回Python中使用的代码页('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库中是否有一个等价物,而不需要生成子进程、读取stdout和解析结果字符串……似乎
chcp
命令在引擎盖下使用API来获取活动控制台代码页的编号。所以你可以通过使用
似乎
chcp
命令使用引擎盖下的API获取活动控制台代码页的编号。所以你可以通过使用
我试过了,似乎奏效了。非常感谢你@Max1234 ITA不客气:)我试过了,似乎有效。非常感谢你@Max1234 ITA欢迎您:)
>>> 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