关于python:如何在EOF之前读取用户输入?

How to read user input until EOF?

我当前的代码读取用户输入,直到换行。
但是我正在尝试将其更改为一种格式,在该格式下,用户可以写入输入,直到strg d结束输入。

我目前是这样的:

1
input = raw_input ("Input:")

但是如何将其更改为支持EOF的版本?


这在Python 3中对我有用:

1
2
3
4
from sys import stdin

for line in stdin:
  print(line)

line包含结尾的\
字符

在线运行此示例:https://ideone.com/Wn15fP


使用file.read

1
input_str = sys.stdin.read()

根据文档:

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.

1
2
3
>>> import sys
>>> isinstance(sys.stdin, file)
True

顺便说一句,不要使用input作为变量名。它隐藏了内置函数input


您还可以执行以下操作:

1
2
3
4
5
6
7
8
9
acc = []
out = ''
while True:
    try:
        acc.append(raw_input('> ')) # Or whatever prompt you prefer to use.
    except EOFError:
        out = '\
'
.join(acc)
        break


使用sys.stdin.readline(),您可以这样编写:

1
2
3
4
5
6
7
8
import sys

while True:
    input_ = sys.stdin.readline()
    if input_ == '':
        break
    print type(input_)
    sys.stdout.write(input_)

请记住,无论您输入什么,它都是一个字符串。

对于raw_inputinput版本,请这样写:

1
2
3
4
5
6
7
8
9
10
11
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