开发者

Strange python print behavior with unicode

开发者 https://www.devze.com 2023-03-27 06:50 出处:网络
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.

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 exceptio开发者_开发知识库n.


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

More Info can be found HERE:

0

精彩评论

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