开发者

What causes the print function to hang? What should I be using to safely print?

I just had a heap of trouble understanding what was happening while debugging a UnicodeDecodeError with print statements.

I was confusing myself with crazy th开发者_如何学JAVAeories but in the end the problem was just that printing a particular string hangs:

print '\xe6\x9c\xaa\xe5\x91\xbd\xe5\x90\x8d.jpg' 

What causes it to hang?

What should I be using instead to print to the console? print repr(x)?


It works ok on linux for me

Python 2.6.5 (r265:79063, Apr 16 2010, 13:09:56) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print '\xe6\x9c\xaa\xe5\x91\xbd\xe5\x90\x8d.jpg' 
未命名.jpg

What console are you using? perhaps it has a bug


That appears to be a UTF8 encoded string:

>>> '\xe6\x9c\xaa\xe5\x91\xbd\xe5\x90\x8d.jpg'.decode('utf8')
u'\u672a\u547d\u540d.jpg'

If your console can only handle ASCII, and not (say) UTF-8, it is crashing because there's no way to decode that series of bytes to an ASCII representable string:

>>> '\xe6\x9c\xaa\xe5\x91\xbd\xe5\x90\x8d.jpg'.decode('ascii')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 0: ordinal not in range(128)

You need to be using a console that supports UTF-8.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜