"""
收集继承自MonoBehaviour的类的类名,并输出到文件中。
直接,间接
这里只搜集了直接继承的部分类。
用python3运行
"""
import string
import os
import shutil
import datetime
import re
def getTypeFiles(path, type):
"""
获取文件夹下的后缀名文件
:param type: 传入的后缀名
:param path: 项目根路径
:return: 文件路径数组
"""
assert os.path.isdir(path), '%s not exist.' % path
fs = []
for root, dirs, files in os.walk(path):
for filespath in files:
if os.path.splitext(filespath)[1] == type:
file = os.path.join(root, filespath)
# print("file= ", file)
fs.append(file)
return list(set(fs))
def getCsClasss(csFileList):
"""
提取.cs文件中的类名
:param csFileList: cs文件路径数组
:return: 类名数组
"""
classs = []
for file in csFileList:
f = open(file, "r", encoding="ISO-8859-1")
for text in f:
className = getClassName(text)
# className = getClassNameInheritMono(text)
if not className == "":
# print("className= ", className)
classs.append(className)
f.close()
classs.sort(key=lambda x: len(x), reverse=True)
return list(set(classs))
def getClassName(line):
"""
提取类名结构
:param text: 传入的字符串
:return: 类名
"""
className = ""
# if re.findall("public class ", text) or re.findall("public enum ", text) or re.findall("private struct", text) or re.findall("public struct", text):
if re.findall("public class ", line):
text = line
text = text.replace("\n", "")
text = text.replace("{", "")
if ":" in text:
text = text.split(":")[0]
if "<" in text:
text = text.split("<")[0]
texts = text.split()
#找到他的父类
classSupers = getClassSupers(line)
for classSuper in classSupers:
if classSuper == "MonoBehaviour":
# print("父类为:MonoBehaviour")
className = texts[-1]
return className
def getClassSupers(text):
classSupers = []
if re.findall("public class ", text):
text = text.replace("\n", "")
text = text.replace("{", "")
if not ":" in text:
return []
text = text.split(":")[1]
text = text.replace(" ", "")
if "," in text:
return text.split(",")
else:
return [text]
else:
return []
def createClassNameFile(path, classList):
"""
生成类名文件
:param path: 文件路径
:param classList: 类的列表
:return:
"""
str_data = ""
for value in classList:
str_data = str_data + value + "\n"
with open(path, "w", encoding="utf-8") as f:
f.write(str_data)
f.close()
#入口代码
if __name__ == '__main__':
#"./AllCS" 即同级目录AllCS
path = "./AllCS"
if not os.path.exists(path):
print(path + " not exist!")
startTime = datetime.datetime.now()
print("正在扫描需要处理的文件...")
csFiles = getTypeFiles(path, ".cs")
# print(csFiles, "\n", len(csFiles))
print("cs文件的总数", len(csFiles))
#找出所有满足要求的类,并输出到文件中
classList = getCsClasss(csFiles)
classNameFilePath = "./ClassName_" + datetime.datetime.now().strftime('%Y%m%d') + ".txt"
print("正在生成对类名文件...\n" + classNameFilePath)
createClassNameFile(classNameFilePath, classList)
endTime = datetime.datetime.now()
print('脚本执行用时:' + str((endTime - startTime).seconds) + "s")
我把项目中两千多个cs文件复制到AllCS文件夹,脚本执行用时大概只要1秒钟。