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


Python test.support.captured_stdin用法及代碼示例

用法:

test.support.captured_stdin()
test.support.captured_stdout()
test.support.captured_stderr()

io.StringIO 對象臨時替換命名流的上下文管理器。

與輸出流一起使用的示例:

with captured_stdout() as stdout, captured_stderr() as stderr:
    print("hello")
    print("error", file=sys.stderr)
assert stdout.getvalue() == "hello\n"
assert stderr.getvalue() == "error\n"

與輸入流一起使用的示例:

with captured_stdin() as stdin:
    stdin.write('hello\n')
    stdin.seek(0)
    # call test code that consumes from sys.stdin
    captured = input()
self.assertEqual(captured, "hello")

相關用法


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