如何解决如何从单独的脚本访问文档字符串?
为用户构建 GUI 以选择他们想要运行的 Python 脚本。每个脚本都有自己的文档字符串来解释脚本的输入和输出。我想在他们突出显示脚本后在 UI 中显示该信息,但没有选择运行它,而且我似乎无法从基本程序访问文档字符串。
例如
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))
解决方法
让我们要访问的文档字符串属于文件 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
确实 导入脚本(这会导致执行其所有顶级语句),但是当函数返回时模块本身会被丢弃。
如果这是我想从中获取文档字符串的当前目录中的脚本 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'
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。