ValueError:在捕获raw_input时打开的关闭文件的I/O操作。

时间:2021-01-26 19:34:06

I have a simple method that takes a string passed to it and determines if the user was confirming their selection or not. The idea is that a user can type 0 to exit from the program all together. Whenever a user selects 0 though I receive ValueError. Is it something I implemented in my while loop?

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

Notes

self.YellowBold will simply color text with ANSII escape characters.

自我。只需用ANSII转义字符给文本上色。

self.CleanUp does open and close a log file before exiting. This method however has never caused a problem in my program and is called often and will exit the program.

自我。在退出之前,清理将打开并关闭一个日志文件。然而,这个方法从来没有在我的程序中引起问题,并且经常被调用,并将退出程序。

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

Error

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

CleanUp

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

Solution

My exception was too broad and using exception as flow control in this case did not work because of the interaction with CleanUp(). I reworked my flow control.

我的异常范围太广,在这种情况下使用异常作为流控制不起作用,因为与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 个解决方案

#1


0  

You are using a blanket except and catching the SystemExit exception raised by exit(1). It looks like stdin is already closed by that time.

您正在使用一个毯子,除了和捕获由exit(1)引发的SystemExit异常。看起来stdin已经关闭了。

You need to be more selective in what exceptions you catch. You could limit to Exception:

您需要在捕获的异常中更有选择性。您可以限制为例外:

except Exception:

but that's still to wide a net, even though SystemExit is then no longer caught (it inherits from BaseException).

但这仍然是一个巨大的网络,即使SystemExit不再被捕获(它继承自BaseException)。

There shouldn't really be any exceptions to catch here anyway, str() is very flexible as all objects should have a working __repr__ implementation to fall back to.

这里不应该有任何异常,str()非常灵活,因为所有对象都应该有一个可工作的__repr__实现。

This is sufficient for your specific prompt:

这足以满足您的具体提示:

    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: "))

#2


0  

I tried a simplified version of this code and it works without any errors. Here is the code:

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

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)

I am suspecting that the problem is somewhere else. Perhaps You have opened a file but not closed it in except block. Need more code to reach conclusion.

我怀疑问题出在别的地方。也许您已经打开了一个文件,但是除了块之外没有关闭它。需要更多的代码才能得出结论。

#1


0  

You are using a blanket except and catching the SystemExit exception raised by exit(1). It looks like stdin is already closed by that time.

您正在使用一个毯子,除了和捕获由exit(1)引发的SystemExit异常。看起来stdin已经关闭了。

You need to be more selective in what exceptions you catch. You could limit to Exception:

您需要在捕获的异常中更有选择性。您可以限制为例外:

except Exception:

but that's still to wide a net, even though SystemExit is then no longer caught (it inherits from BaseException).

但这仍然是一个巨大的网络,即使SystemExit不再被捕获(它继承自BaseException)。

There shouldn't really be any exceptions to catch here anyway, str() is very flexible as all objects should have a working __repr__ implementation to fall back to.

这里不应该有任何异常,str()非常灵活,因为所有对象都应该有一个可工作的__repr__实现。

This is sufficient for your specific prompt:

这足以满足您的具体提示:

    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: "))

#2


0  

I tried a simplified version of this code and it works without any errors. Here is the code:

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

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)

I am suspecting that the problem is somewhere else. Perhaps You have opened a file but not closed it in except block. Need more code to reach conclusion.

我怀疑问题出在别的地方。也许您已经打开了一个文件,但是除了块之外没有关闭它。需要更多的代码才能得出结论。