Python中bytes对象上的项分配

2024-09-28 19:07:38 发布

您现在位置:Python中文网/ 问答频道 /正文

唉,代码不工作真是糟糕的代码!

in RemoveRETNs toOutput[currentLoc - 0x00400000] = b'\xCC' TypeError: 'bytes' object does not support item assignment

我如何解决这个问题:

inputFile = 'original.exe'
outputFile = 'output.txt'
patchedFile = 'original_patched.exe'

def GetFileContents(filename):
    f = open(filename, 'rb')
    fileContents = f.read()
    f.close()

    return fileContents

def FindAll(fileContents, strToFind):
    found = []

    lastOffset = -1

    while True:
        lastOffset += 1
        lastOffset = fileContents.find(b'\xC3\xCC\xCC\xCC\xCC', lastOffset)

        if lastOffset != -1:
            found.append(lastOffset)
        else:
            break

    return found

def FixOffsets(offsetList):
    for current in range(0, len(offsetList)):
        offsetList[current] += 0x00400000
    return offsetList

def AbsentFromList(toFind, theList):
    for i in theList:
        if i == toFind:
            return True
    return False

# Outputs the original file with all RETNs replaced with INT3s.
def RemoveRETNs(locationsOfRETNs, oldFilesContents, newFilesName):
    target = open(newFilesName, 'wb')

    toOutput = oldFilesContents

    for currentLoc in locationsOfRETNs:
        toOutput[currentLoc - 0x00400000] = b'\xCC'

    target.write(toOutput)

    target.close()

fileContents = GetFileContents(inputFile)
offsets = FixOffsets(FindAll(fileContents, '\xC3\xCC\xCC\xCC\xCC'))
RemoveRETNs(offsets, fileContents, patchedFile)

我做错了什么,我能做什么来纠正它?代码示例?


Tags: 代码intargetforreturndeforiginalfound
2条回答

Bytestrings(通常是字符串)是Python中不可变的对象。一旦你创造了它们,你就无法改变它们。相反,你必须创建一个新的,恰好有一些旧的内容。(例如,使用基本字符串newString = oldString[:offset] + newChar + oldString[offset+1:]或类似的字符串。)

相反,您可能希望首先将bytestring转换为字节列表,或者操作bytearray,然后在完成所有操作后将bytearray/list转换回静态字符串。这样可以避免为每个替换操作创建新字符串。

GetFileContentsreturn语句更改为

return bytearray(fileContents)

其他的都能用。你需要使用bytearray,而不是bytes,因为前者是可变的(读/写),后者(这就是你现在使用的)是不可变的(只读)。

相关问题 更多 >