![](/img/trans.png)
[英]I am receiving the following error when executing my code - EOFError: EOF when reading a line
[英]EOFError when executing Python scripts in I/O Redirection
如果我使用以下代码在Python中创建程序“ prog.py”:
#!/usr/bin/python3.3
# -*-coding:Utf-8 -*
while True:
number = int(input())
print(number * 2)
我有一个文件“ numbers.txt”:
1
2
3
4
5
6
7
8
9
10
我这样运行:
chmod +x prog.py
cat numbers.txt | ./prog.py
我明白了:
2
4
6
8
10
12
14
16
18
20
Traceback (most recent call last):
File "./prog.py", line 5, in <module>
number = int(input())
EOFError: EOF when reading a line
为什么会出现这个错误?
这是因为您正在使用
while True:
替换为
import sys
for line in sys.stdin:
number = int(line.strip())
这是预期的; 您尝试从标准输入中读取带有input
而不检查是否已到达文件末尾。 但是,比重复调用input
更好的做法是直接在文件sys.stdin
上进行迭代。
import sys
for line in sys.stdin:
number = int(line)
print(number * 2)
到达文件末尾时,迭代将自动停止,因此无需显式检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.