可能重复:
Setting the correct encoding when piping stdout in python
以下在python shell(2.7.3)中按预期运行
for i in range(999):
print i, unichr(i)
将其保存在文件(asd.py)中,并在shell中运行
$ ./asd.py
也有效,但
$ ./asd.py > asd.txt
给出:
Traceback (most recent call last):
File "./asd.py", line 3, in <module>
print i, unichr(i)
UnicodeEncodeError: 'ascii' codec can't encode character u'\x80' in position 0: ordinal not in range(128)
为什么?如何解决它?
答案 0 :(得分:1)
试试这段代码,
#!/usr/bin/python
for i in range(999):
print i, unichr(i).encode('utf-8')