如何捕獲 Python 中的 EOFError 異常?
當 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
廣告