2010-07-30 66 views
2

尝试将异常重定向到STDERR时出现奇怪的错误。TypeError:writelines()参数必须是字符串的序列

我有一个脚本,用来加载几个“插件”,作为主入口程序。该插件做的东西一样连接到数据库,解析文本数据,连接到Web服务,等等。

是这样的:

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) 

这是在命令行中执行,有时我得到错误:

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

我不知道如何在这个地球上一个异常没有返回作为一个字符串在这里。

回答

2

我终于明白了这一点。

这happend时:

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

我破解这个(来自ActiveState的社区):

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

这很有可能是e有问题。我不知道为什么。可能有些东西没有被正确强制。

这有帮助吗?

0

要获取有关发生了什么更好的线索,包装在尝试冒犯声明:以下情况除外:......在不同的条款,做

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

为什么你需要unicode串而不是str字符串?

6

我对这个解决方案是在UTF-8

file.writelines("some unicode text here".encode('utf-8')) 
文本编码
相关问题