I'd like to accept standard input until empty lines are entered with the code below, but even if I enter only new lines, the process will not end.
Please tell me how to end the input.
Thank you for your cooperation.
def get_input():
while True:
try:
yield''.join(input())
except EOFError:
break
if__name__=='__main__':
a=list(get_input())#[a1,a2,a3,...]
Environment:
MacOSX 10.12.6
python 3.5.1
A new line does not cause EOF.If you want to recognize empty lines, you need to use a different method instead of EOFError.
For example, the following code may be helpful if you want to read one line at a time:
def get_input():
while True:
try:
Note that input() behavior differs between line=input()#Python2.x and Python 3.x.
if line==':# If empty, the line contains an empty string.
break
else:
yield line
except EOFError:
break
if__name__=='__main__':
a=list(get_input())
print(a)
Supplement: Regarding EOFError, for macOS terminals, you can communicate EOF by pressing Control+D (Reference).
For example, if you enter the following, an EOFError occurs and the original program in the questionnaire is terminated:
aaa
bbbbbbbbbbbbbbbbbbbb
cc
# Press Control+D here and break the line if necessary.
Also, since it's called end of file, you can enter it from a file.
$cat input.txt
aaaa Corporation
bbbbbbbbbbbbbbbbbbbb
cc
$ python example.py <input.txt
© 2025 OneMinuteCode. All rights reserved.