【问题标题】:Windows cmd encoding change causes Python crashWindows cmd 编码更改导致 Python 崩溃
【发布时间】:2010-10-27 02:39:25
【问题描述】:

首先我将 Windows CMD 编码更改为 utf-8 并运行 Python 解释器:

chcp 65001
python

然后我尝试在其中打印一个 unicode 字符串,当我这样做时,Python 以一种特殊的方式崩溃(我只是在同一个窗口中得到一个 cmd 提示符)。

>>> import sys
>>> print u'ëèæîð'.encode(sys.stdin.encoding)

任何想法为什么会发生以及如何使其发挥作用?

UPDsys.stdin.encoding 返回'cp65001'

UPD2:我突然想到这个问题可能与 utf-8 使用 multi-byte character set 的事实有关(kcwu 对此提出了很好的意见)。我尝试使用“windows-1250”运行整个示例并得到“ëea”? Windows-1250 使用单字符集,因此它适用于它理解的那些字符。但是我仍然不知道如何让 'utf-8' 在这里工作。

UPD3:哦,我发现是known Python bug。我猜发生的情况是 Python 将 cmd 编码作为 'cp65001 复制到 sys.stdin.encoding 并尝试将其应用于所有输入。由于它无法理解“cp65001”,因此它会在任何包含非 ascii 字符的输入上崩溃。

【问题讨论】:

  • 你能打印 sys.stdin.encoding 吗?它返回什么?
  • python 很容易知道如何处理 'cp65001' 编解码器:必须在 Lib/encodings/aliases.py 中添加一行,将 'cp65001' 映射到 'utf_8'。我为此创建了一个补丁,并更新了你提到的错误,Alex。但仍然存在问题。

标签: python windows unicode encoding cmd


【解决方案1】:

从 Python 3.8+ 开始,编码 cp65001utf-8 的别名

https://docs.python.org/library/codecs.html#standard-encodings

【讨论】:

    【解决方案2】:

    该问题已在此线程中解决并解决:

    Change the system encoding

    解决方案是取消选择 Unicode UTF-8 以获得 Win 中的全球支持。这将需要重新启动,您的 Python 应该会恢复正常。

    胜利的步骤:

    1. 转到控制面板
    2. 选择时钟和区域
    3. 点击区域 > 行政
    4. 在非 Unicode 程序的语言中单击“更改系统区域设置”
    5. 在弹出的“区域设置”窗口中取消选中“测试版:使用 Unicode UTF-8...”
    6. 根据 Win 提示重启机器

    图片显示如何解决问题的确切位置:

    How to resolve the issue

    【讨论】:

    • 欢迎提供解决方案的链接,但请确保您的答案在没有它的情况下有用:add context around the link 这样您的其他用户就会知道它是什么以及为什么会出现,然后引用最相关的内容您链接到的页面的一部分,以防目标页面不可用。 Answers that are little more than a link may be deleted.
    • 不要发布仅链接到另一个答案的答案,而是将flag the question作为副本发布。
    • 谢谢@Zoe。我在回复中添加了更多信息,因为不幸的是,我目前的声誉不允许我将问题标记为重复。但肯定会记下未来。
    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 谢谢@罗伯特。我已经添加了详细信息,以防链接失效。尝试添加图片,但我的声誉再次不允许此功能。
    【解决方案3】:

    对于未知编码:cp65001 问题,可以将新的 Variable 设置为 PYTHONIOENCODING 并将 Value 设置为 UTF-8。 (这对我有用)

    查看这个:

    【讨论】:

      【解决方案4】:

      对我来说,在执行 python 程序之前设置这个环境变量:

      set PYTHONIOENCODING=utf-8
      

      【讨论】:

        【解决方案5】:

        设置PYTHONIOENCODING系统变量:

        > chcp 65001
        > set PYTHONIOENCODING=utf-8
        > python example.py
        Encoding is utf-8
        

        example.py的来源很简单:

        import sys
        print "Encoding is", sys.stdin.encoding
        

        【讨论】:

        • 我在 Python 2.7.5 中试过这个,而 sys.stdin.encodingsys.stdout.encoding 都说 utf-8 它没有生成正确的输出。它将输出的每个字节显示为单个字符,而不是将它们组合成代码点。
        • python -c "import sys; print('Encoding='+sys.stdin.encoding)" 而不是制作文件。
        • 这个在 Windows 7.0 x64 上对我有用。在我的例子中,编码是 720。
        • 我在 Windows 10 上运行 MobaSSH 服务器。我通过 SSH 登录远程在该服务器上工作。当我使用随 Windows 10 VM 一起安装的 OpenSSHv6.7 时,Python 根本不起作用。如果我使用 MobaSSH 服务器,效果会更好,但是 Python 给出了这个错误
        • 虽然,OP 没有提到这个特定的错误,我也没有找到其他任何人发现这个错误的地方,我确实遇到了这个。完成上述步骤后,问题就解决了。
        【解决方案6】:

        以下是如何在不更改 encodings\aliases.py 的情况下将 cp65001 别名为 UTF-8:

        import codecs
        codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
        

        (恕我直言,不要在意 cp65001http://bugs.python.org/issue6058#msg97731 上的 UTF-8 不同的愚蠢之处。即使微软的编解码器有一些小错误,它也是一样的。)

        这里有一些代码(为 Tahoe-LAFS,tahoe-lafs.org 编写)使控制台输出工作不管 chcp 代码页,并且还读取 Unicode 命令行参数。感谢 Michael Kaplan 提供此解决方案背后的想法。如果 stdout 或 stderr 被重定向,它将输出 UTF-8。如果你想要一个字节顺序标记,你需要明确地写出来。

        [编辑:此版本在 MSVC 运行时库中使用 WriteConsoleW 而不是 _O_U8TEXT 标志,这是错误的。 WriteConsoleW 相对于 MS 文档也有问题,但更少。]

        import sys
        if sys.platform == "win32":
            import codecs
            from ctypes import WINFUNCTYPE, windll, POINTER, byref, c_int
            from ctypes.wintypes import BOOL, HANDLE, DWORD, LPWSTR, LPCWSTR, LPVOID
        
            original_stderr = sys.stderr
        
            # If any exception occurs in this code, we'll probably try to print it on stderr,
            # which makes for frustrating debugging if stderr is directed to our wrapper.
            # So be paranoid about catching errors and reporting them to original_stderr,
            # so that we can at least see them.
            def _complain(message):
                print >>original_stderr, message if isinstance(message, str) else repr(message)
        
            # Work around <http://bugs.python.org/issue6058>.
            codecs.register(lambda name: codecs.lookup('utf-8') if name == 'cp65001' else None)
        
            # Make Unicode console output work independently of the current code page.
            # This also fixes <http://bugs.python.org/issue1602>.
            # Credit to Michael Kaplan <http://www.siao2.com/2010/04/07/9989346.aspx>
            # and TZOmegaTZIOY
            # <http://stackoverflow.com/questions/878972/windows-cmd-encoding-change-causes-python-crash/1432462#1432462>.
            try:
                # <http://msdn.microsoft.com/en-us/library/ms683231(VS.85).aspx>
                # HANDLE WINAPI GetStdHandle(DWORD nStdHandle);
                # returns INVALID_HANDLE_VALUE, NULL, or a valid handle
                #
                # <http://msdn.microsoft.com/en-us/library/aa364960(VS.85).aspx>
                # DWORD WINAPI GetFileType(DWORD hFile);
                #
                # <http://msdn.microsoft.com/en-us/library/ms683167(VS.85).aspx>
                # BOOL WINAPI GetConsoleMode(HANDLE hConsole, LPDWORD lpMode);
        
                GetStdHandle = WINFUNCTYPE(HANDLE, DWORD)(("GetStdHandle", windll.kernel32))
                STD_OUTPUT_HANDLE = DWORD(-11)
                STD_ERROR_HANDLE = DWORD(-12)
                GetFileType = WINFUNCTYPE(DWORD, DWORD)(("GetFileType", windll.kernel32))
                FILE_TYPE_CHAR = 0x0002
                FILE_TYPE_REMOTE = 0x8000
                GetConsoleMode = WINFUNCTYPE(BOOL, HANDLE, POINTER(DWORD))(("GetConsoleMode", windll.kernel32))
                INVALID_HANDLE_VALUE = DWORD(-1).value
        
                def not_a_console(handle):
                    if handle == INVALID_HANDLE_VALUE or handle is None:
                        return True
                    return ((GetFileType(handle) & ~FILE_TYPE_REMOTE) != FILE_TYPE_CHAR
                            or GetConsoleMode(handle, byref(DWORD())) == 0)
        
                old_stdout_fileno = None
                old_stderr_fileno = None
                if hasattr(sys.stdout, 'fileno'):
                    old_stdout_fileno = sys.stdout.fileno()
                if hasattr(sys.stderr, 'fileno'):
                    old_stderr_fileno = sys.stderr.fileno()
        
                STDOUT_FILENO = 1
                STDERR_FILENO = 2
                real_stdout = (old_stdout_fileno == STDOUT_FILENO)
                real_stderr = (old_stderr_fileno == STDERR_FILENO)
        
                if real_stdout:
                    hStdout = GetStdHandle(STD_OUTPUT_HANDLE)
                    if not_a_console(hStdout):
                        real_stdout = False
        
                if real_stderr:
                    hStderr = GetStdHandle(STD_ERROR_HANDLE)
                    if not_a_console(hStderr):
                        real_stderr = False
        
                if real_stdout or real_stderr:
                    # BOOL WINAPI WriteConsoleW(HANDLE hOutput, LPWSTR lpBuffer, DWORD nChars,
                    #                           LPDWORD lpCharsWritten, LPVOID lpReserved);
        
                    WriteConsoleW = WINFUNCTYPE(BOOL, HANDLE, LPWSTR, DWORD, POINTER(DWORD), LPVOID)(("WriteConsoleW", windll.kernel32))
        
                    class UnicodeOutput:
                        def __init__(self, hConsole, stream, fileno, name):
                            self._hConsole = hConsole
                            self._stream = stream
                            self._fileno = fileno
                            self.closed = False
                            self.softspace = False
                            self.mode = 'w'
                            self.encoding = 'utf-8'
                            self.name = name
                            self.flush()
        
                        def isatty(self):
                            return False
        
                        def close(self):
                            # don't really close the handle, that would only cause problems
                            self.closed = True
        
                        def fileno(self):
                            return self._fileno
        
                        def flush(self):
                            if self._hConsole is None:
                                try:
                                    self._stream.flush()
                                except Exception as e:
                                    _complain("%s.flush: %r from %r" % (self.name, e, self._stream))
                                    raise
        
                        def write(self, text):
                            try:
                                if self._hConsole is None:
                                    if isinstance(text, unicode):
                                        text = text.encode('utf-8')
                                    self._stream.write(text)
                                else:
                                    if not isinstance(text, unicode):
                                        text = str(text).decode('utf-8')
                                    remaining = len(text)
                                    while remaining:
                                        n = DWORD(0)
                                        # There is a shorter-than-documented limitation on the
                                        # length of the string passed to WriteConsoleW (see
                                        # <http://tahoe-lafs.org/trac/tahoe-lafs/ticket/1232>.
                                        retval = WriteConsoleW(self._hConsole, text, min(remaining, 10000), byref(n), None)
                                        if retval == 0 or n.value == 0:
                                            raise IOError("WriteConsoleW returned %r, n.value = %r" % (retval, n.value))
                                        remaining -= n.value
                                        if not remaining:
                                            break
                                        text = text[n.value:]
                            except Exception as e:
                                _complain("%s.write: %r" % (self.name, e))
                                raise
        
                        def writelines(self, lines):
                            try:
                                for line in lines:
                                    self.write(line)
                            except Exception as e:
                                _complain("%s.writelines: %r" % (self.name, e))
                                raise
        
                    if real_stdout:
                        sys.stdout = UnicodeOutput(hStdout, None, STDOUT_FILENO, '<Unicode console stdout>')
                    else:
                        sys.stdout = UnicodeOutput(None, sys.stdout, old_stdout_fileno, '<Unicode redirected stdout>')
        
                    if real_stderr:
                        sys.stderr = UnicodeOutput(hStderr, None, STDERR_FILENO, '<Unicode console stderr>')
                    else:
                        sys.stderr = UnicodeOutput(None, sys.stderr, old_stderr_fileno, '<Unicode redirected stderr>')
            except Exception as e:
                _complain("exception %r while fixing up sys.stdout and sys.stderr" % (e,))
        
        
            # While we're at it, let's unmangle the command-line arguments:
        
            # This works around <http://bugs.python.org/issue2128>.
            GetCommandLineW = WINFUNCTYPE(LPWSTR)(("GetCommandLineW", windll.kernel32))
            CommandLineToArgvW = WINFUNCTYPE(POINTER(LPWSTR), LPCWSTR, POINTER(c_int))(("CommandLineToArgvW", windll.shell32))
        
            argc = c_int(0)
            argv_unicode = CommandLineToArgvW(GetCommandLineW(), byref(argc))
        
            argv = [argv_unicode[i].encode('utf-8') for i in xrange(0, argc.value)]
        
            if not hasattr(sys, 'frozen'):
                # If this is an executable produced by py2exe or bbfreeze, then it will
                # have been invoked directly. Otherwise, unicode_argv[0] is the Python
                # interpreter, so skip that.
                argv = argv[1:]
        
                # Also skip option arguments to the Python interpreter.
                while len(argv) > 0:
                    arg = argv[0]
                    if not arg.startswith(u"-") or arg == u"-":
                        break
                    argv = argv[1:]
                    if arg == u'-m':
                        # sys.argv[0] should really be the absolute path of the module source,
                        # but never mind
                        break
                    if arg == u'-c':
                        argv[0] = u'-c'
                        break
        
            # if you like:
            sys.argv = argv
        

        最后,可以满足 ΤZΩΤZΙΟΥ 使用 DejaVu Sans Mono 的愿望,我同意这是一种出色的字体,用于控制台。

        您可以在'Necessary criteria for fonts to be available in a command window' Microsoft KB 中找到有关字体要求以及如何为 Windows 控制台添加新字体的信息

        但基本上,在 Vista 上(可能还有 Win7):

        • HKEY_LOCAL_MACHINE_SOFTWARE\Microsoft\Windows NT\CurrentVersion\Console\TrueTypeFont下,将"0"设置为"DejaVu Sans Mono"
        • 对于HKEY_CURRENT_USER\Console 下的每个子项,将"FaceName" 设置为"DejaVu Sans Mono"

        在 XP 上,检查线程 'Changing Command Prompt fonts?' in LockerGnome forums

        【讨论】:

        • +1,因为您的回答是值得的,加上字体问题建议的虚拟 +1,即使为时已晚(我和 Windows 因多次争吵而分手;我没有如果不是在朋友的电脑上短暂相遇,我们不会再在一起了 :) 谢谢。
        • @David-Sarah:感谢您提供非常有用的代码!您是否碰巧知道是否有相应的方法来修复控制台 input(以便例如复制粘贴的 unicode 字符 Just Work,无论代码页等)这可能涉及 ReadConsoleW?
        • 我尝试在我的项目github.com/Drekin/win-unicode-console 中解决有关 Python 3 的 bugs.python.org/issue1602 的问题。包在 PyPI 上:pypi.python.org/pypi/win_unicode_console。它实际上是基于问题中的代码构建的,该问题源于您的代码。
        • @KevinThibedeau:使用 colorama 包。
        • @KevinThibedeau:我不知道为什么 cp65001 很重要。另一方面,没有必要使用cp65001。
        【解决方案7】:

        我也遇到了这个烦人的问题,我讨厌无法在 MS Windows 中像在 linux 中一样运行我的 unicode 感知脚本。所以,我设法想出了一个解决方法。

        获取此脚本(例如,您的站点包中的uniconsole.py 或其他):

        import sys, os
        
        if sys.platform == "win32":
            class UniStream(object):
                __slots__= ("fileno", "softspace",)
        
                def __init__(self, fileobject):
                    self.fileno = fileobject.fileno()
                    self.softspace = False
        
                def write(self, text):
                    os.write(self.fileno, text.encode("utf_8") if isinstance(text, unicode) else text)
        
            sys.stdout = UniStream(sys.stdout)
            sys.stderr = UniStream(sys.stderr)
        

        这似乎可以解决 python 错误(或 win32 unicode 控制台错误等)。然后我在所有相关脚本中添加:

        try:
            import uniconsole
        except ImportError:
            sys.exc_clear()  # could be just pass, of course
        else:
            del uniconsole  # reduce pollution, not needed anymore
        

        最后,我只是根据需要在运行chcp 65001 且字体为Lucida Console 的控制台中运行我的脚本。 (我多么希望可以使用 DejaVu Sans Mono 来代替……但是破解注册表并将其选择为控制台字体会恢复为位图字体。)

        这是一个快速而肮脏的stdoutstderr 替换,也不会处理任何与raw_input 相关的错误(显然,因为它根本不涉及sys.stdin)。顺便说一句,我在标准库的encodings\aliases.py 文件中为utf_8 添加了cp65001 别名。

        【讨论】:

        • 这是完美的工作!另外,在类中至少添加一个空的def flush(self): pass,使其与stderr/stdout 兼容(可能缺少更多方法,但Twisted 只抱怨缺少.flush())。
        • 在使用了你的 sn-p 之后,看起来 David-Sarah Hopwood 的 sn-p 更通用。
        • _DebuggerOutput 没有属性fileno
        【解决方案8】:

        您希望 Python 编码为 UTF-8 吗?

        >>>print u'ëèæîð'.encode('utf-8')
        ëèæîð
        

        Python 不会将 cp65001 识别为 UTF-8。

        【讨论】:

          【解决方案9】:

          一些 cmets:您可能拼错了 encodig.code。这是我运行的示例。

          C:\>chcp 65001
          Active code page: 65001
          
          C:\>\python25\python
          ...
          >>> import sys
          >>> sys.stdin.encoding
          'cp65001'
          >>> s=u'\u0065\u0066'
          >>> s
          u'ef'
          >>> s.encode(sys.stdin.encoding)
          Traceback (most recent call last):
            File "<stdin>", line 1, in <module>
          LookupError: unknown encoding: cp65001
          >>>
          

          结论 - cp65001 不是 Python 的已知编码。试试 'UTF-16' 或类似的东西。

          【讨论】:

          • 是的,我确实拼错了,但我尝试了正确的方法,同样的崩溃(这实际上证明解释器实际上并没有评估拼写错误的 'encode()' 和 'encoding ()' 属性并在处理 'ëèæîð' 时崩溃。我修正了错字。
          【解决方案10】:

          这是因为 cmd 的 "code page" 与 system 的 "mbcs" 不同。虽然你改变了“代码页”,但python(实际上是windows)仍然认为你的“mbcs”没有改变。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-08-04
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-05-17
            相关资源
            最近更新 更多