Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

redirect_output_to: flush(), fsync(), and close before resetting stdout and stderr #75

Merged
merged 2 commits into from
Nov 6, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 24 additions & 21 deletions src/sim_recon/files/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,29 +132,32 @@ def redirect_output_to(file_path: str | PathLike[str]) -> Generator[None, None,
saved_stdout_fd = os.dup(stdout_fd)
saved_stderr_fd = os.dup(stderr_fd)
saved_stdout = sys.stdout
saved_sterr = sys.stderr
f = None
f_fd = None
saved_stderr = sys.stderr
try:
f = file_path.open("w+", buffering=1)
f_fd = f.fileno()
os.dup2(f_fd, stdout_fd)
os.dup2(f_fd, stderr_fd)
sys.stdout = f
sys.stderr = f
yield
with file_path.open("w+", buffering=1) as f:
f_fd = f.fileno()
try:

os.dup2(f_fd, stdout_fd)
os.dup2(f_fd, stderr_fd)
sys.stdout = f
sys.stderr = f
yield
except Exception:
logger.error(
"Failed to redirect output to log at %s", file_path, exc_info=True
)
finally:
sys.stdout.flush()
sys.stderr.flush()
os.fsync(f_fd)
# Reset stdout and stderr file descriptors
os.dup2(saved_stdout_fd, stdout_fd)
os.dup2(saved_stderr_fd, stderr_fd)
sys.stdout = saved_stdout
sys.stderr = saved_stderr
except Exception:
logger.error("Failed to write output to log at %s", file_path, exc_info=True)
finally:
# Reset stdout and stderr file descriptors
os.dup2(saved_stdout_fd, stdout_fd)
os.dup2(saved_stderr_fd, stderr_fd)
sys.stdout = saved_stdout
sys.stderr = saved_sterr
if f_fd is not None:
os.fsync(f_fd)
if f is not None:
f.close()
logger.error("Failed to create log file %s", file_path)


def combine_text_files(
Expand Down