How to read user input until EOF?

こ雲淡風輕ζ 提交于 2019-11-30 05:43:14

Use 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.

>>> import sys
>>> isinstance(sys.stdin, file)
True

BTW, dont' use input as a variable name. It shadows builtin function input.

This worked for me in Python 3:

from sys import stdin

for line in stdin:
  print(line)

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

With sys.stdin.readline() you could write like this:

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_input or input version, write like this:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!