Python Glossary Русский

all Python 3systerm

sys.stdin

streams

The standard input stream — a text file object. input() and the for line in sys.stdin loop read from it.

Syntax

import sys
for line in sys.stdin:
    ...

Lines arrive with their trailing '\n', so .strip() is almost always needed — otherwise a comparison with the expected answer fails on an invisible character. for line in sys.stdin stops only at end of input (Ctrl+D in a terminal, Ctrl+Z then Enter on Windows), which is how problems with an unknown number of lines are read. sys.stdin.read() takes the whole input as one string.

Examples

import io, sys
sys.stdin = io.StringIO('3 4\n5 6\n')  # так ввод подставят тесты: python main.py < input.txt
for line in sys.stdin:
    a, b = map(int, line.split())
    print(a + b)  # → 7 / 11
import io, sys
sys.stdin = io.StringIO('hello\n')
line = sys.stdin.readline()
print(repr(line), repr(line.strip()))  # → 'hello\n' 'hello'

See also

Open in the full glossarydocs.python.orgReport an inaccuracy