當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python doctest.script_from_examples用法及代碼示例

用法:

doctest.script_from_examples(s)

將帶有示例的文本轉換為腳本。

參數 s 是一個包含 doctest 示例的字符串。該字符串被轉換為 Python 腳本,其中 s 中的 doctest 示例被轉換為常規代碼,其他所有內容都被轉換為 Python 注釋。生成的腳本以字符串形式返回。例如,

import doctest
print(doctest.script_from_examples(r"""
    Set x and y to 1 and 2.
    >>> x, y = 1, 2

    Print their sum:
    >>> print(x+y)
    3
"""))

顯示:

# Set x and y to 1 and 2.
x, y = 1, 2
#
# Print their sum:
print(x+y)
# Expected:
## 3

此函數由其他函數在內部使用(見下文),但在您想要將交互式 Python 會話轉換為 Python 腳本時也很有用。

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 doctest.script_from_examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。