我可以将unicode输出从控制台直接重定向到文件吗? [英] Can I redirect unicode output from the console directly into a file?

查看:227
本文介绍了我可以将unicode输出从控制台直接重定向到文件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个python脚本输出unicode到控制台,我想重定向到一个文件。显然,python中的重定向过程涉及将输出转换为字符串,所以我得到关于无法解码unicode字符的错误。

I've got a python script that outputs unicode to the console, and I'd like to redirect it to a file. Apparently, the redirect process in python involves converting the output to a string, so I get errors about inability to decode unicode characters.

那么,有没有办法重定向到UTF-8编码的文件?

So then, is there any way to perform a redirect into a file encoded in UTF-8?

推荐答案

打印到控制台时,Python会查看 sys.stdout.encoding 确定在打印之前用于编码unicode对象的编码。

When printing to the console, Python looks at sys.stdout.encoding to determine the encoding to use to encode unicode objects before printing.

将输出重定向到文件时, sys.stdout.encoding 为None,因此Python2默认为< c $ c> ascii 编码。 (相比之下,Python3默认为 utf-8 。)这通常导致打印unicode时出现异常。

When redirecting output to a file, sys.stdout.encoding is None, so Python2 defaults to the ascii encoding. (In contrast, Python3 defaults to utf-8.) This often leads to an exception when printing unicode.

您可以在打印之前自己显式编码unicode,以避免错误:

You can avoid the error by explicitly encoding the unicode yourself before printing:

print (unicode_obj.encode('utf-8'))

或者您可以重新定义 sys.stdout 所以所有输出都编码在 utf-8

or you could redefine sys.stdout so all output is encoded in utf-8:

import sys
import codecs
sys.stdout=codecs.getwriter('utf-8')(sys.stdout)
print(unicode_obj)

这篇关于我可以将unicode输出从控制台直接重定向到文件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆