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?
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.
Use file.read:
input_str = sys.stdin.read()
According to the documentation:
file.read([size])
Read at most size bytes from the file (less if the read hits EOF
before obtaining size bytes). If the size argument is negative or
omitted, read all data until EOF is reached.
>>> import sys
>>> isinstance(sys.stdin, file)
True
BTW, dont' use input as a variable name. It shadows builtin function input.
You could also do the following:
acc = []
out = ''
while True:
try:
acc.append(raw_input('> ')) # Or whatever prompt you prefer to use.
except EOFError:
out = '\n'.join(acc)
break
With sys.stdin.readline() you could write like this:
import sys
while True:
input_ = sys.stdin.readline()
if input_ == '':
break
print type(input_)
sys.stdout.write(input_)
Remember, whatever your input is, it is a string.
For raw_input or input version, write like this:
while True:
try:
input_ = input("Enter:\t")
#or
_input = raw_input("Enter:\t")
except EOFError:
break
print type(input_)
print type(_input)
print input_
print _input
Related
Imagine unlimited multiline input with some URL addresses, for example:
How would you get that addresses from the input separately?
Following was close, but actually not helping:
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
source: How to get multiline input from user
And other advices I consider completely useless: https://python.plainenglish.io/taking-multiple-inputs-from-user-in-python-3-6cbe02d03a95
If I understand the problem correctly, this may help:
lines = []
try:
while line := input():
lines.append(line)
except EOFError:
pass
print(lines)
This will handle both interactive and redirected input (stdin)
There is a function you could use:
import sys
sys.stdin.read()
But I'm not sure this is a great idea because it won't know when to stop reading. The traditional input() function will detect a \n symbol via the return key, then end input.
I think looping would be the best way forward.
Like:
urls = ''
while True:
url = input()
if url:
urls += url + '\n'
else:
break
Have a nice day.
I try to output the sum of 1 - 12 lines which contain each two numbers which are seperated by ' '. Because I don't know how many lines will be inputed, I have an endless loop, which will be interupted if the line is empty. But if there is no input anymore, there won't be any empty input and the program is stuck in the input function.
while True:
line = input()
if line:
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
else:
break
So after the last outputed sum I want the program to stop. Maybe it is possible with a time limit?
It looks like the automated input is coming in via sys.stdin. In that case you can just read from the standard input stream directly. Try this:
def main():
import sys
lines = sys.stdin.read().splitlines()
for line in lines:
print(sum(map(int, line.split())))
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
With an input of "1 2\n3 4" to the sys.stdin stream, this script prints 3 and 7.
For the case without timeout, and the case allowing you to capture the content (which is usually handy).
The following code has been tested in HACKERRANK. I am sure HackerEarth is the same.
contents = []
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
contents.append(line)
if you don't care about the input.
while True:
try:
line = input()
line = line.split(' ')
print(str(int(line[0]) + int(line[1])))
except EOFError:
break
I have to read unknown number of lines from stdin in python3. Is there a way to do this without any modules? One more question: How to denote end of input for multiple lines in python3?
Try something like this
a_lst = [] # Start with empty list
while True:
a_str = input('Enter item (empty str to exit): ')
if not a_str: # Exit on empty string.
break
a_lst.append(a_str)
print(a_lst)
We can use try and except in the following way
while True:
try:
n = int(input())
# Perform your operations
except EOFError:
# You can denote the end of input here using a print statement
break
The main aim of the code is to take n lines of input and add this data to dictionary and then perform n queries on dictionary. however only the last query is working correctly.
from sys import stdin
n = int(input())
mydict={}
for i in range(0,n):
pairs=input().split(' ')
key=pairs[0]
value=pairs[1]
mydict[key]=value
print (mydict)
for a in stdin:
print(a)
if(a in mydict):
print(a+'='+mydict[a])
else:
print("Not Found")
The input obtained from stdin includes the new line character(s), however, due to the use of input() the keys in the dictionary do not, hence the lookup fails. It works on the final iteration because the line is terminated by end of file rather than new line.
You could fix it by stripping whitespace at the end of the line in the second loop:
for a in stdin:
a = a.rstrip()
print(a)
if a in mydict:
print(a+'='+mydict[a])
else:
print("Not Found")
The content read from stdin is original stream.
So when you hit the enter key, the '\n' is add to the stream.
Solution 1: use input method.
Solution 2: read from stdin, and use rstrip() method before query from the dict.
This question already has answers here:
How to read multiple lines of raw input?
(16 answers)
Closed 6 years ago.
I want to write a program that gets multiple line input and work with it line by line. Why isn't there any function like raw_input in Python 3?
input does not allow the user to put lines separated by newline (Enter). It prints back only the first line.
Can it be stored in a variable or even read it to a list?
raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:
Python 3
print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
try:
line = input()
except EOFError:
break
contents.append(line)
Python 2
print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
try:
line = raw_input("")
except EOFError:
break
contents.append(line)
In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n
To get multi-line input from the user you can go like:
no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
lines+=input()+"\n"
print(lines)
Or
lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)
input(prompt) is basically equivalent to
def input(prompt):
print(prompt, end='', file=sys.stderr, flush=True)
return sys.stdin.readline()
You can read directly from sys.stdin if you like.
lines = sys.stdin.readlines()
lines = [line for line in sys.stdin]
five_lines = list(itertools.islice(sys.stdin, 5))
The first two require that the input end somehow, either by reaching the end of a file or by the user typing Control-D (or Control-Z in Windows) to signal the end. The last one will return after five lines have been read, whether from a file or from the terminal/keyboard.
Use the input() built-in function to get a input line from the user.
You can read the help here.
You can use the following code to get several line at once (finishing by an empty one):
while input() != '':
do_thing
no_of_lines = 5
lines = ""
for i in xrange(5):
lines+=input()+"\n"
a=raw_input("if u want to continue (Y/n)")
""
if(a=='y'):
continue
else:
break
print lines