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
🌐
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:
Find elsewhere
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.
🌐
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.
🌐
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).
🌐
Python Morsels
pythonmorsels.com › reading-from-standard-input
Reading from standard input - Python Morsels
October 30, 2023 - import sys if len(sys.argv) == 2: file = open(sys.argv[1]) elif len(sys.argv) == 1: file = sys.stdin else: sys.exit("This program accepts one filename to look for TODOs in") with file: todo_count = file.read().count("TODO") print(f"{todo_count} TODOs found") So when our Python process is launched from the terminal with another process piped into it, reading from standard input will read from the output of that other process, instead of prompting the user for input: