code_junkie

Setting the correct encoding when piping stdout in python

Nov 13th, 2011
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. print "åäö"
  3.  
  4. UnicodeEncodeError: 'ascii' codec can't encode character u'xa0' in position 0: ordinal not in range(128)
  5.  
  6. # -*- coding: utf-8 -*-
  7. import sys
  8. reload(sys)
  9. sys.setdefaultencoding('utf-8')
  10. print "åäö"
  11.  
  12. # -*- coding: utf-8 -*-
  13. print u"åäö".encode('utf-8')
  14.  
  15. import sys
  16. for line in sys.stdin:
  17. # decode what you receive:
  18. line = line.decode('iso8859-1')
  19.  
  20. # work with unicode internally:
  21. line = line.upper()
  22.  
  23. # encode what you send:
  24. line = line.encode('utf-8')
  25. sys.stdout.write(line)
  26.  
  27. # -*- coding: utf-8 -*-
  28. print u"åäö".encode('utf-8')
  29.  
  30. import sys
  31. import codecs
  32. sys.stdout = codecs.getwriter('utf8')(sys.stdout)
Add Comment
Please, Sign In to add comment