admin管理员组

文章数量:1122832

A need multiline input in Python (I have v3.12.3) and I want to end the stream by pressing Ctrl+D But it always eats one character at the end.

def main():
    lines = []
    while True:
        try:
            line = input()
            lines.append(line)
        except EOFError:
            break
    print(lines)
    
if __name__=="__main__":
    main()

If I run the program and type 3 times '-' and then press Ctrl+D I got only 2 '-' Similarly 'abc' results in 'ab'.

What am I doing wrong? I need all the data that the user inputs.

A need multiline input in Python (I have v3.12.3) and I want to end the stream by pressing Ctrl+D But it always eats one character at the end.

def main():
    lines = []
    while True:
        try:
            line = input()
            lines.append(line)
        except EOFError:
            break
    print(lines)
    
if __name__=="__main__":
    main()

If I run the program and type 3 times '-' and then press Ctrl+D I got only 2 '-' Similarly 'abc' results in 'ab'.

What am I doing wrong? I need all the data that the user inputs.

Share Improve this question edited Nov 24, 2024 at 11:51 Friedrich 4,56011 gold badges44 silver badges42 bronze badges asked Nov 21, 2024 at 10:24 Michal P.Michal P. 557 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

Use sys.stdin.read() instead of input()

The issue is that when input() function processes the EOF (Ctrl+D) it terminates the current line without processing the final character entered before it.

Use sys.stdin.read() instead.

import sys

def main():
    try:
        lines = sys.stdin.read().splitlines()
        print(lines)
    except EOFError:
        pass

if __name__ == "__main__":
    main()

Why does this happen? Explanation:

The input() function reads input line-by-line, stopping at a newline (\n). If EOF (e.g., Ctrl+D on Unix/macOS, Ctrl+Z + Enter on Windows) is sent before a newline, input() won't process the final incomplete line because it expects a newline to complete the input.

On the other hand, sys.stdin.read() reads the entire input stream until EOF, including any partial lines before the EOF signal. This is because it treats input as a continuous stream rather than discrete lines.

Key Difference:

  • input(): Processes input line-by-line and requires a newline to handle input.
  • sys.stdin.read(): Processes the entire stream and handles incomplete lines before EOF.

本文标签: pythonInput always eats one characterStack Overflow