EOFError
input() asked for a line and stdin had nothing left — common when a script that expects a keyboard runs in CI, Docker, an online IDE or with piped input.
Demo
import io, sys sys.stdin = io.StringIO('\n'.join(['alice', '42'])) try: answers = [input() for _ in range(2)] finally: sys.stdin = sys.__stdin__ answers
An empty line is not EOF: input() returns '' for it and keeps going. EOFError comes only when stdin has nothing at all left — the third input() on two lines, or the first input() on empty stdin. That is exactly what happens when a script runs with no keyboard attached: stdin is empty (or closed) from the start.
Constructor
| Name | Type | Required | Description |
|---|---|---|---|
| *args | object | no | The message; input() passes "EOF when reading a line", pickle "Ran out of input". |
Attributes
| Attribute | Type | Meaning |
|---|---|---|
| args | tuple | The message tuple, e.g. ('EOF when reading a line',). |
Common patterns
try: name = input('Name: ') except EOFError: name = 'anonymous'
import sys for line in sys.stdin: process(line.rstrip('\n'))
records = [] with open('data.pkl', 'rb') as f: while True: try: records.append(pickle.load(f)) except EOFError: break
Examples
Pitfalls
import io, sys sys.stdin = io.StringIO('a\nb') lines = [] try: line = input() while line != '': lines.append(line) line = input() finally: sys.stdin = sys.__stdin__ lines
import io, sys sys.stdin = io.StringIO('a\nb') lines = [] try: while True: lines.append(input()) except EOFError: pass finally: sys.stdin = sys.__stdin__ lines
import pickle data = pickle.dumps([1, 2, 3])[:5] try: obj = pickle.loads(data) except EOFError: obj = [] obj
import pickle data = pickle.dumps([1, 2, 3])[:5] try: obj = pickle.loads(data) except (EOFError, pickle.UnpicklingError): obj = [] obj
When to use
- Detecting the end of interactive or piped input to input()
- Ending a loop over consecutive pickle.load() calls
- Raising it from your own reader when a stream ends before a complete record
- Reading files line by line → iterate the file; it stops at EOF by itself
- Scripts meant for automation → take arguments (argparse) or read sys.stdin instead of prompting
Notes
FAQ
input() found stdin already at end-of-file. Common causes: the script runs where there is no keyboard (CI jobs, cron, Docker without -it, some online IDEs and editor 'Run' buttons that do not attach a console), input is piped from a file with fewer lines than the script asks for, or the user pressed Ctrl-D (Ctrl-Z Enter on Windows). Either provide the input (echo 'alice' | python script.py, docker run -it), or catch EOFError and use a default.