Last active
June 6, 2022 13:05
-
-
Save osiriswrecks/ebc39243b2829608daa22e4fd9736454 to your computer and use it in GitHub Desktop.
How to intercept stdout with Python in Blender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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