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 badges1 Answer
Reset to default 1Use 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
版权声明:本文标题:python - Input always eats one character - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736311820a1934875.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论