阅读一行时如何删除EOFError:EOF? [英] How to remove EOFError: EOF when reading a line?

查看:39
本文介绍了阅读一行时如何删除EOFError:EOF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我必须检查特定模式是否出现在一行中.如果是,我必须打印该行,否则不打印.所以这是我的代码:

Basically, I have to check whether a particular pattern appear in a line or not. If yes, I have to print that line otherwise not. So here is my code:

p = input()
 while 1:
   line = input()
   a=line.find(p)
   if a!=-1:
     print(line)
   if line=='':
     break

这段代码看起来不错,被接受为正确答案.但有一个问题.我在读取代码测试网站忽略的行时收到运行时错误 EOFError: EOF.

This code seems to be good and is being accepted as the correct answer. But there's a catch. I'm getting a run time error EOFError: EOF when reading a line which is being overlooked by the code testing website.

我有三个问题:1)为什么会被忽视?2)如何去除?3)有没有更好的方法来解决这个问题?

I have three questions: 1) Why it is being overlooked? 2) How to remove it? 3) Is there a better way to solve the problem?

推荐答案

没有什么会被忽视.根据 documentation input 引发 EOFError 当它遇到文件结束条件.本质上,input 让你知道我们已经完成了,没有什么可阅读的了.你应该等待这个异常,当你得到它时,从你的函数返回或终止程序.

Nothing is overlooked. As per the documentation input raises an EOFError when it hits an end-of-file condition. Essentially, input lets you know we are done here there is nothing more to read. You should await for this exception and when you get it just return from your function or terminate the program.

def process_input():
    p = input()
    while True:
        try:
            line = input()
        except EOFError:
            return
        a = line.find(p)             
        if a != -1:
            print(line)
        if line=='':
            return

这篇关于阅读一行时如何删除EOFError:EOF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆