如果在 Python 3.4 中,我想读取值(此处为int),直到用户输入为止。 喜欢这个 C代码
while( scanf("%d", &no) )
{
printf("%d" , no);
}
我尝试过类似的事情:
inp = input()
while inp != '':
print(int(inp))
inp = input()
只要我从终端手动输入并使用 enter或newline结束输入
,上面的python代码就可以工作但它抛出: EOFError:读取行时的EOF ,当我从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
答案 0 :(得分: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
答案 1 :(得分:1)
抓住错误..
def safe_input(prompt=None):
try:
return input(prompt)
except EOFError:
return ''
inp = safe_input()
while inp != '':
print(int(inp))
inp = safe_input()