Home > OS >  Python stdout and stdout.buffer capture
Python stdout and stdout.buffer capture

Time:10-21

Hey i want to prevent any stdouts from anywhere and capture it in a variable.

Now the problem:

I have two methods to print something in stdout

Method 1:

print("Normal Print")

Method 2:

fds: List[BinaryIO] = [sys.stdin.buffer, sys.stdout.buffer, sys.stderr.buffer]
fds[1].write(b"%d\n" % a)
fds[1].flush()

Now i tried something like this

from io import BufferedWriter, BytesIO, StringIO

mystdout = StringIO()
mystdout.buffer = BufferedWriter(raw=BytesIO())
sys.stdout = mystdout

But with this i get no output at all.

How is the best way to archiev this?

CodePudding user response:

What do you mean that you get no output at all? It's in variable:

mystdout = StringIO()
mystdout.buffer = BufferedRandom(raw=BytesIO()) # You can read from BufferedRandom
sys.stdout = mystdout
sys.stdout.buffer.write(b"BUFFER")
print("PRINT")
sys.stdout = sys.__stdout__ # Restore original stdout

print(mystdout.getvalue()) # PRINT
mystdout.buffer.seek(0)
print(mystdout.buffer.read()) b"BUFFER"
  • Related