Skip to content

Commit a5d86a2

Browse files
committedOct 31, 2024
Changed to only open and close output file once instead of on every line write
1 parent b8c7587 commit a5d86a2

File tree

1 file changed

+14
-11
lines changed

1 file changed

+14
-11
lines changed
 

‎scripts/tests/linux/log_line_processing.py

+14-11
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import queue
1717
import subprocess
1818
import threading
19+
import time
1920
from typing import List
2021

2122

@@ -43,6 +44,7 @@ class ProcessOutputCapture:
4344
def __init__(self, command: List[str], output_path: str):
4445
# in/out/err are pipes
4546
self.command = command
47+
self.output_file = None # Output file handle
4648
self.output_path = output_path
4749
self.output_lines = queue.Queue()
4850
self.process = None
@@ -52,18 +54,13 @@ def __init__(self, command: List[str], output_path: str):
5254
self.done = False
5355

5456
def _write_to_file(self, line: str, is_error_line=False):
55-
"""Writes a line to an output file in a thread-safe manner.
56-
57-
Opens file in append-text mode ('at') with line buffering
58-
for immediate output to ensure all writes are appended.
59-
"""
57+
"""Writes a line to an output file in a thread-safe manner."""
6058
with self.lock:
61-
with open(self.output_path, "at", buffering=1) as f:
62-
if is_error_line:
63-
f.write(f"!!STDERR!! : {line}")
64-
else:
65-
f.write(line)
66-
f.flush()
59+
if is_error_line:
60+
self.output_file.write(f"!!STDERR!! : {line}")
61+
else:
62+
self.output_file.write(line)
63+
self.output_file.flush()
6764

6865
def _stdout_thread(self):
6966
"""Reads stdout process lines and writes them to an output file.
@@ -103,6 +100,8 @@ def __enter__(self):
103100
self.stderr_thread = threading.Thread(target=self._stderr_thread)
104101
self.stdout_thread.start()
105102
self.stderr_thread.start()
103+
self.output_file = open(self.output_path, "wt", buffering=1) # Enable line buffering
104+
self._write_to_file(f"### PROCESS START: {time.ctime()} ###\n")
106105
return self
107106

108107
def __exit__(self, exception_type, exception_value, traceback):
@@ -117,6 +116,10 @@ def __exit__(self, exception_type, exception_value, traceback):
117116
if self.stderr_thread:
118117
self.stderr_thread.join()
119118

119+
if self.output_file:
120+
self._write_to_file(f"### PROCESS END: {time.ctime()} ###\n")
121+
self.output_file.close()
122+
120123
if exception_value:
121124
# When we fail because of an exception, report the entire log content
122125
logging.error(f"-------- START: LOG DUMP FOR {self.command!r} -----")

0 commit comments

Comments
 (0)