ValueError:捕获raw_input时引发的关闭文件的I / O操作

时间:2015-02-12 15:10:34

标签: python python-2.7

我有一个简单的方法,它接受一个传递给它的字符串,并确定用户是否确认了他们的选择。这个想法是用户可以键入0以一起退出程序。每当用户选择0但我收到ValueError时。这是我在while循环中实现的东西吗?

注释

self.YellowBold只会使用ANSII转义字符为文本着色。

self.CleanUp会在退出之前打开并关闭日志文件。然而,这种方法从未在我的程序中引起问题,并且经常被调用并将退出程序。

def AskConfirm(self, answer):
    # Used throughout the script for all confirmations.
    # Try to force the answer to a lower case string. Bring up the prompt again if it fails.

        yes = ['yes','y']
        no = ['no','n']
        codes = ['0'] # Can be expanded later for other options

        while True:
            try:
                answer = str(answer).lower()

                if answer in yes: return True
                if answer in no: return False
                if answer in codes: self.CleanUp()

                raise Exception

            except:
                answer = raw_input (self.YellowBold("Please respond with 'y' or 'n' or '0' to exit: "))
                continue

错误

answer = raw_input (self.YellowBold("Please respond with 'y' or 'n' or '0' to exit:"))
ValueError: I/O operation on closed file

清理

def CleanUp(self): # Exit and add a breakpoint to the log file.
    open_log = self.OpenLog()
    open_log.write("-"*50 + "\n")
    exit(1)

解决方案

由于与CleanUp()的交互,我的异常太宽泛并且使用异常,因为流控制在这种情况下不起作用。我重写了流量控制。

def AskConfirm(self, answer):
        yes = ['yes','y']
        no = ['no','n']
        codes = ['0'] 
        prompt = self.YellowBold("Please respond with 'y' or 'n' or '0' to exit: ")

        while True:
            answer = str(answer).lower()
            if answer in yes: return True
            if answer in no: return False
            if answer in codes: self.CleanUp()

            answer = raw_input(prompt)

2 个答案:

答案 0 :(得分:1)

您正在使用一揽子except并抓住SystemExit引发的exit(1)例外情况。看来stdin已经关闭了。

您需要在捕获的异常方面更具选择性。您可以限制为Exception

except Exception:

但即使SystemExit不再被捕获(它继承自BaseException),仍然可以扩大网络。

无论如何都不应该有任何异常,str()非常灵活,因为所有对象都应该有一个有效的__repr__实现可以回归到。< / p>

这足以满足您的特定提示:

    while True:
        answer = str(answer).lower()

        if answer in yes: return True
        if answer in no: return False
        if answer in codes: self.CleanUp()

        # if we haven't returned, ask again
        answer = raw_input (self.YellowBold("Please respond with 'y' or 'n' or '0' to exit: "))

答案 1 :(得分:0)

我尝试了此代码的简化版本,它没有任何错误。这是代码:

yes = ['yes','y']
no = ['no','n']
answer = 'c'
def magic(answer):
    try:
        answer = str(answer).lower()
        print answer
        if answer in yes: return True
        if answer in no: return False
        raise Exception
    except Exception:
        print answer
        answer = raw_input ("Please respond with 'y' or 'n' or '0' to exit: ")
        print answer
        pass

magic(answer)

我怀疑问题出在其他地方。也许您已经打开了一个文件但未在except块中关闭它。需要更多代码才能得出结论。