如何在python中读取用户输入直到EOF?

roh*_*han 11 eof python-3.x

我在 UVa OJ 中遇到了这个问题。272-文本行情

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

while( scanf("%s",&s)!=EOF ) { //do something } 
Run Code Online (Sandbox Code Playgroud)

这如何在 python 中完成。?

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

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

小智 7

您可以使用sys模块:

import sys

complete_input = sys.stdin.read()
Run Code Online (Sandbox Code Playgroud)

sys.stdin是一个类似文件的对象,您可以像对待Python File 对象一样对待它。

从文档:

内置函数帮助阅读:

_io.TextIOWrapper 实例的 read(size=-1, /) 方法从流中读取最多 n 个字符。

Read from underlying buffer until we have n characters or we hit EOF.
If n is negative or omitted, read until EOF.
Run Code Online (Sandbox Code Playgroud)


MrS*_*ker 6

你可以阅读从控制台输入,直到使用文件的末尾sys,并os在Python模块。我已经多次在像 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
Run Code Online (Sandbox Code Playgroud)

请注意,\n您阅读的每一行的末尾都会有一个行尾字符。如果您想在打印时避免打印 2 个结束行字符,请line使用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)
Run Code Online (Sandbox Code Playgroud)

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

第三种方法:

while True:
    line = input()
    if line == '':
        break
    process(line)
Run Code Online (Sandbox Code Playgroud)

如果您仍在使用 python 2,请替换input()为。raw_input()


小智 5

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

while True:
try :
    line = input()
    ...
except EOFError:
    break;
Run Code Online (Sandbox Code Playgroud)