如何让UTF-8在Windows现代PowerShell中完美生效?
Windows下UTF-8输出异常问题
我有一个输出原生UTF-8的C++程序,在Linux上运行完全正常,但在Windows Shell中输出显示异常,比如“®”变成“┬«”,“©”变成“┬⌐”。代码里还有Python部分,它输出到Shell时表现更好,所以我针对Python输出做了测试:
PS C:\Users\user> python -c 'print("\N{GREEK CAPITAL LETTER DELTA}")' > test_file_python.txt Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\encodings\cp1252.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_table)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u0394' in position 0: character maps to <undefined> PS C:\Users\user> python -X utf8 -c 'print("\N{GREEK CAPITAL LETTER DELTA}")' > test_file_python.txt PS C:\Users\user> cat test_file_python.txt ╬ö PS C:\Users\user> python -c 'print("\N{GREEK CAPITAL LETTER DELTA}")' Δ PS C:\Users\user> cat .\test_file_python_wsl.txt # Generated in WSL with the above commands Δ PS C:\Users\user> Format-Hex .\test_file_python.txt Label: C:\Users\user\test_file_python.txt Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 E2 95 AC C3 B6 0D 0A â�¬Ã¶�� PS C:\Users\user> Format-Hex .\test_file_python_wsl.txt Label: C:\Users\user\test_file_python_wsl.txt Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 CE 94 0A Î��
我搞不懂PowerShell的编码工作机制:为什么Python输出到Shell时正常,但重定向到文件就出问题?为什么在WSL的Linux Bash里能完美运行的内容,到跨平台的PowerShell Core中就会出现这类问题?这些问题应该有通用的解决方案。
补充信息:我使用的是PowerShell Core v7.3.6,其编码设置如下:
PS C:\Users\user> $OutputEncoding Preamble : BodyName : utf-8 EncodingName : Unicode (UTF-8) HeaderName : utf-8 WebName : utf-8 WindowsCodePage : 1200 IsBrowserDisplay : True IsBrowserSave : True IsMailNewsDisplay : True IsMailNewsSave : True IsSingleByte : False EncoderFallback : System.Text.EncoderReplacementFallback DecoderFallback : System.Text.DecoderReplacementFallback IsReadOnly : True CodePage : 65001
内容的提问来源于stack exchange,提问作者cubanpit
相关产品推荐
相关产品推荐

