So, took your code out of the function and ran some tests.

import sys
buffer = []
while run:
    line = sys.stdin.readline().rstrip('\n')
    if line == 'quit':
        run = False
    else:
        buffer.append(line)

print buffer

Changes:

  • Removed the 'for' loop
  • Using 'readline' instead of 'readlines'
  • strip'd out the '\n' after input, so all processing afterwards is much easier.

Another way:

import sys
buffer = []
while True:
    line = sys.stdin.readline().rstrip('\n')
    if line == 'quit':
        break
    else:
        buffer.append(line)
print buffer

Takes out the 'run' variable, as it is not really needed.

Answer from Wing Tang Wong on Stack Overflow
🌐
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.

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 › 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 this code, we simply use stdin's readline() method to get input from the user. The line is then printed out with the prefix "Received: ". If you run this code and type in some input, you'll see that it echoes back each line you enter: $ python read_stdin.py Hello, world! Received: Hello, world! The input() function is a simpler way to read a line of input from stdin.
Top answer
1 of 6
27

stdin.read(1) reads one character from stdin. If there was more than one character to be read at that point (e.g. the newline that followed the one character that was read in) then that character or characters will still be in the buffer waiting for the next read() or readline().

As an example, given rd.py:

from sys import stdin

x = stdin.read(1)
userinput = stdin.readline()
betAmount = int(userinput)
print ("x=",x)
print ("userinput=",userinput)
print ("betAmount=",betAmount)

... if I run this script as follows (I've typed in the 234):

C:\>python rd.py
234
x= 2
userinput= 34

betAmount= 34

... so the 2 is being picked up first, leaving the 34 and the trailing newline character to be picked up by the readline().

I'd suggest fixing the problem by using readline() rather than read() under most circumstances.

2 of 6
11

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

🌐
Reddit
reddit.com › r/learnpython › multi-line input in python 3
r/learnpython on Reddit: Multi-line input in Python 3
June 15, 2019 -

I'm trying to feed a prompt to a GPT-2 model, which is trained on song lyrics. With this model, you can feed it a prompt and it will attempt to finish it. The problem I'm having is that I need for the prompt to be formatted correctly like song lyrics - with each lyric on a newline. Since this model has been trained on formatted lyrics, the prompt needs to look the same to produce above average results.

input() doesn't work, because hitting return submits the text. I've also tried sys.stdin.read() as well and nothing seems to happen, just returns ' '.

Is it because I'm running it in a notebook? I'm only like 8 months deep into this python hobby, so I could be asking for something that can't happen.

Here's the code, would appreciate any ideas you've got.

prompt = input('Input Prompt:')
gpt2.generate(sess,
              length=200,
              temperature=.99,
              prefix= prompt, #this is where the prompt goes
              nsamples=5,
              top_p=.9,
              batch_size=5,
              run_name='run1'
              )
Find elsewhere
🌐
Bobby Hadz
bobbyhadz.com › blog › python-input-multiple-lines
Multiple lines user Input in Python | bobbyhadz
Copied!import sys # 👇️ User must press Ctrl + D (Unix) or Ctrl + Z (Windows) to exit print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit') user_input = sys.stdin.readlines() # 👇️ get list of lines print(user_input) # 👇️ join the list items into a string print(''.join(user_input))
🌐
UltaHost
ultahost.com › knowledge-base › read-from-stdin-python
How to Read From stdin in Python | Ultahost Knowledge Base
March 14, 2025 - In this Python code, sys.stdin.readlines() reads all lines from stdin until the user (ends input with Ctrl+Z and then press enter on Windows). The lines are stored in a list, which you can process as needed.
🌐
Stack Overflow
stackoverflow.com › questions › 67875570 › how-to-modify-sys-stdin-readline-to-read-all-the-input-data-at-the-same-time
python - How to modify sys.stdin.readline() to read all the input data at the same time? - Stack Overflow
def main(): nodes = int(sys.stdin.readline().strip()) tree = [] for i in range(nodes): tree.append(list(map(int, sys.stdin.readline().strip().split()))) if IsBinarySearchTree(tree): print("CORRECT") else: print("INCORRECT") so that instead of ...
🌐
GeeksforGeeks
geeksforgeeks.org › difference-between-input-and-sys-stdin-readline
Difference between input() and sys.stdin.readline() - GeeksforGeeks
October 29, 2021 - # Python program to demonstrate # sys.stdin.readline() import sys name = sys.stdin.readline() print(name) num = sys.stdin.readline(2) print(num) Output: Comment · More infoAdvertise with us · Next Article · How to input multiple values from user in one line in Python?
🌐
Sentry
sentry.io › sentry answers › python › read user input (stdin) in python
Read user input (STDIN) in Python | Sentry
November 15, 2023 - 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.
🌐
Narkive
comp.lang.python.narkive.com › Ou5yKTDE › sys-stdin-readline
sys.stdin.readline()
for sL in sys.stdin.readline(): print sL It does return a full line. *One* line. Then your loop iterates over the characters in that line.
🌐
DigitalOcean
digitalocean.com › community › tutorials › read-stdin-python
How to Read from stdin in Python | DigitalOcean
August 3, 2022 - Internally, it calls the input() function. The input string is appended with a newline character (\n) in the end. So, you can use the rstrip() function to remove it. Here is a simple program to read user messages from the standard input and process it. The program will terminate when the user ...
🌐
CSEstack
csestack.org › home › how to read multiline user input in python 2 and 3?
How to Read Multiline User Input in Python 2 and 3?
April 15, 2019 - Once you complete giving the user input in multiple lines, press ctrl+d. It sends signalEOF to your system. If you are a windows user, use ctrl+z instead of ctrl+d. And enter.” · But still my console is allowing to enter from keyboards .. why ??