【问题标题】:Reading Input till User Stops读取输入直到用户停止
【发布时间】:2015-09-04 04:51:56
【问题描述】:

如果在 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 终端中的标准输入读取时使用:

python3.4 filename.py < input

如果 input 文件不包含尾随 换行符

编辑:

目前正在使用此方法,等待其他方法。

 import sys

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

【问题讨论】:

  • 那么您是在读取用户输入还是从文件中读取?这是两个完全不同的操作。另外,抛出EOFError的代码在哪里?
  • 我帖子的上述python部分抛出了那个错误
  • 你说当你从文件中读取时它会抛出EOFError。您的问题中没有从文件中读取的任何代码。
  • 先生编辑后有意义吗? @双位炼金术士

标签: python python-3.x


【解决方案1】:

给定:

$ 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

【讨论】:

  • 实际上我说我想从文件输入是错误的!我想要它两种方式!编辑有意义吗?
  • fileinput 支持来自标准输入的文件名或文本(Perl 和类似 awk 的功能......)
  • 好的,我将对此进行研究....我接受了ans,但肯定会寻找其他方法来做到这一点...最好不导入任何东西.... bdw 感谢您的ans!
  • 如果不导入某些内容,就无法读取标准输入。 sysfileinput 都在标准分发中。
【解决方案2】:

抓住错误..

def safe_input(prompt=None):
    try:
        return input(prompt)
    except EOFError:
        return ''

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

【讨论】:

    猜你喜欢
    • 2012-04-24
    • 2018-10-19
    • 2022-12-05
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-26
    相关资源
    最近更新 更多