I want python3 to determine empty line input, but EOFError does not occur.

Asked 2 years ago, Updated 2 years ago, 41 views

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

python python3

2022-09-30 21:27

1 Answers

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


2022-09-30 21:27

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.