nonoitall nonoitall - 1 month ago 11
Python Question

Why do I get a ValueError when explicitly closing stdout?

Python newbie here. I'm writing a script that can dump some output to either a file or stdout, depending on the arguments passed to it. When interpreting arguments, I assign either an

open
'ed file or
stdout
to a global variable named
output_file
, which can be used by the rest of the script to write output regardless of what type of stream was selected. At the very end of the script I
close
output_file
. This is proper to do for a file stream, and though it's redundant for stdout, my experience with other programming languages suggests that there's no harm in explicitly closing stdout immediately before the program ends.

However, whenever stdout is used for output (and subsequently closed), I get a "ValueError: 'I/O operation on closed file.'". I know this error is not directly produced by my call to close stdout, but occurs after my script returns. My question is: Why does this happen, and is there a way to manually close stdout without triggering it? (I'm aware that I can easily work around the problem by conditionally closing the stream only when a file was selected, but I want to know if/why this is necessary.)

Very simple demonstrative snippet:

from sys import stdout
stdout.close()

Answer

The problem is that on python-3.2 there's an attempt at shutdown to flush stdout without checking if it was closed.

The issue13444 is about this.

You shouldn't have this problem in python-2.7 in releases after the fixing patch.