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

问题描述 投票:0回答:2

构建一个 GUI 供用户选择他们想要运行的 Python 脚本。每个脚本都有自己的文档字符串,解释脚本的输入和输出。一旦他们突出显示了脚本,但没有选择运行它,我想在用户界面中显示该信息,并且我似乎无法从基本程序访问文档字符串。

例如。

test.py

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

program.py

对于本示例,

index
test.py
,但通常不知道,因为它是用户在 GUI 中选择的任何内容。

# 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))
python python-3.8 docstring python-ast
2个回答
2
投票

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

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"))

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


1
投票

以下是如何通过

importlib
获取它。大部分逻辑已放入函数中。请注意,使用
importlib
does 导入脚本(这会导致执行其所有顶级语句),但当函数返回时,模块本身将被丢弃。

如果这是当前目录中的脚本

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
模块进行解析来实现此目的,从而避免导入/执行脚本以及尝试使用正则表达式自行解析它。

这看起来或多或少相当于你问题中的内容,所以不清楚为什么你所拥有的不适合你。

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'
© www.soinside.com 2019 - 2024. All rights reserved.