The Shape of Everything
A website mostly about Mac stuff, written by Gus Mueller
» Acorn
» Retrobatch
» Twitter
» Micro.blog
» Mastodon
» Instagram
» Github
» Maybe Pizza?
» Archives
» Feed
» Micro feed
November 8, 2004
(This post is from my old, old, super old site. My views have changed over the years, hopefully my writing has improved, and there is now more than a handful of folks reading my site. Enjoy.)

Monday, November 8th, 2004

I always seem to get tripped up when it comes to utf8 and python. I keep on getting errors like "UnicodeError: ASCII encoding error: ordinal not in range.." when I print out something non-ascii-ish. And I always find a fix for it, but I can never remember what it is next time I encounter it.

So for future reference, here it is what to do when you (or I for that matter) encounter this problem:

#!/usr/bin/python -U # -*- coding: utf-8 -*- import os, sys, string, codecs (e,d,sr,sw) = codecs.lookup('utf-8') sys.stdout = sw(sys.stdout)

And that seems to take care of everything. I got that hint from reportlab.com.

And later on...

Of course, it always turns out that there's an easier way to do anything that I write in python. Bob Ippolito lets me know in the comments that this works as well:

import codecs, sys sys.stdout = codecs.getwriter('utf-8')(sys.stdout)

-- posted 8:57 pm