如何在python中的EOF之前读取用户输入? [英] How to read user input until EOF in python?
问题描述
我在UVa OJ中遇到了这个问题。 272文本行情
I came across this problem in UVa OJ. 272-Text Quotes
这个问题很简单。但问题是我无法读取输入。输入以文本行的形式提供,并且输入结束由EOF指示。
在C / C ++中,可以通过运行while循环来完成:
Well, the problem is quite trivial. But the thing is I am not able to read the input. The input is provided in the form of text lines and end of input is indicated by EOF. In C/C++ this can be done by running a while loop:
while( scanf("%s",&s)!=EOF ) { //do something }
如何在python。?
How can this be done in python .?
我已经在网上搜索过,但没有找到满意的答案。
I have searched the web but I did not find any satisfactory answer.
请注意,必须从控制台而不是文件中读取输入。
Note that the input must be read from the console and not from a file.
推荐答案
您可以使用 sys
模块:
import sys
complete_input = sys.stdin.read()
sys.stdin 是类似于对象的文件,您可以将其视为 Python文件对象。
sys.stdin is a file like object that you can treat like a Python File object.
来自文档:
关于内置函数读取的帮助:
Help on built-in function read:
_io.TextIOWrapper实例的read(size = -1,/)方法
从流中读取最多n个字符。
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中的EOF之前读取用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!