如何在 Python 中捕获 EOFError 异常?

pythonserver side programmingprogramming

当内置函数(如 input() 或 raw_input())在遇到输入流末尾之前未读取任何数据时,会引发 EOFError。文件方法(如 read())在文件末尾返回一个空字符串。

给定的代码重写如下,以捕获 EOFError 并找到其类型。

示例

#eofError.py
try:
while True:
data = raw_input('prompt:')
print 'READ:', data
except EOFError as e:
print e
Then if we run the script at the terminal
$ echo hello | python eofError.py

输出

prompt:READ: hello
prompt:EOF when reading a line



相关文章