【问题标题】:How do you use write() in python to write a docstring to a file?如何在 python 中使用 write() 将文档字符串写入文件?
【发布时间】:2019-02-12 06:44:36
【问题描述】:

我正在使用 pytest 检查多行文档字符串,而我测试这些多行 cmets 的方法包括制作一个临时文件并使用 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 方式。它与文档字符串无关。文档字符串是函数的第一个未分配的字符串。您可以使用任何引号来表示它。打印后,"""X""""X"'X' 都将变为 X
  • 当然,如果你想用三引号写string,你可以hello_file.write('"""{}"""'.format(string))
  • @tripleee 谢谢你,那行得通。也读进去怎么样?只看到一对引文。我如何让它也看到另一个?
  • 你应该理解上面的第一条评论。

标签: python pytest docstring


【解决方案1】:

如果我需要将文档写入文件,我将使用this 方式通过__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__)

【讨论】:

    【解决方案2】:

    正如 cmets """ 所说,仅显示多行字符串。如果您只想将文档字符串写入文件,您可以直接从具有__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"""')
    

    【讨论】:

      猜你喜欢
      • 2013-11-09
      • 2018-11-25
      • 2011-01-30
      • 1970-01-01
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-05
      相关资源
      最近更新 更多