【发布时间】:2013-08-18 02:59:49
【问题描述】:
我试过io、repr() 等,它们都不起作用!
输入å时出现问题(\xe5):
(这些都不起作用)
import sys
print(sys.stdin.read(1))
sys.stdin = io.TextIOWrapper(sys.stdin.detach(), errors='replace', encoding='iso-8859-1', newline='\n')
print(sys.stdin.read(1))
x = sys.stdin.buffer.read(1)
print(x.decode('utf-8'))
他们都给我大致UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe5 in position 0: unexpected end of data
还尝试使用以下命令启动 Python:export PYTHONIOENCODING=utf-8 也不起作用。
现在,这就是我所在的位置:
import sys, codecs
sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
sys.stdin = codecs.getwriter("utf-8")(sys.stdin.detach())
x = sys.stdin.read(1)
print(x.decode('utf-8', 'replace'))
这给了我:�
近了……
如何在我的控制台中将\xe5 转换为å?
如果它不破坏input(),因为这个解决方案破坏了它。
注意:我知道以前有人问过这个问题,但没有人能解决它.. 尤其是 io
我的系统的一些信息
os.environ['LANG'] == 'C'
sys.getdefaultencoding() == 'utf-8'
sys.stdout.encoding == 'ANSI_X3.4-1968'
sys.stdin.encoding == 'ANSI_X3.4-1968'
我的操作系统:ArchLinux 运行 xterm
运行locale -a 给我:C | POSIX | sv_SE.utf8
我已经关注了这些:
- Python 3: How to specify stdin encoding
- http://python-notes.curiousefficiency.org/en/latest/python3/binary_protocols.html
- http://wolfprojects.altervista.org/talks/unicode-and-python-3/
- http://getpython3.com/diveintopython3/strings.html
- Python 3 - Encode/Decode vs Bytes/Str
- How to set sys.stdout encoding in Python 3?
- http://docs.python.org/3.0/howto/unicode.html
(还有 50 多个)
解决方案(有点,仍然打破input())
sys.stdout = codecs.getwriter("latin-1")(sys.stdout.detach())
sys.stdin = codecs.getwriter("latin-1")(sys.stdin.detach())
x = sys.stdin.read(1)
print(x.decode('latin-1', 'replace'))
【问题讨论】:
-
您没有输入 UTF-8 数据;看起来像 Latin-1。
-
print sys.stdin.encoding告诉你 python 认为你的终端编解码器是什么? -
它是.. 我认为.. (iso-8859-1),但即使是“Latin-1”也给我带来了麻烦。那么如何解决呢?因为我整天都在为此烦恼,一整天都在文学上......(检查我的系统信息,在底部......它是
ANSI_X3 -
ANSI_X3.4-1968是 ASCII。基本上,请参阅en.wikipedia.org/wiki/ASCII#Aliases。这是相当古老的。这是什么平台? -
ArchLinux 在 xorg 下运行 xterm。
标签: python unicode character-encoding stdout python-3.3