def tee_output_fd():
    """Duplicate stdout and stderr to a file on the file descriptor level."""
    with NamedTemporaryFile(mode="w+", newline="") as target:
        original_stdout_fd = 1
        original_stderr_fd = 2
        target_fd = target.fileno()

        # Save a copy of the original stdout and stderr file descriptors)
        saved_stdout_fd = os.dup(original_stdout_fd)
        saved_stderr_fd = os.dup(original_stderr_fd)

        try:
            # start_new_session=True to move process to a new process group
            # this is done to avoid receiving KeyboardInterrupts (see #149)
            tee_stdout = subprocess.Popen(
                ["tee", "-a", target.name],
                start_new_session=True,
                stdin=subprocess.PIPE,
                stdout=1,
            )
            tee_stderr = subprocess.Popen(
                ["tee", "-a", target.name],
                start_new_session=True,
                stdin=subprocess.PIPE,
                stdout=2,
            )
        except (FileNotFoundError, OSError, AttributeError):
            # No tee found in this operating system. Trying to use a python
            # implementation of tee. However this is slow and error-prone.
            tee_stdout = subprocess.Popen(
                [sys.executable, "-m", "sacred.pytee"],
                stdin=subprocess.PIPE,
                stderr=target_fd,
            )
            tee_stderr = subprocess.Popen(
                [sys.executable, "-m", "sacred.pytee"],
                stdin=subprocess.PIPE,
                stdout=target_fd,
            )

        flush()
        os.dup2(tee_stdout.stdin.fileno(), original_stdout_fd)
        os.dup2(tee_stderr.stdin.fileno(), original_stderr_fd)
        out = CapturedStdout(target)

        try:
            yield out  # let the caller do their printing
        finally:
            flush()

            # then redirect stdout back to the saved fd
            tee_stdout.stdin.close()
            tee_stderr.stdin.close()

            # restore original fds
            os.dup2(saved_stdout_fd, original_stdout_fd)
            os.dup2(saved_stderr_fd, original_stderr_fd)

            try:
                tee_stdout.wait(timeout=1)
            except subprocess.TimeoutExpired:
                warnings.warn("tee_stdout.wait timeout. Forcibly terminating.")
                tee_stdout.terminate()

            try:
                tee_stderr.wait(timeout=1)
            except subprocess.TimeoutExpired:
                warnings.warn("tee_stderr.wait timeout. Forcibly terminating.")
                tee_stderr.terminate()

            os.close(saved_stdout_fd)
            os.close(saved_stderr_fd)
            out.finalize()
Duplicate stdout and stderr to a file on the file descriptor level.
sacred/stdout_capturing.py