EOF 错误 python

EOF error python

我正在 Python 中编写一个简单的代码并收到此错误: 追溯(最近一次通话): 文件 "prog.py",第 4 行,位于 EOFError:读取一行时出现 EOF

我的代码是:

inp = [""]
i=0
while i==0:
    answer = raw_input("")
    if answer!="":
        inp.append(answer)
    else:
        break

for item in inp:
    if item=="42":
        break
    else:
        print item

print ""

您可以尝试阅读并理解这个答案(以帮助您在 Python 知识之旅中):

#! /usr/bin/env python
"""Short description what this module does."""
from __future__ import print_function


inp = []
while True:
    try:
        answer = raw_input("")  # in python v3 use input instead
    except EOFError as e:
        print("Ignored:", e)
        answer = None
    if answer:
        inp.append(answer)
    else:
        break

for item in inp:
    if item == "42":
        break
    else:
        print(item)

print()

这只是尝试更具可读性的编码风格的第一步。

接下来肯定会尝试 python.org 上的原始 Python 教程 ...

上述脚本的调用存储在prog.py中:

$> python2 prog.py < /dev/null

这使得程序从 /dev/null 中读取,因为输入不再导致:

Traceback (most recent call last):
  File "prog.py", line 5, in <module>
    answer = raw_input("")
EOFError: EOF when reading a line

而是:

Ignored: EOF when reading a line
[]

如果你只想不打印出 Ignored ... 行,并且知道可以默默忽略,你可以将 line/block 除外重写为

except EOFError:
    answer = None