2016-03-11 44 views
-3

我想知道是否有辦法解決這個錯誤。任何幫助,將不勝感激!反向工程python 3

TypeError: can't concat bytes to str 
import marshal, imp 

f=open('PYTHONSCRIPT','rb') 
f.seek(28) # Skip the header, you have to know the header size beforehand 

ob=marshal.load(f) 

for i in range(0,len(ob)): 
    open(str(i)+'.pyc','wb').write(imp.get_magic() + '\0'*4 + marshal.dumps(ob[i])) 

f.close() 

open(str(i)+'.pyc','wb').write(imp.get_magic() + '\0'*4 + marshal.dumps(ob[i])) 
+0

可能重複的[Python 3 TypeError:必須是str,而不是字節與sys.stdout.write()](http://stackoverflow.com/questions/21689365/python-3-typeerror-must-be-str -not-bytes-with-sys-stdout-write) – Carpetsmoker

+0

請提供完整的堆棧跟蹤。 –

+0

'str'和'bytes'類型不兼容。你必須轉換其中的一個。上面的答案應該給你你需要的信息和細節。 – Carpetsmoker

回答

1

你的問題是,你試圖連接兩個byte s和str。這在python3中是不可能的,因爲python3明確區分了字節和字符串(python2中strunicode之間有點模糊區別是一件好事)。我想你想要的東西可能是以下幾點:

import marshal, imp 

f=open('PYTHONSCRIPT','rb') 
f.seek(28) # Skip the header, you have to know the header size beforehand 

ob=marshal.load(f) 

for i in range(0,len(ob)): 
    with open(str(i)+'.pyc','wb') as my_file: 
     my_file.write(imp.get_magic() + b'\0'*4 + marshal.dumps(ob[i])) 

f.close() 

with open(str(i)+'.pyc','wb') as my_file: 
    my_file.write(imp.get_magic() + b'\0'*4 + marshal.dumps(ob[i])) 

b琴絃之前是一個標記,告訴蟒蛇的字符串是byte字符串,而不是str字符串。

請注意,我還添加了with ... as ...:,這將確保即使在非CPython實現(PyPy,Jython,IronPython等)中,您的文件也能立即確定性地關閉。

+0

對'with'有很好的一般性建議,但是這段代碼當然不會在除了CPython之外的其他任何東西上運行:D –

+0

@AnttiHaapala我不關注。它看起來像一個非常標準的python,至少可以在pypy上運行(我不能說Jython或IronPython,因爲我不太瞭解它們)。你知道關於提問者申請的一些事嗎? – CrazyCasta

+0

它與CPython .pyc文件混淆,當然不會在使用java .classes的Jython上工作。至少Jython 2.7似乎有'imp.get_magic'返回CPython get_magic,但是元帥不兼容。 –

2

'\0'*4str,使用b'\0' * 4來得到所需的bytes值。