0

I am trying to redirect output, and flush every once in a while to clear the buffer.

Flushing doesn't do anything - can't even enter the function with debugger.

from io import BytesIO as StringIO

out = StringIO()
out.write("hi")
output = out.getvalue().strip()
assert output == "hi"
out.flush()
output = out.getvalue().strip()
assert output == ""

The second assertion fails, as output is still "hi". flush() did nothing.

What am I getting wrong?

Gulzar
  • 23,452
  • 27
  • 113
  • 201

1 Answers1

1

Just do one change, Replace out.flush() with out.truncate(0) and then it will be work fine as follows:

from io import BytesIO as StringIO

out = StringIO()
out.write("hi")
output = out.getvalue().strip()
assert output == "hi"
out.seek(0)
out.truncate(0)
output = out.getvalue().strip()
assert output == ""
Chirag Kalal
  • 638
  • 1
  • 7
  • 21