博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
生成生成代码的工具(python实现)
阅读量:4709 次
发布时间:2019-06-10

本文共 4010 字,大约阅读时间需要 13 分钟。

在应用开发中,我们经常会通过工具生成一些代码以提高开发效率,而本文则通过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
View Code

 

转载于:https://www.cnblogs.com/ChengShuKaiShi/p/7750557.html

你可能感兴趣的文章
Struts2环境搭建
查看>>
Linux: Check version info
查看>>
stl学习之测试stlen,cout等的运行速度
查看>>
魔戒三曲,黑暗散去;人皇加冕,光明归来
查看>>
Error和Exception
查看>>
Python和Singleton (单件)模式[转载]
查看>>
httpclient设置proxy与proxyselector
查看>>
IT常用单词
查看>>
拓扑排序
查看>>
NYOJ--32--SEARCH--组合数
查看>>
gulpfile 压缩模板
查看>>
【34.14%】【BZOJ 3110】 [Zjoi2013]K大数查询
查看>>
【 henuacm2016级暑期训练-动态规划专题 A 】Cards
查看>>
第五篇:白话tornado源码之褪去模板的外衣
查看>>
设备常用框架framework
查看>>
bootstrap模态框和select2合用时input无法获取焦点(转)
查看>>
MockObject
查看>>
BZOJ4516: [Sdoi2016]生成魔咒(后缀自动机)
查看>>
查看手机已经记住的WIFI密码
查看>>
最新版IntelliJ IDEA2019 破解教程(2019.08.07-情人节更新)
查看>>