首页 文章

读取输入直到用户停止

提问于
浏览
2

如果在 Python 3.4 中我想读取值(此处为int)直到用户输入为止 . 喜欢这个C代码

while( scanf("%d", &no) )
    {
     printf("%d" , no);
}

我试过类似的东西:

inp = input()
while inp != '':
   print(int(inp))
   inp = input()

只要我从终端手动输入并使用enter或换行结束输入,上面的python代码就可以工作

但它抛出: EOFError: EOF when reading a line 当我从linux终端的stdin读取时使用:

python3.4 filename.py < input

如果输入文件不包含尾随换行符 .

编辑:

我现在正在使用这种方法,并等待其他一些方法 .

import sys

 for line in sys.stdin:
     do_anything()   #here reading input
 # End here
 else_whatever()     #just passing here

2 回答

  • 2

    鉴于:

    $ cat input.txt
    hello
    

    尝试使用fileinput如下:

    import fileinput
    
    for line in fileinput.input():
        print(line)
    

    测试一下:

    $ python3 input.py < input.txt
    hello
    

    Fileinput也足够聪明,可以区分文件名和stdin:

    $ python3 input.py input.txt
    hello
    
  • 0

    grab 错误..

    def safe_input(prompt=None):
        try:
            return input(prompt)
        except EOFError:
            return ''
    
    inp = safe_input()
    while inp != '':
       print(int(inp))
       inp = safe_input()
    

相关问题