python - 获取任意脚本文件的Python docstring

标签 python inspect docstring

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

获取了调用脚本的文件名
import inspect
filename = inspect.stack()[1].filename

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

最佳答案

根据 chaos 关于使用 ast 的建议,我编写了以下内容,看起来效果很好。

import ast

with open(fname, 'r') as f:
    tree = ast.parse(f.read())
docstring = ast.get_docstring(tree)

关于python - 获取任意脚本文件的Python docstring,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43519927/

相关文章:

python - 如何查看Python的__builtins__源代码?

python - 使用inspect_container在python上检查停止的docker容器

python - 如何使用 Python 数据类记录类的构造函数?

python - 使用正则表达式有效地将一列中的部分值替换为 pandas 中另一列中的值?

Python BeautifulSoup 没有抓取多个页面

python - 为什么线程会进入休眠状态?

python - 编写类时扩展或覆盖文档字符串

python - 如何使用 ZeroMQ 从 Python 建立到 Metatrader 4 的连接

python - 在 Python 中打印时包括当前方法名称

latex - Sphinx 未正确呈现文档字符串中的数学表达式