如果在Python 3.4中我想读取值(这里是int)直到用户给出输入怎么办? 就像这个C代码
while( scanf("%d", &no) )
{
printf("%d" , no);
}
我尝试过类似的方法:
inp = input()
while inp != '':
print(int(inp))
inp = input()
只要我从终端手动输入并用回车或换行符结束输入,上面的Python代码就可以工作
但它抛出:EOFError:读取行时的EOF当我使用以下命令从Linux终端中的标准输入读取时:
python3.4 filename.py < input
如果输入文件不包含尾部换行符。
编辑:
我现在正在使用这个方法,并等待其他方法。
import sys
for line in sys.stdin:
do_anything() #here reading input
# End here
else_whatever() #just passing here
最佳答案
给定:
$ cat input.txt
hello
尝试使用fileinput像这样:
import fileinput
for line in fileinput.input():
print(line)
测试一下:
$ python3 input.py < input.txt
hello
Fileinput 也足够聪明,可以区分文件名和标准输入:
$ python3 input.py input.txt
hello
关于python - 读取输入直到用户停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32384782/