你如何使用Python中的write()写一个文档字符串到一个文件?

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

我使用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

python pytest docstring
2个回答
0
投票

如果我需要写docsting到文件我会用this方式使用__doc__属性接收文档字符串:

def some_function():
    """some docstring
    multiline""" 
    return 0

>>>    some_function.__doc__
    'some docstring\n    multiline'

>>>    type(some_function.__doc__)
    <class 'str'>

写这docsting作为普通字符串后:

hello_file.write(some_function.__doc__)

0
投票

正如已经被评论"""只呈现出多串说。如果你只想写一个文档字符串到一个文件,你可以从__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"""')
© www.soinside.com 2019 - 2024. All rights reserved.