pty icon indicating copy to clipboard operation
pty copied to clipboard

Separate stderr and stdout

Open kevspl opened this issue 1 year ago • 0 comments

Hey all, I am using pty in my project to get some CLI tools to print with color.

Is it possible to get back 3 files here, one as it is now where stdout & stderr are combined, and one where it is just stdout and the other stderr? This would really help with some string/file manipulation I want to do afterwards. Currently this is the only way I found to separate out stdout and stderr:

func RunCommand(command string) (stdout, stderr string, err error) {
	cmd := exec.Command("bash", "-c", command)

	var stderrBuf bytes.Buffer
	var stdoutBuf bytes.Buffer

	cmd.Stderr = &stderrBuf // this line redirects the stderr to the buffer

	ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Cols: 80, Rows: 24})
	if err != nil {
		return "", "", err
	}
	defer func() { _ = ptmx.Close() }()

	go func() {
		_, _ = stdcopy(&stdoutBuf, ptmx)
	}()

	if err := cmd.Wait(); err != nil {
		return stdoutBuf.String(), stderrBuf.String(), err
	}

	return stdoutBuf.String(), stderrBuf.String(), nil
}

However this means that I can't keep the original output ordering, if for example a CLI tool prints to stdout then stderr then back to stdout this ordering is lost.

Thanks for the project, would appreciate some insight here!

kevspl avatar May 01 '24 17:05 kevspl