小编san*_*der的帖子

在 Windows 上将 python 输出重定向到文件会导致 UnicodeEncodeError

我正在尝试将 python 脚本的输出重定向到文件。当输出包含非 ascii 字符时,它可以在 macOS 和 Linux 上运行,但不能在 Windows 上运行。

\n\n

我已经将问题推导为一个简单的测试。以下是 Windows 命令提示符窗口中显示的内容。测试只是一次打印调用。

\n\n
Microsoft Windows [Version 10.0.17134.472]\n(c) 2018 Microsoft Corporation. All rights reserved.\n\nD:\\>set PY\nPYTHONIOENCODING=utf-8\n\nD:\\>type pipetest.py\nprint(\'\\u0422\\u0435\\u0441\\u0442\')\n\nD:\\>python pipetest.py\n\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\n\nD:\\>python pipetest.py > test.txt\n\nD:\\>type test.txt\n\xe2\x95\xa8\xc3\xb3\xe2\x95\xa8\xe2\x95\xa1\xe2\x95\xa4\xc3\xbc\xe2\x95\xa4\xc3\xa9\n\nD:\\>type test.txt | iconv -f utf-8 -t utf-8\n\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\n\nD:\\>set PYTHONIOENCODING=\n\nD:\\>python pipetest.py\n\xd0\xa2\xd0\xb5\xd1\x81\xd1\x82\n\nD:\\>python pipetest.py > test.txt\nTraceback (most recent call last):\n  File "pipetest.py", line 1, in <module>\n    print(\'\\u0422\\u0435\\u0441\\u0442\')\n  File "C:\\Python\\Python37\\lib\\encodings\\cp1252.py", line 19, in encode\n    return codecs.charmap_encode(input,self.errors,encoding_table)[0]\nUnicodeEncodeError: \'charmap\' codec can\'t encode characters in position 0-3: character maps to <undefined>\n\nD:\\>python -V\nPython 3.7.2\n
Run Code Online (Sandbox Code Playgroud)\n\n

正如人们所看到的,设置 …

python windows encoding

7
推荐指数
2
解决办法
1433
查看次数

标签 统计

encoding ×1

python ×1

windows ×1