使用更新的函数搜索和替换现有的python脚本

时间:2017-04-20 21:16:29

标签: python

我需要编写一个Python脚本来更新另一个Python脚本,以便旧的代码片段将被更新的函数替换。基本上每当它看到类似“Model ... Read()或Model ... Write(x)”的东西时,它应该用更新的字符串替换它们。例如,脚本应该找到字符串“Model.CB1_OV_En.Read()”并将其替换为“MAPort.Read(Model.CB1_OV_En).Value”。有许多变量要更新,手动完成这将是繁琐的,所以我很好奇是否有一个很好的方法来实现自动化。我有字符串替换函数已完成,但我不确定如何自动查找.py文件中的变量。

def main():
    textfile = "C:\\Desktop\\Trip_Logic.py"
    with open(textfile, 'r') as file :
        filedata = file.read()
    readString     = "Model....Read()"
    if readString in filedata:
        print readString[2:7]
    filedata = filedata.replace(readString, convertReadHILAPI(readString))
    with open(textfile, 'w') as file:
        file.write(filedata)
    #filedata = filedata.replace(string, convertWriteHILAPI(writeString))

    ##############################################################
    #Example:
    readString1     = "Model.CB1_OV_En.Read()"
    newReadString1  = "MAPort.Read(Model.CB1_OV_En).Value"
    readString2     = "Model.CB2_OV_En.Read()"
    newReadString2  = "MAPort.Read(Model.CB2_OV_En).Value"
    ##############################################################
    writeString1    = "Model.CB1_OV_En.Write(1)"
    newWriteString1 = "MAPort.Write(Model.CB1_OV_En, Float(1))"
    writeString2    = "Model.CB2_OV_En.Write(1)"
    newWriteString2 = "MAPort.Write(Model.CB2_OV_En, Float(1))"
    ##############################################################

def convertReadHILAPI(string):
    variableStartIndex = 6
    variableStopIndex  = string.find(".Read")
    varName = string[variableStartIndex:variableStopIndex]
    cmd = 'newVarName = "MAPort.Read(Model.%s).Value" % (varName)'
    exec cmd
    return newVarName

def convertWriteHILAPI(string):
    variableStartIndex = 6
    variableStopIndex  = string.find(".Write")
    valueStartIndex = string.find("(")
    valueStopIndex = string.find(")")
    varName = string[variableStartIndex:variableStopIndex]
    value = string[valueStartIndex+1:valueStopIndex]
    cmd = 'newVarName = "MAPort.Write(Model.%s, Float(%s)) " % (varName, value)'
    exec cmd
    return newVarName

if __name__ == '__main__':
    main()

1 个答案:

答案 0 :(得分:0)

您可以使用re module。这是实现你想要的更多pythonic方式:

import re


def main():
    fname = r'C:\Desktop\Trip_Logic.py'
    with open(fname) as reader:
        data = reader.read()

    # Model.XXX.Read() => MAPort.Read(Model.XXX).Value
    data = re.sub(r'(Model\.(.+)\.Read\(\))',
                  r'MAPort.Read(Model.\2).Value',
                  data)

    # Model.XXX.Write(N) => MAPort.Write(Model.XXX, Float(N))
    data = re.sub(r'(Model\.(.+)\.Write\((\d+)\))',
                  r'MAPort.Write(Model.\2, Float(\3))',
                  data)

    with open(fname, 'w') as writer:
        writer.write(data)