簡體   English   中英

如何在python中使用write()將文檔字符串寫入文件?

[英]How do you use write() in python to write a docstring to a file?

我正在使用pytest來檢查多行docstring,而我正在測試來檢查這些多行注釋的方法包括制作一個臨時文件,並使用write()將docstring寫入其中,然后進行搜索。

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

如果我需要將docsting寫入文件,我將使用這種方式通過使用__doc__屬性來接收文檔字符串:

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

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

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

之后,將此文檔編寫為常規字符串:

hello_file.write(some_function.__doc__)

正如評論中所說, """僅顯示多行字符串。如果您只想向文件寫入文檔字符串,則可以直接從具有__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"""')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM