如何从单独的脚本访问文档字符串?

How to access a docstring from a separate script?

为用户构建一个 GUI select Python 他们想要的脚本 运行。每个脚本都有自己的文档字符串,用于解释脚本的输入和输出。一旦他们突出显示了脚本,我想在 UI 中显示该信息,而不是 selected 到 运行 它,而且我似乎无法访问文档字符串基础程序。

例如

test.py

"""this is a docstring"""
print('hello world')

program.py

index 在这个例子中是 test.py,但通常不知道,因为它是用户在 GUI.[=16= 中 select 编辑的任何内容]

# index is test.py
def on_selected(self, index):
    script_path = self.tree_view_model.filePath(index)
    fparse = ast.parse(''.join(open(script_path)))
    self.textBrowser_description.setPlainText(ast.get_docstring(fparse))

假设您要访问的文档字符串属于文件,file.py

您可以通过执行以下操作获取文档字符串:

import file
print(file.__doc__)

如果您想在导入之前获取文档字符串,那么您可以读取文件并提取文档字符串。这是一个例子:

import re


def get_docstring(file)
    with open(file, "r") as f:
        content = f.read()  # read file
        quote = content[0]  # get type of quote
        pattern = re.compile(rf"^{quote}{quote}{quote}[^{quote}]*{quote}{quote}{quote}")  # create docstring pattern
    return re.findall(pattern, content)[0][3:-3]  # return docstring without quotes


print(get_docstring("file.py"))

注意:要使此正则表达式起作用,文档字符串需要位于最顶部。

这是通过 importlib 获取它的方法。大多数逻辑都放在一个函数中。请注意,使用 importlib 导入脚本(这会导致执行其所有顶级语句),但模块本身在函数 returns 时被丢弃.

如果这是我想从中获取文档字符串的当前目录中的脚本 docstring_test.py

""" this is a multiline
    docstring.
"""
print('hello world')

操作方法如下:

import importlib.util

def get_docstring(script_name, script_path):
    spec = importlib.util.spec_from_file_location(script_name, script_path)
    foo = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(foo)
    return foo.__doc__

if __name__ == '__main__':

    print(get_docstring('docstring_test', "./docstring_test.py"))

输出:

hello world
 this is a multiline
    docstring.

更新:

这是通过让标准库中的 ast 模块进行解析来完成的,这既避免了 importing/executing 脚本,也避免了尝试使用正则表达式自己解析它。

这看起来或多或少等同于你的问题,所以不清楚为什么你所拥有的不适合你。

import ast

def get_docstring(script_path):
    with open(script_path, 'r') as file:
        tree = ast.parse(file.read())
        return ast.get_docstring(tree, clean=False)

if __name__ == '__main__':

    print(repr(get_docstring('./docstring_test.py')))

输出:

' this is a multiline\n    docstring.\n'