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

新手上路,请多包涵

我在 UVa OJ 中遇到了这个问题。 272 条文字引述

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

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

这怎么能在 python 中完成?

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

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

原文由 rohan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2k
2 个回答

您可以使用 sys 模块:

 import sys

complete_input = sys.stdin.read()

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.

原文由 user1785721 发布,翻译遵循 CC BY-SA 4.0 许可协议

您可以使用 sysos 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

请注意,在您阅读的每一行末尾都会有一个行尾字符 \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)

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

第三种方法:

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

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

原文由 MrSeeker 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题