打印 unicode 字符串到控制台 OK 但重定向到文件时失败.怎么修? [英] Print unicode string to console OK but fails when redirect to a file. How to fix?
问题描述
我在简体中文版的 Windows XP 上有 Python 2.7.1,我有一个这样的程序(windows_prn_utf8.py):
I have Python 2.7.1 on a Simplified-Chinese version of Windows XP, and I have a program like this(windows_prn_utf8.py):
#!/usr/bin/env python
# -*- coding: utf8 -*-
print unicode('\xE7\x94\xB5', 'utf8')
如果我在Windows CMD控制台上运行它,它输出正确的汉字'电';但是,如果我尝试将命令输出重定向到文件.我出错了.
If I run it on Windows CMD console, it output the right Chinese character '电' ; however, if I try to redirect the command output to a file. I got error.
D:\Temp>windows_prn_utf8.py > 1.txt
Traceback (most recent call last):
File "D:\Temp\windows_prn_utf8.py", line 4, in <module>
print unicode('\xE7\x94\xB5', 'utf8')
UnicodeEncodeError: 'ascii' codec can't encode character u'\u7535' in position 0: ordinal not in range(128)
我意识到这里缺少一个链接.应该有办法判断,万一生成了1.txt,1.txt中的unicode字符应该是utf-8还是codepage-936或者其他编码.
I realize there is a missing link here. There should be a way to determine, in case 1.txt is generated, whether the unicode character in 1.txt should be encoded in utf-8 or codepage-936 or other encodings.
那怎么解决呢?我的偏好是在 1.txt 中使用 utf-8 编码.谢谢.
Then how to fix it? My preference is to have utf-8 encoding in 1.txt . Thank you.
推荐答案
设置 PYTHONIOENCODING
环境变量.
SET PYTHONIOENCODING=cp936
windows_prn_utf8.py > 1.txt
这篇关于打印 unicode 字符串到控制台 OK 但重定向到文件时失败.怎么修?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!