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


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

查看所有标签

猜你喜欢:

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

这就是搜索引擎

这就是搜索引擎

张俊林 / 电子工业出版社 / 2012-1-1 / 45.00元

搜索引擎作为互联网发展中至关重要的一种应用,已经成为互联网各个领域的制高点,其重要性不言而喻。搜索引擎领域也是互联网应用中不多见的以核心技术作为其命脉的领域,搜索引擎各个子系统是如何设计的?这成为广大技术人员和搜索引擎优化人员密切关注的内容。 本书的最大特点是内容新颖全面而又通俗易懂。对于实际搜索引擎所涉及的各种核心技术都有全面细致的介绍,除了作为搜索系统核心的网络爬虫、索引系统、排序系统、......一起来看看 《这就是搜索引擎》 这本书的介绍吧!

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具