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
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.
Discussions

python - What does sys.stdin read? - Stack Overflow
I get how to open files, and then use Python's pre built in functions with them. But how does sys.stdin work? More on stackoverflow.com
๐ŸŒ stackoverflow.com
Confused about stdin and stdout
stdin, stdout and stderr have nothing to do with python specifically. These are what we call the main pathways for data to flow in and out of any CLI program. As a beginner, you don't need to worry about them at all, because python wraps them in easy to use input() (for stdin) and print() (for stdout) functions. But for advanced users and very rare usecases we can use the sys modules to access them. https://en.wikipedia.org/wiki/Standard_streams More on reddit.com
๐ŸŒ r/learnpython
6
1
September 16, 2022
What's the difference between input() and sys.stdin.readline()? - Python - Learn Code Forum
basically that is my question hahahahah I create a function and test both, apparently is the same thing. would like to know if it really is the same or is just my lack of knowledge on the subject. My code: import sys #3 moon weight program #using sys.stdin.readline() mini-program using prompt ... More on forum.learncodethehardway.com
๐ŸŒ forum.learncodethehardway.com
3
0
April 13, 2018
[BEGINNERS] Intro to reading from standard input
This is very informative! Thank you so much! More on reddit.com
๐ŸŒ r/learnpython
1
18
January 6, 2018
Top answer
1 of 2
5

Clarification through Code Examples

I've been asking myself the same question, so I came up with these two snippets, which clarify how sys.stdin and input() differ by emulating the latter with the former:

import sys

def my_input(prompt=''):
  print(prompt, end='') # prompt with no newline
  for line in sys.stdin:
    if '\n' in line: # We want to read only the first line and stop there
      break
  return line.rstrip('\n')

Here is a more condensed version:

import sys

def my_input(prompt=''):
  print(prompt, end='')
  return sys.stdin.readline().rstrip('\n')

Both these snippets differ from the input() function in that they do not detect the End Of File (see below).

Clarification through Documentation

This is how the official documentation describes the function input():

input([prompt])

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

And here's how sys.stdin is described:

sys.stdin

File object used by the interpreter for standard input.
stdin is used for all interactive input (including calls to input());
These streams (sys.stdin, sys.stdout and sys.stderr) are regular text files like those returned by the open() function. [...]

So whereas input() is a function, sys.stdin is an object (a File object). As such, it has a number of attributes, which you can explore in the interpreter, with:

> dir(sys.stdin)

['_CHUNK_SIZE',
 '__class__',
 '__del__',
 '__delattr__',
 '__dict__',
 '__dir__',

  ...

 'truncate',
 'writable',
 'write',
 'write_through',
 'writelines']

and which you can display individually, for instance:

> sys.stdin.mode
r

It also has methods, such as readline(), which "reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesnโ€™t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline." (1)

Full implementation

This last method allows us to fully emulate the input() function, including its EOF Exception error:

def my_input(prompt=''):
  print(prompt, end='')
  line = sys.stdin.readline()
  if line == '': # readline() returns an empty string only if EOF has been reached
    raise EOFError('EOF when reading a line')
  else:
    return line.rstrip('\n')
2 of 2
1

Here's something to get you started:

The builtin function input reads a line of input from the standard input stream, optionally with a message prompt. Be careful with the prompt, though, because the result of:

result = input('Do you want to do whatever? ')  ## doesn't work how you'd expect
if result.lower() in ('y', 'ye', 'yes', 'yup', 'ya'):
    do_whatever()
    ...
else:
    do_something_else()
    ...

..will include the prompt string as well (and so will never be equal to 'y'/'yes'/etc). In my opinion, it is better to print the prompt string first and then call input with no args, like so:

print('Do you want to do whatever?')
result = input()  ## notice that there is no prompt string passed to input()
if result.lower() in ('y', 'ye', 'yes', 'yup', 'ya'):
    do_whatever()
    ...
else:
    do_something_else()
    ...

So, to recap, the builtin function input reads input from the standard input stream (sys.stdin), and the builtin function print prints output to the standard output stream (sys.stdout). There's a third one as well, the standard error stream (sys.stderr), to which unhandled exceptions get printed.

Usually, you don't have to worry about it too much. It's just when building IDEs and frameworks and such.

๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ sys.html
sys โ€” System-specific parameters and functions
Non-character devices such as disk files and pipes use the system locale encoding (i.e. the ANSI codepage). Non-console character devices such as NUL (i.e. where isatty() returns True) use the value of the console input and output codepages at startup, respectively for stdin and stdout/stderr.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ difference-between-input-and-sys-stdin-readline
Difference between input() and sys.stdin.readline() - GeeksforGeeks
July 12, 2025 - 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.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ read-stdin-python
How to Read from stdin in Python | DigitalOcean
August 3, 2022 - This function works in the same way as sys.stdin and adds a newline character to the end of the user-entered data. import fileinput for fileinput_line in fileinput.input(): if 'Exit' == fileinput_line.rstrip(): break print(f'Processing Message from fileinput.input() *****{fileinput_line}*****') print("Done") ... Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. ... Java and Python Developer for 20+ years, Open Source Enthusiast, Founder of https://www.askpython.com/, https://www.linuxfordevices.com/, and JournalDev.com (acquired by DigitalOcean).
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))
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 provides a few methods for reading from stdin in different contexts. The simplest and most commonly used is the default input function, which prompts the user to enter a line into stdin and returns it as a string once they press Enter. For example: name = input("Enter your name: ") print(f"Hi {name}!") ... 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.
๐ŸŒ
AskPython
askpython.com โ€บ home โ€บ python โ€“ stdin, stdout, and stderr
Python - stdin, stdout, and stderr - AskPython
February 16, 2023 - Now that we know a little bit about stdin, let us move to stdout. For the output file object, we use sys.stdout. It is similar to sys.stdin, but it directly displays anything written to it to the Console.
๐ŸŒ
Learn Code Forum
forum.learncodethehardway.com โ€บ python
What's the difference between input() and sys.stdin.readline()? - Python - Learn Code Forum
April 13, 2018 - basically that is my question hahahahah I create a function and test both, apparently is the same thing. would like to know if it really is the same or is just my lack of knowledge on the subject. My code: import sys #3 moon weight program #using sys.stdin.readline() mini-program using prompt def moon_weight_sys(): #print("What is your weight on earth?
๐ŸŒ
Quora
quora.com โ€บ What-is-the-difference-between-input-and-sys-stdin-in-Python
What is the difference between input() and sys.stdin in Python? - Quora
Answer: input() prompts the user to enter an input. It is implemented in Python 3 and you cannot use it in Python 2 (throws a syntax error). Instead of just reading the input, it even tries to evaluate the read input to appropriate datatype. So the read input is mostly of the same datatype as ent...
๐ŸŒ
Python Morsels
pythonmorsels.com โ€บ reading-from-standard-input
Reading from standard input - Python Morsels
October 30, 2023 - Python also includes a readable file-like object for prompting users for input. This file-like object is called standard input: >>> sys.stdin <_io.TextIOWrapper name='<stdin>' mode='r' encoding='utf-8'>
๐ŸŒ
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.

๐ŸŒ
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.
Top answer
1 of 5
19

stdin and stdout are file-like objects provided by the OS. In general, when a program is run in an interactive session, stdin is keyboard input and stdout is the user's tty, but the shell can be used to redirect them from normal files or piped output from and input to other programs.

input() is used to prompt the user for typed input. In the case of something like a programming puzzle, it's normally assumed that stdin is redirected from a data file, and when the input format is given it's usually best to use sys.stdin.read() rather than prompting for input with input(). input() is intended for interactive user input, it can display a prompt (on sys.stdout) and use the GNU readline library (if present) to allow line editing, etc.

print() is, indeed, the most common way of writing to stdout. There's no need to do anything special to specify the output stream. print() writes to sys.stdout if no alternate file is given to it as a file= parameter.

2 of 5
5

When you run your Python program, sys.stdin is the file object connected to standard input (STDIN), sys.stdout is the file object for standard output (STDOUT), and sys.stderr is the file object for standard error (STDERR).

Anywhere in the documentation you see references to standard input, standard output, or standard error, it is referring to these file handles. You can access them directly (sys.stdout.write(...), sys.stdin.read() etc.) or use convenience functions that use these streams, like input() and print().

For the Spotify puzzle, the easiest way to read the input would be something like this:

import sys
data = sys.stdin.read()

After these two lines the input for your program is now in the str data.

๐ŸŒ
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. For example: ... Alternatively, you can use the sys.stdin object, which is a file-like object that can be read from using the standard file I/O methods, such as read(), readline(), and readlines().
๐ŸŒ
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 - Reads user input from the keyboard (sys.stdin). Removes new lines from the user entry (rstrtip()). Prints back the entered message by appending an f-string. Exits the for loop (break). The program expects user input, prints the entered text stream, and returns to the command line. The second way to read input from stdin in Python is with the built-in input() function.