如何解决如何获取本地计算机当前使用的代码页?
在 Python 3.8 脚本中,我试图检索当前在我的计算机(操作系统:Windows 10)中使用的代码页。
使用 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 库中是否有等价物,无需生成子进程、读取标准输出和解析结果字符串...
解决方法
似乎 chcp
命令在幕后使用 GetConsoleOutputCP API 来获取活动控制台代码页的编号。因此,您可以通过使用 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。