You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.3 KiB
63 lines
2.3 KiB
import ast
|
|
import inspect
|
|
|
|
|
|
def get_functions_name_in_main(source_code):
|
|
"""
|
|
Return the functions defined in the main of a source code.
|
|
|
|
source_code: content to analyze
|
|
"""
|
|
tree = ast.parse(source_code)
|
|
functions_in_main = []
|
|
|
|
class MainVisitor(ast.NodeVisitor):
|
|
def visit_If(self, node):
|
|
# Check if the condition is: if __name__ == '__main__':
|
|
if isinstance(node.test, ast.Compare) and \
|
|
isinstance(node.test.left, ast.Name) and node.test.left.id == "__name__" and \
|
|
isinstance(node.test.ops[0], ast.Eq) and \
|
|
isinstance(node.test.comparators[0], ast.Constant) and node.test.comparators[0].value == "__main__":
|
|
# Visit the body of the if statement
|
|
for n in node.body:
|
|
if isinstance(n, ast.FunctionDef):
|
|
functions_in_main.append(n.name)
|
|
elif isinstance(n, ast.AsyncFunctionDef):
|
|
functions_in_main.append(n.name)
|
|
else:
|
|
self.generic_visit(n)
|
|
else:
|
|
self.generic_visit(node)
|
|
|
|
visitor = MainVisitor()
|
|
visitor.visit(tree)
|
|
return functions_in_main
|
|
|
|
|
|
def help(filepath, globals_values):
|
|
"""
|
|
Print helper functions for interactive mode.
|
|
|
|
filepath: path of the file to analyze, __file__
|
|
globals_values: call globals()
|
|
"""
|
|
with open(filepath, "r") as file:
|
|
source_code = file.read()
|
|
functions = get_functions_name_in_main(source_code)
|
|
|
|
print('~' * 20)
|
|
for func_name in functions:
|
|
# Utiliser inspect pour obtenir la fonction elle-même
|
|
func = globals_values.get(func_name)
|
|
if func:
|
|
# Obtenir la signature de la fonction
|
|
signature = inspect.signature(func)
|
|
# Obtenir la docstring de la fonction
|
|
docstring = inspect.getdoc(func)
|
|
# Extraire la première ligne de la docstring
|
|
first_line_of_docstring = docstring.split('\n')[0] if docstring else "No docstring available"
|
|
# Afficher le nom de la fonction, sa signature et la première ligne de la docstring
|
|
print(f"{func_name}{signature}")
|
|
print(f" {first_line_of_docstring}")
|
|
print('~' * 20)
|