在应用开发中,我们经常会通过工具生成一些代码以提高开发效率,而本文则通过python将正常代码转成生成该代码的工具,并自动将原始代码类名、函数名等转成参数,目前只支持c#语言(待优化),一下是python工具代码:
1 #!/usr/bin/ python 2 # -*- coding:utf-8 -*- 3 #操作同路径下的所有.cs .lua文件,并生成自动生成该cs文件的代码 4 import os 5 global classCount,lastClassName 6 7 def MachiningSourceCode(x): 8 global classCount,lastClassName 9 if x.find('class') >= 0: 10 #类名由tool方法参数决定 11 classCount = classCount + 112 xarr = x.split()13 nindex = -114 for a in range(len(xarr)):15 if xarr[a] == 'class':16 nindex = a17 break18 lastClassName = xarr[nindex + 1]19 xarr[nindex + 1] = '{0}'20 x = ' '.join(xarr)21 x = ' stringBuilder.AppendFormat(\"'+x.strip('\n').replace('\"','\\"')+'\\n\",className%d);\n' % classCount22 elif x.find(lastClassName) >= 0:23 #处理构造函数类名也由tool方法参数决定24 x = x.replace(lastClassName,'{0}')25 x = ' stringBuilder.AppendFormat(\"'+x.strip('\n').replace('\"','\\"')+'\\n\",className%d);\n' % classCount26 else: 27 x = ' stringBuilder.AppendLine(\"'+x.strip('\n').replace('\"','\\"')+'\");\n'28 return x29 30 #生成自动生成工具代码31 def GenerateAutoCreatingToolCode(f,newfileName):32 lines = f.readlines()33 global classCount34 classCount = 035 newlines = map(MachiningSourceCode,lines)36 toolFuncParam = ''37 if classCount > 0:38 for x in range(classCount):39 toolFuncParam = toolFuncParam + ',string className%d' % (x + 1) 40 namespaceReference = 'using UnityEngine;\nusing System.Text;\nusing System.IO;\n\n'41 classAndFunc = 'public static class %s\n {\n public static void CreateClass(string stSaveFilePath %s,string stNameSpace = "")\n {\n \42 if (string.IsNullOrEmpty(stSaveFilePath))\n {\n return;\n }\n \43 StringBuilder stringBuilder = new StringBuilder();\n' % (newfileName,toolFuncParam)44 nameSpace = ' if (!string.IsNullOrEmpty(stNameSpace))\n {\n stringBuilder.AppendFormat\45 (string.Format(\"namespace {0}\\n\", stNameSpace));\n stringBuilder.AppendLine(\"{\");\n }\n'46 saveFile = ' if (!string.IsNullOrEmpty(stNameSpace))\n {\n stringBuilder.AppendLine(\"}\");\n }\n \47 File.WriteAllText(stSaveFilePath, stringBuilder.ToString());\n }\n}'48 newlines.insert(0,namespaceReference)49 newlines.insert(1,classAndFunc)50 newlines.insert(2,nameSpace)51 newlines.insert(len(newlines),saveFile)52 return newlines53 54 if __name__ == '__main__': 55 try:56 global lastClassName57 lastClassName = 'lastClassName'58 59 #创建生成代码文件夹60 currentPath = os.path.abspath('.') 61 createFilePath = os.path.join(currentPath,'createFile')62 if not os.path.exists(createFilePath):63 os.mkdir(createFilePath)64 65 for x in os.listdir("."):66 if os.path.isfile(x) and (os.path.splitext(x)[1] == '.cs' or os.path.splitext(x)[1] == '.lua'):67 readFilePath = os.path.join(currentPath,x)68 newfileName = 'Create%sAuto' % os.path.splitext(x)[0]69 newfile = newfileName + os.path.splitext(x)[1]70 writeFilePath = os.path.join(createFilePath,newfile)71 with open(readFilePath,'r') as f: 72 newlines = GenerateAutoCreatingToolCode(f,newfileName)73 74 #生成代码文件 75 if os.path.exists(writeFilePath):76 os.remove(writeFilePath)77 print('delete old file:%s' % writeFilePath)78 with open(writeFilePath,'w') as fw:79 fw.writelines(newlines)80 except Exception as e:81 print(e)82 n = input()83