相关疑难解决方法(0)

在Python中管道stdout时设置正确的编码

管道Python程序的输出时,Python解释器会对编码感到困惑,并将其设置为None.这意味着这样的程序:

# -*- coding: utf-8 -*-
print u"åäö"
Run Code Online (Sandbox Code Playgroud)

正常运行时会正常工作,但失败时:

UnicodeEncodeError:'ascii'编解码器无法对位置0中的字符u'\ xa0'进行编码:序数不在范围内(128)

当在管道序列中使用时.

在配管时使这项工作的最佳方法是什么?我可以告诉它使用shell/filesystem /无论使用什么编码吗?

到目前为止我看到的建议是直接修改你的site.py,或者使用这个hack对defaultencoding进行硬编码:

# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
print u"åäö"
Run Code Online (Sandbox Code Playgroud)

是否有更好的方法使管道工作?

python terminal encoding stdout python-2.x

327
推荐指数
7
解决办法
19万
查看次数

python ...使用linux时的编码问题>

编码问题的简单测试程序:

#!/bin/env python
# -*- coding: utf-8 -*-
print u"Råbjerg"      # >>> unicodedata.name(u"å") = 'LATIN SMALL LETTER A WITH RING ABOVE'
Run Code Online (Sandbox Code Playgroud)

这是我从debian命令框中使用它时得到的,我不明白为什么在这里使用重定向打破了这个东西,因为我可以在没有使用时正确看到它.

有人可以帮助理解我错过了什么吗?什么应该以正确的方式打印这些角色,以便它们到处都可以?

$ python testu.py
Råbjerg

$ python testu.py > A
Traceback (most recent call last):
  File "testu.py", line 3, in <module>
    print u"Råbjerg"
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe5' in position 1: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

使用debian Debian GNU/Linux 6.0.7(squeeze)配置:

$ locale
LANG=fr_FR.UTF-8
LANGUAGE=
LC_CTYPE="fr_FR.UTF-8"
LC_NUMERIC="fr_FR.UTF-8"
LC_TIME="fr_FR.UTF-8"
LC_COLLATE="fr_FR.UTF-8"
LC_MONETARY="fr_FR.UTF-8"
LC_MESSAGES="fr_FR.UTF-8"
LC_PAPER="fr_FR.UTF-8"
LC_NAME="fr_FR.UTF-8"
LC_ADDRESS="fr_FR.UTF-8"
LC_TELEPHONE="fr_FR.UTF-8"
LC_MEASUREMENT="fr_FR.UTF-8"
LC_IDENTIFICATION="fr_FR.UTF-8"
LC_ALL= …
Run Code Online (Sandbox Code Playgroud)

python encoding utf-8

3
推荐指数
1
解决办法
3520
查看次数

管道输出导致python程序失败

我有以下简单的程序:

# -*- coding: utf-8 -*-

GREEK = u'???? ???? ???? ???? ???? ???? ???? ???? ???? ???? ???? ????'

print GREEK
Run Code Online (Sandbox Code Playgroud)

在终端上运行此产生,如下所示:

$ python test.py
???? ???? ???? ???? ???? ???? ???? ???? ???? ???? ???? ????
Run Code Online (Sandbox Code Playgroud)

但是将输出传递给另一个程序会导致错误:

$ python test.py | less

Traceback (most recent call last):
  File "test.py", line 5, in <module>
    print GREEK
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)
Traceback (most recent call last):
  File "ddd.py", line 5, in …
Run Code Online (Sandbox Code Playgroud)

python unicode terminal redirect terminal-emulator

2
推荐指数
1
解决办法
1313
查看次数