【问题标题】:How to get the codepage currently used in local computer?如何获取本地计算机当前使用的代码页?
【发布时间】:2021-02-10 13:04:21
【问题描述】:

在 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 库中是否有等价物,无需生成子进程、读取标准输出和解析结果字符串...

【问题讨论】:

    标签: python codepages


    【解决方案1】:

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

    【讨论】:

    • 我试过了,似乎有效。非常感谢!
    猜你喜欢
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    • 2011-06-14
    • 2010-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    相关资源
    最近更新 更多