Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read user input until EOF?

My current code reads user input until line-break. But I am trying to change that to a format, where the user can write input until strg+d to end his input.

I currently do it like this:

input = raw_input ("Input: ") 

But how can I change that to an EOF-Ready version?

like image 261
Saphire Avatar asked Jan 20 '14 13:01

Saphire


People also ask

How do you take input until EOF in Python?

read(size=-1, /) method of _io. TextIOWrapper instance Read at most n characters from stream. Read from underlying buffer until we have n characters or we hit EOF. If n is negative or omitted, read until EOF.

How do you specify EOF in Python?

Python doesn't have built-in eof detection function but that functionality is available in two ways: f. read(1) will return b'' if there are no more bytes to read. This works for text as well as binary files. The second way is to use f.

How does Python handle EOF error?

BaseException -> Exception -> EOFError The best practice to avoid EOF in python while coding on any platform is to catch the exception, and we don't need to perform any action so, we just pass the exception using the keyword “pass” in the “except” block.

How do you fix EOFError EOF when reading a line in Python?

This error is sometimes experienced while using online IDEs. This occurs when we have asked the user for input but have not provided any input in the input box. We can overcome this issue by using try and except keywords in Python. This is called as Exception Handling.


1 Answers

In Python 3 you can iterate over the lines of standard input, the loop will stop when EOF is reached:

from sys import stdin  for line in stdin:   print(line, end='') 

line includes the trailing \n character

Run this example online: https://ideone.com/rUXCIe


This might be what most people are looking for, however if you want to just read the whole input until EOF into a single variable (like OP), then you might want to look at this other answer.

like image 76
arekolek Avatar answered Oct 19 '22 08:10

arekolek