You can wrap stdin to strip the newlines; if you can strip all trailing whitespace (usually okay), then it's just:

for name in map(str.rstrip, sys.stdin):
    ...

You're on Py3, so that works as is; if you're on Py2, you'll need to add an import, from future_builtins import map, so you get a lazy, generator based map (that yields the lines as they're requested, rather than slurping stdin until it ends, then returning a list of all the lines).

If you need to limit to newlines, a generator expression can do it:

for name in (line.rstrip("\r\n") for line in sys.stdin):
    ...

or with an import to allow map to push work to C layer for (slightly) faster code (a matter of 30-some nanoseconds per line faster than the genexpr, but still 40 ns per line slower than the argumentless option at the top of this answer):

from operator import methodcaller

for name in map(methodcaller('rstrip', '\r\n'), sys.stdin):
    ...

Like the first solution, on Py2, make sure to get the map from future_builtins.

Answer from ShadowRanger on Stack Overflow
Top answer
1 of 9
22

The following should just work.

import sys
for line in sys.stdin:
    # whatever

Rationale:

The code will iterate over lines in stdin as they come in. If the stream is still open, but there isn't a complete line then the loop will hang until either a newline character is encountered (and the whole line returned) or the stream is closed (and the whatever is left in the buffer is returned).

Once the stream has been closed, no more data can be written to or read from stdin. Period.

The reason that your code was overloading your cpu is that once the stdin has been closed any subsequent attempts to iterate over stdin will return immediately without doing anything. In essence your code was equivalent to the following.

for line in sys.stdin:
    # do something

while 1:
    pass # infinite loop, very CPU intensive

Maybe it would be useful if you posted how you were writing data to stdin.

EDIT:

Python will (for the purposes of for loops, iterators and readlines() consider a stream closed when it encounters an EOF character. You can ask python to read more data after this, but you cannot use any of the previous methods. The python man page recommends using

import sys
while True:
    line = sys.stdin.readline()
    # do something with line

When an EOF character is encountered readline will return an empty string. The next call to readline will function as normal if the stream is still open. You can test this out yourself by running the command in a terminal. Pressing ctrl+D will cause a terminal to write the EOF character to stdin. This will cause the first program in this post to terminate, but the last program will continue to read data until the stream is actually closed. The last program should not 100% your CPU as readline will wait until there is data to return rather than returning an empty string.

I only have the problem of a busy loop when I try readline from an actual file. But when reading from stdin, readline happily blocks.

2 of 9
4

This actually works flawlessly (i.e. no runnaway CPU) - when you call the script from the shell, like so:

tail -f input-file | yourscript.py

Obviously, that is not ideal - since you then have to write all relevant stdout to that file -

but it works without a lot of overhead! Namely because of using readline() - I think:

while 1:
        line = sys.stdin.readline()

It will actually stop and wait at that line until it gets more input.

Hope this helps someone!

Discussions

python - Loop on sys.stdin - Stack Overflow
If that is inside of a generator, a simple for loop can be constructed: def read_stdin(): readline = sys.stdin.readline() while readline: yield readline readline = sys.stdin.readline() for line in read_stdin(): line = line.split() print(line) ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... 1 Python ... More on stackoverflow.com
🌐 stackoverflow.com
May 24, 2017
How do I process a multiple line input from "for line in sys.stdin:"?
Firstly, note that the split method returns a new list object, so need to try to convert it to a list i.e. you only need line.split() and not list(line.split()). Secondly, it is not clear from what you've written how the standard input is being presented. So, lets assume you want all of the lines of data from sys.stdin and every space seperated entry in any line should be another number. Thirdly, don't forget you need to convert from str to int. Example, using a data to reference a str standing in for sys.stdin: data = """1 2 3 4""" nums = [] # a new empty list to hold the numbers for line in data: # each line of standard input for n in line.split(): # each space seperated entry in a line nums.append(int(n)) # cast str to int and append to list print(nums) PS. list comprehension can be used to write this in a more compact form but validation should also be added in case data is entered that does not provide a valid number entry More on reddit.com
🌐 r/learnpython
15
4
September 28, 2024
Python sys.stdin.read(1) in a while(True) loop consistently executes 1 time getting input and multiple times not getting input - Stack Overflow
How do I get Python to read one char at a time in an infinite loop? ... I lied. In PyDev Eclipse calling flush() makes 1 time getting user input and 1 time skipping user input (instead of 2 times). Adding multiple flush() has no other effect. ... Problem is probably due to flushing of stdin since ... More on stackoverflow.com
🌐 stackoverflow.com
python - reading from stdin, while consuming no more memory than needed - Stack Overflow
I am trying to create a line-by-line filter in python. However, stdin.readlines() reads all lines in before starting to process, and python runs out of memory (MemoryError). How can I have just one More on stackoverflow.com
🌐 stackoverflow.com
August 21, 2015
🌐
Linux Hint
linuxhint.com › read-from-stdin-in-python
How to Read from stdin in Python – Linux Hint
It calls the input() function internally and adds ‘\n‘ after taking the input. Create a python file with the following script to check the use of the sys.stdin to take standard input. Here, the ‘for-in’ loop is used to take the input from the user infinite times until the user wants ...
🌐
Reddit
reddit.com › r/learnpython › how do i process a multiple line input from "for line in sys.stdin:"?
r/learnpython on Reddit: How do I process a multiple line input from "for line in sys.stdin:"?
September 28, 2024 -

I recently took a coding assessment where I was tasked to compute the square of the input which is relatively easy. The issue was that the input was a multiple line input:
7
16

and the expected output is
49
256

The given code was

for line in sys.stdin:
    # your code here
    print(line, end="")

I tried to do ls = list(line.split()) but ls[0] is
['7']
['16']
and ls[1] is None

I also tried ls = list(line.split('\n')) but ls is
['7', '']
['16', '']

So how was I supposed to process the input to get ['7', '16'] rather than a 2 dimensional list?

From there I know how continue with make it an integer using map, creating a for loop for each item of the list and printing the square of each item.

I dont have a picture of the question since I was monitored on webcam but this is roughly what I remembered from the question.

edit: It was an online assessment platform so I am not sure exactly how the input was written as (like the raw input). Also I can only modify the code inside for line in sys.stdin:

Also, does anyone know how to write the input for sys.stdin using jupyternotebook such that I can practice this problem?

🌐
Stack Abuse
stackabuse.com › reading-from-stdin-in-python
Reading from stdin in Python
August 28, 2023 - In Python, reading multiple lines from stdin can be accomplished in a couple of ways. One common approach is to use a for loop with sys.stdin.
🌐
Learner
ahmedgouda.hashnode.dev › user-input-and-while-loops-in-python
User Input and While Loops in Python - Learner - Hashnode
May 8, 2022 - You can use the break statement in any of Python’s loops. For example, you could use break to quit a for loop that’s working through a list or a dictionary. Rather than breaking out of a loop entirely without executing the rest of its code, ...
Find elsewhere
🌐
DigitalOcean
digitalocean.com › community › tutorials › read-stdin-python
How to Read from stdin in Python | DigitalOcean
August 3, 2022 - Hi Processing Message from sys.stdin *****Hi ***** Hello Processing Message from sys.stdin *****Hello ***** Exit Done ... Notice the use of rstrip() to remove the trailing newline character so that we can check if the user has entered “Exit” message or not. We can also use Python input() function to read the standard input data. We can also prompt a message to the user. Here is a simple example to read and process the standard input message in the infinite loop, unless the user enters the Exit message. while True: data = input("Please enter the message:\n") if 'Exit' == data: break print(f'Processing Message from input() *****{data}*****') print("Done")
🌐
Codeforces
codeforces.com › blog › entry › 54228
How to read input until EOF in python? - Codeforces
How to read input until EOF in python? By rgkbitw, history, 8 years ago, I came across this problem in UVa OJ. 272-Text Quotes · Well, the problem is quite trivial. But the thing is I am not able to read the input. The input is provided in the form of text lines and end of input is indicated by EOF. In C/C++ this can be done by running a while loop: while( scanf("%s",&s)!=EOF ) { //do something } How can this be done in python .?
🌐
Stack Overflow
stackoverflow.com › questions › 36606909 › python-sys-stdin-for-loop-not-working
python sys.stdin for loop not working - Stack Overflow
April 13, 2016 - It stops after the first interation because you are assigning the value being iterated over in the definition of the for loop. You can see this by doing sys.stdin.readline() in the interpreter. This means your loop is equivalent to ... In your while loop, it will keep asking for more inputs, and so your code works.
🌐
PythonHow
pythonhow.com › how › read-from-stdin-standard-input
Here is how to read from stdin (standard input) in Python
import sys input_text = sys.stdin.read() print("The input was:", input_text)You can also use file object to read from stdin in python like this: ... *Please note that input() returns the user input as a string, so if you want to use the input as a number, you'll need to convert it using int() or float(). ... Solve Python exercises and get instant AI feedback on your solutions. Try ActiveSkill for Free →
🌐
OpenClass
open.openclass.ai › resource › assignment-5ff7aa8ad492f5deb5b37e8b › question-5ffe7f678fa4e8b2b96dbdab › feedback › share
Write code that iterates through and prints unlimited lines of STDIN until ~BREAK~ is seen. - Control Flow in Python Assignment - Use this assignment in your class! - OpenClass
August 26, 2022 - Python · You passed all test cases! STDIN · The first line The second line The third line ~BREAK~ Expected STDOUT · The first line The second line The third line · Your STDOUT · The first line The second line The third line · STDIN · ~BREAK~ Expected STDOUT ·
🌐
PhoenixNAP
phoenixnap.com › home › kb › devops and development › how to read from stdin in python
How to Read From stdin in Python | phoenixNAP KB
June 5, 2025 - import fileinput for f in fileinput.input(): print(f) ... The code goes through the list of files and prints the file contents to the console. ... You now know three different methods to read input from stdin in Python.
🌐
Python Land
python.land › home › introduction to python › python for loop and while loop
Python For Loop and While Loop • Python Land Tutorial
September 5, 2025 - A Python for-loop allows you to repeat the execution of a piece of code. This tutorial shows how to create proper for-loops and while loops
🌐
Drbeane
drbeane.github.io › python › pages › while_loops.html
While Loops — Python Programming
The syntax for creating a while loop is as follow: while condition: code to be executed each iteration · The condition in a while statement should be an expression that evaluates to a Boolean value. When Python encounters a while loop, it will check to see if the condition evaluates to True.