Go RunCommand()

1 개요[ | ]

Go RunCommand()
Go
Copy
package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"time"
)

func RunCommand(command string) (string, error) {
	var combinedOutput bytes.Buffer
	cmd := exec.Command("sh", "-c", command)
	cmd.Env = append(os.Environ(), "LINES=200")

	reader, writer := io.Pipe()
	defer writer.Close()

	cmd.Stdout = writer
	cmd.Stderr = writer

	go func() {
		defer reader.Close()
		io.Copy(&combinedOutput, reader)
	}()

	err := cmd.Run()
	time.Sleep(100 * time.Millisecond)

	out := combinedOutput.String()
	if err != nil {
		return out, fmt.Errorf("failed to execute command %s: %v", command, err)
	}

	return out, nil
}

func main() {
	out, _ := RunCommand("echo hello; echo world 1>&2")
	fmt.Println("[" + out + "]")
	// [hello
	// world
	// ]
}

2 같이 보기[ | ]