2010-07-30 63 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')) 
文本編碼
相關問題