Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell whether sys.stdout has been flushed in Python

Tags:

python

io

stdout

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 certain 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).

like image 321
M.D. Avatar asked Nov 13 '22 17:11

M.D.


1 Answers

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.

like image 87
rumpel Avatar answered Dec 18 '22 10:12

rumpel