How to finish sys.stdin.readlines() input?
Asked Answered
G

6

42

This might be a silly question, but as I can't find an answer, I have to ask it.

In interactive python I want to process a message which i get with:

>>> message = sys.stdin.readlines()

Everything works fine, but... how to stop it from getting an input and make it save into message variable? Stopping with ctrl+c stops whole process so there is no input to be saved anywhere. I guess there's an easy answer I just can't find...

Gluten answered 5/4, 2011 at 8:26 Comment(0)
M
75

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

Maria answered 5/4, 2011 at 8:30 Comment(0)
S
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.

Sundog answered 29/7, 2013 at 12:52 Comment(0)
H
7

On windows simply do CTRL+Z and press enter

Highclass answered 3/3, 2017 at 10:8 Comment(0)
N
6

Use CTRL-D.

message = sys.stdin.readlines()
abc
def
<CTRL-D>

# message == ['abc\n', 'def\n']
Nolannolana answered 5/4, 2011 at 8:30 Comment(0)
A
3

If you are a Mac user, please use command + D. It works!

Aftersensation answered 7/1, 2021 at 13:56 Comment(0)
C
1

I tested that in VS code terminal.

After using this command:

for line in stdin:

I input many lines of data. Keep pressing Enter does not work now.

Solution:

Press Ctrl + Z, you will see ^Z in the terminal.

Then you have to press Enter to finish.

Cephalic answered 1/10, 2022 at 21:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.