So you have used Python's "pre built in functions", presumably like this:

file_object = open('filename')
for something in file_object:
    some stuff here

This reads the file by invoking an iterator on the file object which happens to return the next line from the file.

You could instead use:

file_object = open('filename')
lines = file_object.readlines()

which reads the lines from the current file position into a list.

Now, sys.stdin is just another file object, which happens to be opened by Python before your program starts. What you do with that file object is up to you, but it is not really any different to any other file object, its just that you don't need an open.

for something in sys.stdin:
    some stuff here

will iterate through standard input until end-of-file is reached. And so will this:

lines = sys.stdin.readlines()

Your first question is really about different ways of using a file object.

Second, where is it reading from? It is reading from file descriptor 0 (zero). On Windows it is file handle 0 (zero). File descriptor/handle 0 is connected to the console or tty by default, so in effect it is reading from the keyboard. However it can be redirected, often by a shell (like bash or cmd.exe) using syntax like this:

myprog.py < input_file.txt 

That alters file descriptor zero to read a file instead of the keyboard. On UNIX or Linux this uses the underlying call dup2(). Read your shell documentation for more information about redirection (or maybe man dup2 if you are brave).

Answer from cdarke on Stack Overflow
Top answer
1 of 6
49

So you have used Python's "pre built in functions", presumably like this:

file_object = open('filename')
for something in file_object:
    some stuff here

This reads the file by invoking an iterator on the file object which happens to return the next line from the file.

You could instead use:

file_object = open('filename')
lines = file_object.readlines()

which reads the lines from the current file position into a list.

Now, sys.stdin is just another file object, which happens to be opened by Python before your program starts. What you do with that file object is up to you, but it is not really any different to any other file object, its just that you don't need an open.

for something in sys.stdin:
    some stuff here

will iterate through standard input until end-of-file is reached. And so will this:

lines = sys.stdin.readlines()

Your first question is really about different ways of using a file object.

Second, where is it reading from? It is reading from file descriptor 0 (zero). On Windows it is file handle 0 (zero). File descriptor/handle 0 is connected to the console or tty by default, so in effect it is reading from the keyboard. However it can be redirected, often by a shell (like bash or cmd.exe) using syntax like this:

myprog.py < input_file.txt 

That alters file descriptor zero to read a file instead of the keyboard. On UNIX or Linux this uses the underlying call dup2(). Read your shell documentation for more information about redirection (or maybe man dup2 if you are brave).

2 of 6
8

It is reading from the standard input - and it should be provided by the keyboard in the form of stream data.

It is not required to provide a file, however you can use redirection to use a file as standard input.

In Python, the readlines() method reads the entire stream, and then splits it up at the newline character and creates a list of each line.

lines = sys.stdin.readlines()

The above creates a list called lines, where each element will be a line (as determined by the end of line character).

You can read more about this at the input and output section of the Python tutorial.

If you want to prompt the user for input, use the input() method (in Python 2, use raw_input()):

user_input = input('Please enter something: ')
print('You entered: {}'.format(user_input))
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ take-input-from-stdin-in-python
Take input from stdin in Python - GeeksforGeeks
July 12, 2025 - import sys for line in sys.stdin: if 'q' == line.rstrip(): break print(f'Input : {line}') print("Exit") ... The input() can be used to take input from the user while executing the program and also in the middle of the execution. ... # this accepts the user's input # and stores in inp inp = input("Type anything") # prints inp print(inp) ... If we want to read more than one file at a time, we use fileinput.input().
Discussions

What's the difference between sys.stdin.read() and input()?
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 ... More on teamtreehouse.com
๐ŸŒ teamtreehouse.com
2
November 27, 2015
Preferred method of reading from stdin?
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. More on reddit.com
๐ŸŒ r/learnpython
6
3
July 21, 2023
Handling `sys.stdin.read()` in Non-Blocking Mode - Core
Hello Python Community, Iโ€™m seeking your input on an issue related to the behavior of sys.stdin.read() when stdin is set to non-blocking mode and no input is available. This discussion is based on issue #109523 in the Python GitHub repository. During the sprint at EuroPython 2024, I created ... More on discuss.python.org
๐ŸŒ discuss.python.org
5
July 31, 2024
python - How do I read from stdin? - Stack Overflow
If you actually just want to read command-line options, you can access them via the sys.argv list. You will probably find this Wikibook article on I/O in Python to be a useful reference as well. ... The 3rd option is what I was looking for to handle the input at code.golf 2020-12-09T01:34:39.063Z+00:00 ... sys.stdin... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ read-stdin-python
How to Read from stdin in Python | DigitalOcean
August 3, 2022 - Here is a simple program to read user messages from the standard input and process it. The program will terminate when the user enters โ€œExitโ€ message. import sys for line in sys.stdin: if 'Exit' == line.rstrip(): break print(f'Processing Message from sys.stdin *****{line}*****') print("Done")
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.
๐ŸŒ
Python.org
discuss.python.org โ€บ core development
Handling `sys.stdin.read()` in Non-Blocking Mode - Core
July 31, 2024 - Hello Python Community, Iโ€™m seeking your input on an issue related to the behavior of sys.stdin.read() when stdin is set to non-blocking mode and no input is available. This discussion is based on issue #109523 in the Python GitHub repository. During the sprint at EuroPython 2024, I created ...
Find elsewhere
๐ŸŒ
Sentry
sentry.io โ€บ sentry answers โ€บ python โ€บ read user input (stdin) in python
Read user input (STDIN) in Python | Sentry
November 15, 2023 - $ python main.py Enter your name: Jane Doe Hi Jane Doe! If we want to read multiple lines from stdin and donโ€™t need to provide a prompt, we can use sys.stdin from Pythonโ€™s built-in sys module. This allows us to treat stdin like a file. For example: import sys for line in sys.stdin: print(f"Received: {line.strip()}") We could then pipe a file (lines.txt) into our script: python stdin_reader.py < lines.txt ยท
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ sys.html
sys โ€” System-specific parameters and functions
They are used during finalization, and could be useful to print to the actual standard stream no matter if the sys.std* object has been redirected. It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object. ... Under some conditions stdin, stdout and stderr as well as the original values __stdin__, __stdout__ and __stderr__ can be None.
๐ŸŒ
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.
๐ŸŒ
Stack Abuse
stackabuse.com โ€บ reading-from-stdin-in-python
Reading from stdin in Python
August 28, 2023 - Python, like most programming languages, provides a few different ways to read from stdin. We'll explore a couple of the most common methods in the following sections. The sys.stdin object in Python is a file-like object that acts as the stdin stream for the Python program.
๐ŸŒ
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: import sys for line in sys.stdin: print(line) *Please note that input() returns the user input as a string, so if you want to use the input as a number, ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ difference-between-input-and-sys-stdin-readline
Difference between input() and sys.stdin.readline() - GeeksforGeeks
October 29, 2021 - Stdin stands for standard input which is a stream from which the program reads its input data. This method is slightly different from the input() method as it also reads the escape character entered by the user.
Top answer
1 of 6
78

For UNIX based systems (Linux, Mac):

Hello, you can type : Ctrld

Ctrld closes the standard input (stdin) by sending EOF.

Example :

>>> import sys
>>> message = sys.stdin.readlines()
Hello
World
My
Name
Is
James
Bond
# <ctrl-d> EOF sent
>>> print message
['Hello\n', 'World\n', 'My\n', 'Name\n', 'Is\n', 'James\n', 'Bond\n']

For Windows :

To send EOF on Windows, type Ctrlz

2 of 6
7

This is an old question but it needs an update about Windows and different keyboard layouts.

If neither CTRL + Z nor CTRL + D ** work for you on Windows and and you're wandering what is going on do this:

  • check if you are using default english keyboard layout
  • if you do have different, non-default keyboard layout try switching keyboard setting to English in language bar, then try pressing ctrl + z after changes
  • if you're still confused look at the screen, what appears in command line when you press ctrl + z. What symbol do you see? When I was pressing ctrl + z I was seeing this: ^Y, and when by mistake I pressed ctrl + y I've seen this ^Z, i pressed enter and the input was taken, EOF sent.

This is somewhat strange and counterintuitive. I changed keys layout some time ago to include polish characters, but all the common keys are left unchanged, z still maps to z when I use the keyboard normally, normally ctrl + z does nothing in my keyboard, so I shouldn't be changed. But apparently in cmd it works differently, in order to have default link between ctrl and z I have to switch to default layout, or use control y to sent EOF.

๐ŸŒ
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.

๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How to read 1MB of input from stdin? - Python Help - Discussions on Python.org
January 7, 2023 - Python sys.stdin.buffer.read() exits when input to stdin is greater than 873816 length. 1MB is 1048576.
๐ŸŒ
Linux Hint
linuxhint.com โ€บ read-from-stdin-in-python
How to Read from stdin in Python โ€“ Linux Hint
Many ways exist in python to read from the standard input. The input() function is the most common way is to read from the standard input, which is a built-in function. The sys.stdin is another way is to read from the standard input the calls input() function internally.
๐ŸŒ
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 - In this article, we will explain how to read input from stdin in Python using the input() function and three other popular methods. These examples will give you a high-level idea of how to read input from the standard input stream in Python ...