Python的[System.Console] :: OutputEncoding / InputEncoding?

栏目: Python · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/39183614/how-system-consoleoutputencoding-inputencoding-with-python
在Powershell v5下,Windows 8.1, Python

3.为什么这些失败和如何解决?

[system.console]::InputEncoding = [System.Text.Encoding]::UTF8; 
[system.console]::OutputEncoding = [System.Text.Encoding]::UTF8; 
chcp; 
"import sys
print(sys.stdout.encoding)
print(sys.stdin.encoding)
sys.stdout.write(sys.stdin.readline())
" | 
sc test.py -Encoding utf8; 
[char]0x0422+[char]0x0415+[char]0x0421+[char]0x0422+"`n" | py -3 test.py

打印:

Active code page: 65001
cp65001
cp1251
п»ї????

您将数据管道传输到 Python 中在那个时候,Python的stdin不再附加到TTY(你的控制台),并且不会猜测编码可能是什么.而是使用默认的系统区域设置;在您的系统上,这是cp1251(基于Windows Latin 1的代码页).

PYTHONIOENCODING environment variable 设置为覆盖:

PYTHONIOENCODING
If this is set before running the interpreter, it overrides the encoding used for stdin/stdout/stderr, in the syntax encodingname:errorhandler . Both the encodingname and the :errorhandler parts are optional and have the same meaning as in str.encode() .

PowerShell似乎不支持UNIX命令行环境变量的方式;最简单的就是先设置变量:

Set-Item Env:PYTHONIOENCODING "UTF-8"

甚至

Set-Item Env:PYTHONIOENCODING "cp65001"

因为Windows UTF-8代码页显然不是很完美的UTF-8,这取决于Windows版本,而是使用更轻的或不重要的管道重定向.

代码日志版权声明:

翻译自:http://stackoverflow.com/questions/39183614/how-system-consoleoutputencoding-inputencoding-with-python


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

刘大猫的财富之旅

刘大猫的财富之旅

刘欣、刘大猫 / 新华出版社 / 2017-7-21 / 58.00元

作者刘大猫是一名90后的互联网连环创业者,26岁的他通过互联网创业收获到了财富,不仅仅是物质财富,还有认知的财富。 与其他创业类书籍不通的是,这本书非常真实,务实。书中没有任何大道理鸡汤,作者用平实的语言记录了创业以来遇到的种种事情,变化,困境,以及阶段性的成绩,记录了作者务实,鲜活的创业青春。一起来看看 《刘大猫的财富之旅》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具