获取任意脚本文件的Python docstring

Oct*_*our 4 python docstring inspect

我正在编写一个需要调用脚本的文档字符串的模块。到目前为止,我已经设法使用获取调用脚本的文件名

import inspect
filename = inspect.stack()[1].filename
Run Code Online (Sandbox Code Playgroud)

文档字符串可以在调用脚本中使用__doc__. 然而,从被调用的脚本中获取文档字符串似乎并不简单。当然我可以写一个函数,但这必然会忽略一些不常见的情况。我有没有办法实际解析调用脚本以找到它的文档字符串(不执行它的代码)?

Oct*_*our 5

根据 Chaos 的使用建议,ast我写了以下似乎工作得很好的内容。

import ast

with open(fname, 'r') as f:
    tree = ast.parse(f.read())
docstring = ast.get_docstring(tree)
Run Code Online (Sandbox Code Playgroud)