[issue6333] logging: ValueError: I/O operation on closed file

Vinay Sajip report at bugs.python.org
Fri Jul 10 10:03:06 CEST 2009


Vinay Sajip <vinay_sajip at yahoo.co.uk> added the comment:

> Are you suggesting that the ownership of `sys.stderr` belongs to the
> logging module once logging.basicConfig (that initializes a 
> StreamHandler with stderr) is called?
> That no other module/library is to close sys.stderr even though they
> created it (sys.__stderr__ being the backup)?

> StreamHandler can take ownership of an arbitrary stream (say, created
> by the caller) passed to it, but assuming ownership of a
> standard stream, that are free to be overridden by a library (such as
> py.test), is rather bizarre.

Actually, it's not bizarre at all. Are you saying it's OK for multiple
threads in a program to write to sys.stderr, whenever they want, without
restriction, even if the end result is end-user visible output which is
gibberish (for example data from two logical streams interspersed
randomly)? Just because it's a "standard" stream? 

Also, perhaps you haven't noticed that StreamHandler has no way of
knowing whether the stream it was passed was a standard stream or not.
Logging may make certain hasattr-type checks e.g. for presence of
"flush" or "close", but it can't expect to not have ownership of the
stream, even for a standard stream.

I advise you to do the following: refactor your test cases to include
the explicit handler-adding code in your setup (instead of basicConfig),
and the handler-removing and closing code in your teardown.

def setUp(self):
  self.hdlr = logging.StreamHandler(stream)
  someLogger.addHandler(h)

def tearDown(self):
    someLogger.removeHandler(self.hdlr)
    self.hdlr.close()

where I have given someLogger module scope in the above snippet, you may
of course make it a testcase attribute too. I've used a unittest-style
of setUp/tearDown, I assume py.test is similar.

No changes to py.test are required. What happens if you do this?

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue6333>
_______________________________________


More information about the Python-bugs-list mailing list