Skip to content

Instantly share code, notes, and snippets.

@osiriswrecks
Last active June 6, 2022 13:05
Show Gist options
  • Save osiriswrecks/ebc39243b2829608daa22e4fd9736454 to your computer and use it in GitHub Desktop.
Save osiriswrecks/ebc39243b2829608daa22e4fd9736454 to your computer and use it in GitHub Desktop.
How to intercept stdout with Python in Blender
import sys
import contextlib
import io
class ConsoleReader(io.StringIO):
def __init__(self, stream):
super().__init__()
self.stream = stream
def enable(self):
sys.stdout = self
def disable(self):
sys.stdout = self.stream
def get_last_line(self):
return self.getvalue().split("\n")[-2]
reader = ConsoleReader(sys.stdout)
reader.enable()
print("This message was intercepted")
print("So was this one")
print("hello there")
reader.disable()
print(reader.getvalue()) # Prints the entire buffer
print(reader.get_last_line()) # Custom method to grab the last line in the buffer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment