Python:Python Multi-Line Stdin and sys.stdin Input Guide
Python•Multi-Line Stdin

Python Multi-Line Stdin and sys.stdin Input Guide

When solving coding challenges or testing scripts in Compilra CPython 3.12, stdin is supplied upfront before clicking Run rather than typed interactively. Learning how to read a case count and parse multiple lines cleanly with sys.stdin keeps your programs fast and predictable.

Syntax

lines = sys.stdin.read().splitlines()

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
sys.stdin.read()strReads the entire pre-supplied standard input stream as a single string.
splitlines()list[str]Splits multi-line text across both LF and CRLF line endings cleanly.
input()strReads one line at a time from stdin; raises EOFError when no lines remain.

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing Python locally:

import sys

lines = [line.strip() for line in sys.stdin.read().splitlines() if line.strip()]
count = int(lines[0])

for idx in range(1, count + 1):
    name, scores_raw = lines[idx].split(":")
    scores = [float(x) for x in scores_raw.split()]
    avg = sum(scores) / len(scores)
    print(f"#{idx} {name.strip()}: avg = {avg:.1f}")
Pre-Supplied Stdin (Input):
3
Alice: 85 90 95
Bob: 70 82 82
Carol: 90 95
Expected Output:
#1 Alice: avg = 90.0
#2 Bob: avg = 78.0
#3 Carol: avg = 92.5

How It Works: Step-by-Step

  • Line 3: Reads all pre-supplied stdin text with sys.stdin.read(), splits lines, and skips blank lines.
  • Line 4: Parses the first line as the integer record count.
  • Lines 6-10: Splits each record on ":", converts space-separated scores to floats, and prints each average.

Key Concepts

  • In Compilra, enter all input lines in the Standard Input (stdin) box before clicking Run—stdin is sent upfront, not typed live while running.
  • sys.stdin.read().splitlines() handles both Unix (\n) and Windows (\r\n) line endings without leaving trailing newline characters.
  • For huge inputs, sys.stdin.read().split() or iterating directly over sys.stdin avoids repeated prompt overhead from input().

Common Mistake: Calling input() more times than lines exist in Stdin

Calling input() after the pre-supplied stdin buffer is exhausted raises EOFError: EOF when reading a line.

❌ Incorrect
n = int(input())
for _ in range(n + 1):
    print(input()) # Raises EOFError on extra iteration
✅ Correct
import sys
lines = sys.stdin.read().splitlines()
for line in lines:
    print(line)

Related Python Tutorials & Compiler

Run and test Python on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

Python Online Compiler