首页 > 解决方案 > 如何在 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

标签: pythonpytestdocstring

解决方案


正如评论已经说过的那样,"""只显示一个多行字符串。如果您只想将文档字符串写入文件,您可以直接从具有__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"""')

推荐阅读