解析python/django代码以使其在GUI中可编辑
我正在开发一个用于创建/编辑Django模型的工具,请参阅 解析Python代码的推荐方法是什么?我需要做一堆正则表达式和很多if-thens吗 下面的代码获取模型名和字段名解析python/django代码以使其在GUI中可编辑,python,regex,django,parsing,Python,Regex,Django,Parsing,我正在开发一个用于创建/编辑Django模型的工具,请参阅 解析Python代码的推荐方法是什么?我需要做一堆正则表达式和很多if-thens吗 下面的代码获取模型名和字段名 code_from_input = request.POST['code'].split('\n')[0] def_lines = '' if ' def' in request.POST['code']: for i, line in enumerate(request.POST['code'].split
code_from_input = request.POST['code'].split('\n')[0]
def_lines = ''
if ' def' in request.POST['code']:
for i, line in enumerate(request.POST['code'].split('\n')):
if line.startswith(' def'):
def_lines = '\n'.join(request.POST['code'].split('\n')[i:])
break
last_code_from_input = request.POST['last_code'].split('\n')[0]
# check if model name in source changed
model_name_in_last_source = ''
model_name_in_code = ''
if last_code_from_input.startswith('class'):
m = re.match(r"class (\w+)\(models.Model\):", last_code_from_input)
try:
model_name_in_last_source = m.group(1)
except:
pass
if code_from_input.startswith('class'):
m = re.match(r"class (\w+)\(models.Model\):", code_from_input)
try:
model_name_in_code = m.group(1)
except:
pass
if model_name_in_last_source != model_name_in_code:
model_name = model_name_in_code
else:
model_name = request.POST['name']
对于非常简单的用例,可以使用正则表达式。如果您只想在源代码中定位类,那么您的方法可能很好 或者,可以查看inspect模块,但这只能用于导入的python模块,而不能用于源文件。您可以枚举模块中的类,提取方法名称、源代码和文档。这可能是你想要的最好的方法 如果您真的深入研究源代码,您可以尝试使用ast模块。它提供了一个解析函数,该函数接受python源代码的字符串并返回一个抽象语法树。这是最复杂的库,也是最强大的库
请参阅:了解更多详细信息。Timothy,请注意,在您接受我的回复后,我对其进行了编辑。我还建议使用inspect模块,我认为它对于您想要的内容更有用。