exceptions and unicode

Stuart McGraw smcg4191 at frii.com
Wed Jun 16 16:10:03 EDT 2010


I am having a problem with exceptions and unicode.

  try: open ('file.txt')
  except IOError, e: pass
  str (e)
  => "[Errno 2] No such file or directory: 'file.txt'"

which is fine but...

  try: open (u'フィイル.txt')
  except IOError, e: pass
  str (e)
  => "[Errno 2] No such file or directory: u'\\u30d5\\u30a3\\u30a4\\u30eb.txt'"

ok, I did ask for a str string so no reason I should expect a unicode
string, but then (in Python 2.6)...

  unicode (e)
  => u"(2, 'No such file or directory')"

i.e. no formatting at all, or in Python 2.6.5

  unicode (e)
  => u"[Errno 2] No such file or directory: u'\\u30d5\\u30a3\\u30a4\\u30eb.txt'"

i.e. the result is a unicode string in name only. :-(

What I was expecting (or at least hoping for) of course was 

  => u"[Errno 2] No such file or directory: '\u30d5\u30a3\u30a4\u30eb.txt'"

which when printed would produce something useful

  => [Errno 2] No such file or directory: 'フィイル.txt'

So how do I get what I want?  (Python 3.x is not an option.)
Note that the exceptions may be anything (I just used IOError 
as an example) and are generated in bowels of an API that I 
can't/won't mess with.



More information about the Python-list mailing list