views:

51

answers:

3

I have a weird error when try to redirect a exception to STDERR.

I have a script that is use to load several "plugins", working as main entry program. The plugins do stuff like connect to databases, parsing text data, connect to web services, etc...

Is like this:

   try:
        Run plugins here...
        #All was ok!
        print "Ok!"
        sys.exit(0)
    except Exception,e:
        sys.stderr.writelines([unicode(e),u'\n',u'\n'])

        traceback.print_exc(file=sys.stderr)
        sys.exit(-1)

This is executed in the command-line, and sometimes I get the error:

TypeError: writelines() argument must be a sequence of strings

I have no clue how in this earth a Exception is not returning as a string here.

A: 

It's highly likely that e is at fault. I have no idea why. Possibly something is not being coerced properly.

Does this help?

sys.stderr.write(u'%s\n\n' % e)
Tim McNamara
A: 

To get a better clue about what is happening, wrap the offending statement in try:except: ... in the except clause, do

print repr(e), repr(unicode(e))

Why do you need unicode strings instead of str strings?

John Machin
A: 

I finally figure this out.

This happend when:

try:
   raise Exception(u'Error with unicode chars')
except:
  sys.stderr.write(u'%s\n\n' % e)

I hack with this (from activestate community):

def safe_unicode(obj, * args):
    """ return the unicode representation of obj """
    try:
        return unicode(obj, * args)
    except UnicodeDecodeError:
        # obj is byte string
        ascii_text = str(obj).encode('string_escape')
        return unicode(ascii_text)

def safe_str(obj):
    """ return the byte string representation of obj """
    try:
        return str(obj)
    except UnicodeEncodeError:
        # obj is unicode
        return unicode(obj).encode('unicode_escape')


 #code
 except Exception,e:
        sys.stderr.write(u'%s\n\n' % safe_unicode(safe_str(e)))
mamcx