开发者

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

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 ex开发者_Go百科ecuted 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.


My solution to this was to encode the text in UTF-8

file.writelines("some unicode text here".encode('utf-8'))


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)))


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)


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?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜