The more pythonesque way is to use input() if you are accepting text from a human and use sys.stdin if you are reading a lot of redirected text, say from a pipe. Answer from Deleted User on reddit.com
🌐
DigitalOcean
digitalocean.com › community › tutorials › read-stdin-python
How to Read from stdin in Python | DigitalOcean
August 3, 2022 - Python stdin Example · 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") Output: Python input() Read From stdin ·
Discussions

io - Python reading from stdin while doing other tasks - Software Engineering Stack Exchange
I am trying to write a system log parser. It will receive messages from the FreeBSD syslog daemon through stdin. It will use those messages to determine if an IP address should be banned or not. The More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
May 9, 2013
Python wait until data is in sys.stdin - Stack Overflow
If i only use a for loop the script will exit, because at a point there is no data in sys.stdin and apache2 will say ohh your script exited unexpectedly. If i use a while true loop my script will use 100% cpu usage. ... It sounds like your problem lies elsewhere then. In the python script it ... More on stackoverflow.com
🌐 stackoverflow.com
python - How do I read from stdin? - Stack Overflow
+1 for open(0). I have an ... to use stdin as file. So I do not want to write extra code. 2022-12-25T14:18:43.5Z+00:00 ... is very simple and pythonic, but it must be noted that the script will wait until EOF before starting to iterate on the lines of input. This means that tail -f error_log | myscript.py will not process lines as expected. ... while 1: try: line ... More on stackoverflow.com
🌐 stackoverflow.com
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
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!

🌐
GitHub
gist.github.com › fyears › 4161739
python stdin example · GitHub
# stdin.py def read_in(): return {x.strip() for x in sys.stdin} def main(): lines = read_in() for line in lines: print(line) if __name__ == '__main__': main() In the console, run this to see above working. Why this works is also explained here · >>>Python3.5 stdout.py >>>cat out.log | Python3.5 stdin.py
Find elsewhere
🌐
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:
🌐
Better Stack
betterstack.com › community › questions › how-to-read-stdin-in-python
How do I read from stdin in Python? | Better Stack Community
October 5, 2023 - In Python, you can read from standard input (stdin) using the input() function. This function blocks execution and waits for the user to enter some text, which is then returned as a string.
Top answer
1 of 2
15
Hi Brendan, in this video the "sys.stdin.read()" is described as being able to take a newline and finish your entry with Control+D. input() would finish your entry with the "Enter" key being pressed on your keyboard, so you couldn't include a newline in your data input that way.
2 of 2
6
That sounds roughly correct, however input() also takes as an argument a string to use as a prompt, while sys.stdin.read() takes the length to read into the user-entered string as an optional argument instead (and provides no prompt - in the video, a print() was provided to serve as a prompt instead). For more information on what these functions are doing though, you can use help(sys.stdin.read) and help(input) while in a Python interpreter, or visit https://docs.python.org/2/library/sys.html for more information about the sys library and its methods, including stdin. As for your other question, we have to import the sys library because sys.stdin.read() is reflecting a method that exists only in that library. The reason it's so long is that we just imported the library, so we have to reference sys at the beginning of any function from that library, then .stdin() is a function with a .read() method available in it (among others) - so it wouldn't make sense to just say read() without telling Python which read() method you're asking it to use (other functions, including one you write yourself, could include their own read() methods). If you mean to say why sys is a library instead of being ready for use in Python all the time, that's likely because it would be inefficient for Python to keep libraries loaded if they aren't being used, so the library is kept optional.
🌐
GeeksforGeeks
geeksforgeeks.org › python › take-input-from-stdin-in-python
Take input from stdin in Python - GeeksforGeeks
July 12, 2025 - Python3 · import sys for line in sys.stdin: if 'q' == line.rstrip(): break print(f'Input : {line}') print("Exit") Output · The input() can be used to take input from the user while executing the program and also in the middle of the execution. Python3 · # this accepts the user's input # and stores in inp inp = input("Type anything") # prints inp print(inp) Output: If we want to read more than one file at a time, we use fileinput.input().
🌐
Stack Abuse
stackabuse.com › reading-from-stdin-in-python
Reading from stdin in Python
August 28, 2023 - While reading from stdin in Python, you might encounter an EOFError. This error is raised when one of the built-in functions like input() hits an end-of-file condition (EOF) without reading any data. This usually happens when you run a program that's expecting input but doesn't receive any.
🌐
Spark By {Examples}
sparkbyexamples.com › home › python › how do you read from stdin in python?
How do you read from stdin in Python? - Spark By {Examples}
May 31, 2024 - If you don’t provide a prompt string as an argument to input(), Python will still wait for the user to enter input, but there will be no visible prompt on the console. The stdin is a variable in the sys module in Python that can be used to read from the console or stdin.
🌐
Quora
quora.com › How-do-I-take-input-from-STDIN-in-Python
How to take input from STDIN in Python - Quora
Studied Python (programming language) · 8y · Suppose we have to take the following input : Input: 2 (Test cases) 3 (Size of array) 0 1 1 (input) 3 · 0 1 2 · We can use following script : import sys · # To store no of test cases here (2). t=int(sys.stdin.readline()) # # To store input here (0 1 1) and (0 1 2). l=[] while t : #To store the size of array here (3).
🌐
Reddit
reddit.com › r/learnpython › [beginners] intro to reading from standard input
r/learnpython on Reddit: [BEGINNERS] Intro to reading from standard input
January 6, 2018 -

Hey everyone, I just want to talk about reading in data from standard input and the 4 main ways it can be done.

I'm not going to talk about the input() or raw_input() functions today, instead ill be talking about how to read from standard input using the sys module.

To get access to the sys module we first need to import it

import sys

Ok now we have access to this module, there are 3 ways to read from standard input:

  1. sys.stdin.read([size])

  2. sys.stdin.readline()

  3. sys.stdin.readlines()

Lets look at how all of these work first and the ways to use them.

First off we can read lines directly from the console, this will look something like this

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

$ python3 stdin.py
Line1
Line 2
**END**
Line 1
Line 2

Our lines variable looks like this: "Line1\nLine2"

Here when we run our program, it waits until it we pass some data through the console window. We specify end of input using ctrl+z on windows and I believe ctrl+d on linux.

The sys.stdin.read() function also has an optional parameter for the size of the data we want to read. For example if we pass 10 then it reads 10 characters including any newline characters.

The read() function will read everything, or the size of data specified, and return it as one string. This is useful for small amounts of data but if we read large files this way, it can use up a lot of memory.

The second way is sys.stdin.readline() which is self explanatory and reads a single line from standard input with a newline character at the end.

line = sys.stdin.readline()
print(line)

$ python3 stdin.py
hello
hello

The next way is sys.stdin.readlines(). I find myself using this way most often. With this way, we read lines from the console and are returned a list containing all the lines we entered.

lines = sys.stdin.readlines()
print(lines)

$ python3 stdin.py
line1
line2
line3
['line1\n', 'line2\n', 'line3\n']

This is very useful if we wish to process a file line by line although, we do have a large list sitting in memory which we may not want with large files. I will show you how to read from files in a moment.

Reading from files:

To read from a file we can do this a couple of ways, we can open and read the file within our program.

with open('FILENAME', [rw]) as our_file:
    for line in our_file:
        print(line)

The optional [rw] specifies whether we wish to open the file for reading, r or writing, w. This will work depending on the access permission on the file. You can check this on linux from the command line by navigating to your directory where the file is and typing:

$ ls -l

This will display the access permissions of the file in that directory.

An error will be thrown if you try to read or write without having permission to do so.

If the file name you entered doesn't exist, an empty file will be created for you.

The use of with open() here is very useful as it closes our file for us when we are finished.

Another way to read a file is passing it at the command line

$ python3 stdin.py < FILENAME.txt

Presuming FILENAME.txt looks like this:

Line 1
Line 2
Line 3

Running the following program, we get the following output:

import sys

lines = sys.stdin.readlines()
print(lines)

$ python3 stdin.py < FILENAME.txt
['Line 1\n', 'Line 2\n', 'Line 3']

I dont want to talk to much about the different ways of reading and writing files as I only wanted to talk about the different methods we have available to use for reading so I wont discuss any further ways of reading.

If we wish to strip the newline characters from our lines we can use the strip() method, I'm going to use a list comprehension here as it is a good example of their usage:

lines = [line.strip() for line in sys.stdin.readlines()]
print(lines)

$ python3 stdin.py < FILENAME.txt
['Line 1', Line 2', 'Line 3']

Whats the list comprehension doing? It uses a for loop to loop through each line in standard input, takes each line and strips it then appends it to our list, lines.

Now our newline characters are gone.

We covered a fair bit of stuff here and got the chance to see some extra things in use such as list comprehensions. If you found anything here confusing, play around with it yourself, after all its one of the best ways to learn.