2017-05-06 97 views
0

我想創建一個HTML報告爲我單位的測試腳本,當我嘗試運行的代碼,它是投擲1拉丁,這個錯誤AttributeError: 'str' object has no attribute 'decode'AttributeError的:「海峽」對象有沒有屬性「解碼」

下面是代碼的一部分,在那裏示出的錯誤: -

if isinstance(o,str): 
    # TODO: some problem with 'string_escape': it escape \n and mess up formating 
    # uo = unicode(o.encode('string_escape')) 
    uo = o.decode('latin-1') 
else: 
    uo = o 
if isinstance(e,str): 
    # TODO: some problem with 'string_escape': it escape \n and mess up formating 
    # ue = unicode(e.encode('string_escape')) 
    ue = e.decode('latin-1') 
else: 
    ue = e 

script = self.REPORT_TEST_OUTPUT_TMPL % dict(
    id = tid, 
    output = saxutils.escape(uo+ue), 
) 

上面的代碼是從HTMLTestRunner.py文件。請幫助調試此問題。

+0

正確的方法是不進行解碼編碼 –

回答

2

我假設你使用python3

在python3不再有一個unicode類型,這簡直是str(因爲你的問題的標記) - str是一個文本類型,這已經是UNICODE解碼,因此,str不再有decode方法。

對於處理字符串,有具有decode方法bytes類型(decode -ing bytes回報str,並encode -ing str回報bytes

從現在開始,所以

- 而不是使用decode當類型是str,使用decode只有類型爲bytes

這意味着你的代碼應該是這樣的:

if isinstance(o,bytes): 
    uo = o.decode('latin-1') 
else: 
    uo = o 
if isinstance(e,bytes): 
    ue = e.decode('latin-1') 
else: 
    ue = e 

script = self.REPORT_TEST_OUTPUT_TMPL % dict(
    id = tid, 
    output = saxutils.escape(uo+ue), 
) 
+0

謝謝你幫我迪安,改變爲「字節」,我面對錯誤之後,在該行中的一個 「self.stream.write(output.encode('UTF8 '))「,它說,」TypeError:write()參數必須是str,而不是字節「請幫助我,如何糾正這個錯誤 – Santosh

+0

@Santosh - 在哪一行?這可能發生在這段代碼之後,將報告寫入文件。 (它預計蒸汽用'wb'而不是'w'開啓) –

+0

謝謝Dean,它開始工作了.. :) – Santosh

相關問題