unicode奇怪的python打印行为 [英] Strange python print behavior with unicode

查看:65
本文介绍了unicode奇怪的python打印行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么可以使用print在OSX Terminal.app中打印unicode字符串,但是如果我将stdout重定向到文件或通过管道将其传输到更多",则会收到UnicodeEncodeError. python如何确定是打印unicode还是引发异常.

I am wondering why i can use print to print a unicode string in my OSX Terminal.app, but if i redirect stdout to a file or pipe it to 'more', i get an UnicodeEncodeError. How does python decides whether it prints unicode or throws an exception.

推荐答案

因为您的终端编码设置正确,并且当您重定向到文件(或管道)时,该编码设置为默认编码(python2中为ASCII).在两次print sys.stdout.encoding时(当您以stdout作为终端运行脚本时,以及重定向到文件时),都将看到差异.

Because your terminal encoding is set correctly and when you redirect to a file (or pipe) the encoding is set to the default encoding (ASCII in python2.) try print sys.stdout.encoding in both time (when you run your script as the terminal as stdout and when you redirect to a file) and you will see the difference.

也可以在命令行中尝试此操作:

Try also this in your command line:

$ python -c 'import sys; print sys.stdout.encoding;'
UTF8
$ python -c 'import sys; print sys.stdout.encoding;' | cat
None

可以找到更多信息此处:

这篇关于unicode奇怪的python打印行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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