Python 如何在EOF之前读取用户输入?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21235855/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read user input until EOF?
提问by Saphire
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.
我当前的代码读取用户输入直到换行。但我试图将其更改为一种格式,用户可以在其中写入输入,直到 strg+d 结束他的输入。
I currently do it like this:
我目前这样做:
input = raw_input ("Input: ")
But how can I change that to an EOF-Ready version?
但是如何将其更改为 EOF-Ready 版本?
采纳答案by falsetru
Use file.read:
使用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.
file.read([size])从文件中最多读取 size 个字节(如果在获取 size 个字节之前读取达到 EOF,则更少)。如果 size 参数为负数或省略,则读取所有数据直到达到 EOF。
>>> import sys
>>> isinstance(sys.stdin, file)
True
BTW, dont' use inputas a variable name. It shadows builtin function input.
顺便说一句,不要input用作变量名。它隐藏了内置函数input。
回答by Joel Cornett
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
回答by Pet B
With sys.stdin.readline()you could write like this:
有了sys.stdin.readline()你可以这样写:
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_inputor inputversion, write like this:
对于raw_input或input版本,这样写:
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
回答by arekolek
This worked for me in Python 3:
这在 Python 3 中对我有用:
from sys import stdin
for line in stdin:
print(line)
Run this example online: https://ideone.com/Wn15fP
在线运行此示例:https: //ideone.com/Wn15fP

