python - 如何在 python 中使用 write() 将文档字符串写入文件?
问题描述
我正在使用 pytest 检查多行文档字符串,而我测试这些多行注释的方法包括制作一个临时文件并使用write()
将文档字符串写入然后搜索它。
def test_file_contains_multiline_python_comment_count(tmpdir):
"""Checks that the multiline python comment count works"""
hello_file = tmpdir.mkdir("subdirectory").join("Hello.py")
hello_file.write(""" hello \n world """)
assert hello_file.read() == """ hello \n world """
assert len(tmpdir.listdir()) == 1
comment_count = entities.count_entities(
hello_file.basename, hello_file.dirname, comments.count_multiline_python_comment
)
assert comment_count == 1
但是我无法弄清楚如何编写实际的文档字符串。例如,"""hello"""
将简单地显示为hello
解决方案
正如评论已经说过的那样,"""
只显示一个多行字符串。如果您只想将文档字符串写入文件,您可以直接从具有__doc__
属性的函数中获取文档字符串。然后你可以用你想要的任何格式将它写到这样的文件中:
def test():
"""
This is docstring of the test function
"""
return "Hello"
if __name__ == "__main__":
with open("out.txt", "w") as f:
f.write('"""\n' + (test.__doc__).strip() + '\n"""')
推荐阅读
- windows - 如何通过名称(而不是 IP)访问主机上的 Docker 容器?
- php - 在jquery中创建一个多维数组
- python-3.x - 使用 query-exporter 将数据从 DB2 导出到 Prometheus
- android - DownloadManager 在开始下载时有很大的延迟
- python - 序列化 os 问题列表并以 JSON 形式返回
- image-processing - ade20k 数据集标签问题
- python - 避免多次调用 Mixin 类的 __init__
- winforms - PowerShell WinForms 阻止安装 Windows 功能
- python-3.x - 省略了 ELIF 语句以支持 ELSE
- python - 根据项目ID添加价格