I have a function that consist of a loop, from which I control the thread with semaphores:
import sys
from io import StringIO
import threading
# Create a semaphore object
sem = threading.Semaphore()
def my_function(event_set=True):
# Start a loop
for i in range(3):
# Wait for the semaphore to be released
sem.acquire()
print("step", i)
if event_set:
sem.release()
# Create a new thread with the my_function function
t = threading.Thread(target=my_function, args=(False,))
After starting this thread, I can can print out each step, but I would like to store console output into a buffer. With the code below, I'm able to save 'step 0\nstep 1\nstep 2\n'
in my_string
after running the thread completely.
# Create a StringIO instance
embedder = StringIO()
# Set sys.stdout to the StringIO instance
previous_stdout = sys.stdout
sys.stdout = embedder
# Create a new thread with the my_function function
t = threading.Thread(target=my_function, args=(False,))
# Initialize
t.start()
# Process the thread sequentially
while t.is_alive():
sem.release()
# Reset stdout
sys.stdout = previous_stdout
# Reset sys.stdout to its original value
my_string = embedder.getvalue()
However, I would like to save or read each step (i.e. 'step 0\n
', then 'step 1\n'
, etc...) separately (and sequentially) right after calling sem.release()
from my thread t
. I have written something as follows:
# Process the thread sequentially
while t.is_alive():
# Get the step string from buffer (after a thread .start() or .release())
current_string = embedder.getvalue()
# Reset the buffer
embedder.seek(0)
embedder.truncate(0)
# Process next step of the function (which prints out a new step)
sem.release()
When doig so, however, current_string
does not capture the string of each step as 'step 0\n
' or 'step 1\n
' ... etc. Is there any way to so?