如何在 python 中读取 EOF 之前的用户输入?

How to read user input until EOF in python?

我在 UVa OJ 遇到过这个问题。 272-Text Quotes

嗯,这个问题很简单。但问题是我无法读取输入。输入以文本行的形式提供,输入结束由 EOF 指示。 在 C/C++ 中,这可以通过 运行 一个 while 循环来完成:

while( scanf("%s",&s)!=EOF ) { //do something } 

如何在 python 中完成此操作?

我在网上搜索过,但没有找到满意的答案。

请注意,必须从控制台而非文件中读取输入。

您可以使用 sys 模块:

import sys

complete_input = sys.stdin.read()

sys.stdin is a file like object that you can treat like a Python File object.

来自文档:

Help on built-in function read:

read(size=-1, /) method of _io.TextIOWrapper instance Read at most n characters from stream.

Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.

如果你需要一次读取键盘上的一个字符,你可以在Python中看到getch的实现:Python read a single character from the user

您可以使用 python 中的 sysos 模块从控制台读取输入直到文件末尾。这些方法我在SPOJ之类的在线评委中用过好几次了

第一种方法(推荐):

from sys import stdin

for line in stdin:
    if line == '': # If empty string is read then stop the loop
        break
    process(line) # perform some operation(s) on given string

请注意,您阅读的每一行末尾都会有一个结束符 \n。如果要避免在打印 line 时打印 2 个结束行字符,请使用 print(line, end='').

第二种方法:

import os
# here 0 and 10**6 represents starting point and end point in bytes.
lines = os.read(0, 10**6).strip().splitlines() 
for x in lines:
    line = x.decode('utf-8') # convert bytes-like object to string
    print(line)

此方法不适用于所有在线评委,但它是从文件或控制台读取输入的最快方法。

第三种方法:

while True:
    line = input()
    if line == '':
        break
    process(line)

input() 替换为 raw_input() 如果您 仍然 使用 python 2.

您可以这样做:

while True:
   try :
      line = input()
      ...
   except EOFError:
      pass

对于 HackerRank 和 HackerEarth 平台,首选以下实现:

while True:
try :
    line = input()
    ...
except EOFError:
    break;