code: def posix_redirect_output(filename=None, permanent=True):
      
      sys.stdout.flush()
      sys.stderr.flush()
  
      stdout_fd = sys.stdout.fileno()
      stderr_fd = sys.stderr.fileno()
  
      if not permanent:
          stdout_fd_copy = os.dup(stdout_fd)
          stderr_fd_copy = os.dup(stderr_fd)
  
      if filename is None:
          out_fd, filename = tempfile.mkstemp()
      else:
          out_fd = os.open(filename, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
  
      try:
          # Redirect stdout and stderr to file
          os.dup2(out_fd, stdout_fd)
          os.dup2(out_fd, stderr_fd)
  
          yield filename
      finally:
          sys.stdout.flush()
          sys.stderr.flush()
          os.close(out_fd)
  
          if not permanent:
              os.dup2(stdout_fd_copy, stdout_fd)
              os.dup2(stderr_fd_copy, stderr_fd)
              os.close(stdout_fd_copy)
              os.close(stderr_fd_copy)
docs: Redirect stdout/stderr to a file, using posix dup2.