1. 问题:
为了使用方便,将函数的相关信息写在文档字符串中,需要根据函数名,将使用信息自动生
成帮助信息提供给其他模块使用,该如何实现?
2. 解决方法:
先获取模块中的函数名称,再根据函数名称获取对应的文档字符串。
- 示例:
# 函数所在文件:demotest.py
import ast
import os
def test_demo_1():
'''字符串文档: 样例函数1'''
print("样例函数1--")
def test_demo_2():
'''字符串文档: 样例函数2'''
print("样例函数2--")
def get_function_doc(python_file_path):
'''获取文档字符内容函数'''
with open(python_file_path, 'r', encoding='utf-8') as file:
content = file.read()
tree = ast.parse(content)
function_names = [node.name for node in ast.walk(tree) if isinstance(node, ast.FunctionDef)]
function_doc = [globals()[item].__doc__ for item in function_names]
return function_doc
# 使用文件
if __name__ == '__main__':
print(get_function_doc(r"D:\codestore\practiseProject\demotest.py"))
- 示例结果: