How to tell whether sys.stdout has been flushed in Python
I'm trying to debug some code I wrote, which involves a lot of parallel processes. And have some unwanted behaviour involving output to sys.stdout
and certa开发者_如何学Pythonin messages being printed twice. For debugging purposes it would be very useful to know whether at a certain point sys.stdout
has been flushed or not. I wonder if this is possible and if so, how?
Ps. I don't know if it matters but I'm using OS X (at least some sys
commands depend on the operating system).
The answer is: you cannot tell (not without serious uglyness, an external C module or similar).
The reason is that python’s file-implementation is based on the C (stdio) implementation for FILE *
. So an underlying python file object basically just has a reference to the opened FILE
. When writing data the C-implementation writes data, and when you tell it to flush()
python also just forwards the flush call. So python does not hold the information. Even for the underlying C layer, a quick search returned that there is no documented API allowing you to access this information, however it's probably somewhere in the FILE
object, so it could in theory be read out if it is that desperately needed.
精彩评论