python - 读取输入直到用户停止

标签 python python-3.x

如果在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/

相关文章:

python - 如何根据其他数据框过滤一个 Pandas 数据框日期

php - 脚本语言如何使用套接字?

python - 无效参数错误 : No OpKernel was registered to support Op 'CudnnRNN'

python-3.x - 如何在没有分隔符的情况下从 CSV 创建 Pandas 数据框(在 python 中)

python - 在 Python3 中评估字符串中的 UTF-8 文字转义序列

python-3.x - Python sys.platform = Linux2 但不是 Linux3?

python - Python 3.x 中字符串的内部表示是什么

python - Pandas 将列集 reshape 为行

python - 从 gridsearchCV 内的 RFECV 检索选定的特征

Python 描述符在 Python 2.7 中不起作用