需要考虑的点
目录下可能还有目录,文件里可能有类似类名格式的字符串
import imp
import os
import re
cls_name_list = []
def get_dir(path):
try:
file_list = os.listdir(path)
except:
file_list = []
print("the path is not dir")
if file_list:
for file in file_list:
file = os.path.join(path, file)
print(file)
if os.path.isdir(file):
get_dir(file)
else:
if file.endswith(".py"):
with open(file, encoding="utf-8") as f:
for line in f.readlines():
cls_match = re.match(r"class\s(.*?)[\(:]", line)
if cls_match:
cls_name = cls_match.group(1)
try:
module = imp.load_source('mycl', file)
cls_a = getattr(module, cls_name)
if cls_a:
cls_name_list.append(cls_name)
except:
pass
if __name__ == '__main__':
path = "/home/study"
get_dir(path)
print(cls_name_list)