Python 3.x 如何在python中读取用户输入直到EOF?

Python 3.x 如何在python中读取用户输入直到EOF?,python-3.x,eof,Python 3.x,Eof,我在UVa OJ中遇到了这个问题 嗯,这个问题很小。但问题是我无法读取输入。输入以文本行的形式提供,输入结束用EOF表示。 在C/C++中,这可以通过运行while循环来完成: while( scanf("%s",&s)!=EOF ) { //do something } 如何在python中实现这一点 我在网上搜索过,但没有找到满意的答案 请注意,输入必须从控制台读取,而不是从文件读取。您可以使用sys模块: import sys complete_input = sys.std

我在UVa OJ中遇到了这个问题

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

while( scanf("%s",&s)!=EOF ) { //do something } 
如何在python中实现这一点

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


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

您可以使用
sys
模块:

import sys

complete_input = sys.stdin.read()
是一个类似文件的对象,您可以将其视为文件

从文件中:

有关内置函数的帮助阅读:

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

如果您需要一次读取键盘上的一个字符,您可以在Python中看到
getch
的实现:

您可以使用Python中的
sys
os
模块从控制台读取输入,直到文件结束。我曾多次在像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
时打印两个结束行字符,请使用
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)
这种方法并不适用于所有在线法官,但它是从文件或控制台读取输入的最快方法

第三种方法:

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)

如果您仍在使用python 2,请将
input()
替换为
raw\u input()

您可以这样做:

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

对于HackerRank和HackerEarth平台,首选以下实施方式:

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

在这种情况下,是什么信号使输入终止?你能看看问题的输入格式吗[问题中提供的链接]。我不确定这是否适用于此。Thanks@rohanEOF字符,与C/C++相同,感谢这个想法。这当然可以做到,但这将导致问题解决方案包括一个只用于读取输入的整个模块。考虑到这是一个受约束的问题,这将不是非常有效。方法1和方法2在读取输入所用时间方面可能重复的比较将使事情变得清楚。。?