试图找到python library
或从python code files
找到最佳方法的方法
例如app.py
from django.conf.urls import url
from oscar.core.loading import get_class
class SearchApplication(Application):
name = 'search'
search_view = get_class('search.views', 'FacetedSearchView')
search_form = get_class('search.forms', 'SearchForm')
def get_urls(self):
# The form class has to be passed to the __init__ method as that is how
# Haystack works. It's slightly different to normal CBVs.
urlpatterns = [
url(r'^$', search_view_factory(
view_class=self.search_view,
form_class=self.search_form,
searchqueryset=self.get_sqs()),
name='search'),
]
return self.post_process_urls(urlpatterns)
我的目的是编写将文件app.py
作为文本或文件输入的代码(两种方法都可以)并输出如下内容:
{
"methods": [
{"name": "get_urls", "class": "SearchApplication", "line": 9, "args": [self], "kwargs": []}
],
"classs": [
{"name": "SearchApplication", "inherits_from": "Application", "line": 5}
]
}
谢谢。请询问意图是否不清楚或问题是否缺少数据。
答案 0 :(得分:1)
使用过的ast.parse
file_content = open('/path_to_file', 'r').read()
parsed_result = ast.parse(self.file_content)
for element in parsed_result.body:
results = self.index_element(element)
def index_element(self, element, class_name=None):
'''
if element is relevant, meaning method -> index
if element is Class -> recursively call it self
:param element:
:param class_name:
:return: [{insert_result: <db_insert_result>, 'structured_data': <method> object}, ...]
'''
# find classes
# find methods inside classes
# find hanging functions
# validation on element type
if self.should_index_element(element):
if self.is_class_definition(element):
class_element = element
indexed_items = []
for inner_element in class_element.body:
# recursive call
results = self.index_element(inner_element, class_name=class_element.name)
indexed_items += results
return indexed_items
else:
structured_data = self.structure_method_into_an_object(element, class_name=class_name)
result_graph = self.dal_client.methods_graph.insert_or_update(structured_data)
return "WhatEver"
return "WhatEver"
element
对象具有函数/类的属性。