Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

How to Read from stdin in Python

Read user input and piped data in Python with input(), sys.stdin and fileinput.

How-To Guides2 min read4 screenshots

stdin (standard input) is where a program reads data from the keyboard or from another program or file through a pipe.

input() for interactive input

# Prompt the user for their name
name = input("Enter your name: ")
print(f"Hello, {name}!")
Reading input with input()

input() reads one line and returns it as a string. Convert it for numbers: age = int(input("Age: ")).

sys.stdin for file-like input

sys.stdin works like a file object.

import sys

print("Enter multiple lines (Ctrl+D to end):")

# Read all lines from stdin
lines = sys.stdin.readlines()

print("You entered:")
print("".join(lines))
Reading all lines with sys.stdin

Press Ctrl+D (Linux and macOS) or Ctrl+Z then Enter (Windows) to end the input.

Read everything at once

import sys

data = sys.stdin.read()
print(f"Characters: {len(data)}")
Reading the whole input with sys.stdin.read

Read line by line

This keeps memory use low for big input:

import sys

for line in sys.stdin:
    print(line.strip().upper())

Read piped data

Save a script as upper.py with the loop above. Then run:

echo "hello world" | python3 upper.py
Piping data into a Python script

or read from a file:

python3 upper.py < notes.txt

fileinput

fileinput reads files named on the command line, or stdin if there are none:

import fileinput

for line in fileinput.input():
    print(line.strip())

Which to use

NeedUse
One value from the userinput()
All textsys.stdin.read()
Big input, line by linefor line in sys.stdin
Files or stdinfileinput

Quick recap

  • input() for a prompt, sys.stdin for piped or long input.