Linux / Python:编码用于打印的unicode字符串 [英] Linux/Python: encoding a unicode string for print

查看:426
本文介绍了Linux / Python:编码用于打印的unicode字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个相当大的python 2.6应用程序,大量的打印语句都是撒谎的。我正在使用unicode字符串,它通常工作很好。但是,如果我重定向应用程序的输出(如myapp.py> output.txt),那么我偶尔会收到如下错误:

 UnicodeEncodeError:'ascii'编解码器不能将字符u'\xa1'编码在位置0:序号不在范围内(128)

如果有人将其LOCALE设置为ASCII,我猜想同样的问题。现在,我完全理解这个错误的原因。我的Unicode字符串中有字符不能用ASCII编码。很公平。但是,我希望我的python程序尽力尝试打印一些可以理解的东西,也许跳过可疑字符,或者使用它们的Unicode ids代替它们。



此问题必须是常见的...处理此问题的最佳做法是什么?我更喜欢一个解决方案,允许我继续使用普通旧的打印,但是如果需要,我可以修改所有的事件。



PS:我现在解决了这个问题。解决方案既不是给出的答案。我使用了 http://wiki.python.org/moin/PrintFails 中给出的方法,作为由ChrisJ在其中一个评论中给出。也就是说,我用一个包装器替换sys.stdout,它使用正确的参数调用unicode编码。工作得很好。

解决方案

我现在已经解决了这个问题。解决方案既不是答案。我使用了 http://wiki.python.org/moin/PrintFails 中给出的方法,作为由ChrisJ在其中一个评论中给出。也就是说,我用一个包装器替换sys.stdout,它使用正确的参数调用unicode编码。工作得很好。


I have a fairly large python 2.6 application with lots of print statements sprinkled about. I'm using unicode strings throughout, and it usually works great. However, if I redirect the output of the application (like "myapp.py >output.txt"), then I occasionally get errors such as this:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa1' in position 0: ordinal not in range(128)

I guess the same issue comes up if someone has set their LOCALE to ASCII. Now, I understand perfectly well the reason for this error. There are characters in my Unicode strings that are not possible to encode in ASCII. Fair enough. But I'd like my python program to make a best effort to try to print something understandable, maybe skipping the suspicious characters or replacing them with their Unicode ids.

This problem must be common... What is the best practice for handling this problem? I'd prefer a solution that allows me to keep using plain old "print", but I can modify all occurrences if necessary.

PS: I have now solved this problem. The solution was neither of the answers given. I used the method given at http://wiki.python.org/moin/PrintFails , as given by ChrisJ in one of the comments. That is, I replace sys.stdout with a wrapper that calls unicode encode with the correct arguments. Works very well.

解决方案

I have now solved this problem. The solution was neither of the answers given. I used the method given at http://wiki.python.org/moin/PrintFails , as given by ChrisJ in one of the comments. That is, I replace sys.stdout with a wrapper that calls unicode encode with the correct arguments. Works very well.

这篇关于Linux / Python:编码用于打印的unicode字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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