-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaulstretch_stdout_redirect.py
More file actions
53 lines (45 loc) · 1.66 KB
/
paulstretch_stdout_redirect.py
File metadata and controls
53 lines (45 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
import sys
import threading
class StdoutRedirector:
"""
A class to redirect stdout to a callback function.
This is used to capture progress updates from the paulstretch scripts.
"""
def __init__(self, callback=None):
self.callback = callback
self.original_stdout = sys.stdout
self.lock = threading.Lock()
self.capture_enabled = False
def write(self, text):
# Always write to the original stdout
self.original_stdout.write(text)
# If capture is enabled and we have a callback, call it
if self.capture_enabled and self.callback:
# Parse progress percentage from the output
if "%" in text and not "Error" in text:
try:
# Extract percentage from text like "50 % "
percentage = int(text.strip().split("%")[0])
self.callback(percentage)
except (ValueError, IndexError):
pass
def flush(self):
self.original_stdout.flush()
def enable_capture(self):
"""Enable capturing stdout"""
with self.lock:
self.capture_enabled = True
def disable_capture(self):
"""Disable capturing stdout"""
with self.lock:
self.capture_enabled = False
def __enter__(self):
"""Context manager entry point"""
sys.stdout = self
self.enable_capture()
return self
def __exit__(self, exc_type, exc_value, traceback):
"""Context manager exit point"""
self.disable_capture()
sys.stdout = self.original_stdout