I want to collect all of the print content and save them in a txt file. I use this answer's method to generate and collect logs. Also I use a threading
, because in my real environment, get_logs
and make_logs
are in different thread.
import sys
import io
import time
import threading
import traceback
class MyThread(threading.Thread):
def __init__(self, func, args):
super(MyThread, self).__init__()
self.func = func
self.args = args
def run(self):
try:
self.result = self.func(*self.args)
except Exception as e:
f = traceback.format_exc()
print(f'{f}')
def get_result(self):
try:
return self.result
except Exception:
return None
def make_logs(delay):
for i in range(100):
print(i)
print("\n")
time.sleep(delay)
def get_logs(t1):
if t1.is_alive():
sys.stdout = old_stdout
whatWasPrinted = buffer.getvalue()
with open("output.txt", "w") as text_file:
text_file.write(whatWasPrinted)
time.sleep(1)
get_logs(t1)
def do_it():
t1 = MyThread(make_logs, args=(1,))
t2 = MyThread(get_logs, args=(t1,))
t1.start(), t2.start()
t1.join(), t2.join()
old_stdout = sys.stdout
sys.stdout = buffer = io.StringIO()
do_it()
However, as I execute this code, I can only write the first elment(0) to txt file. Anyone knows why? Thanks.