Go exec.Command()

(Go exec()에서 넘어옴)

1 개요[ | ]

Go Command()
Go exec.Command()

2 정상 실행 여부만 확인[ | ]

package main

import "fmt"
import "os/exec"

func main() {
	cmd := exec.Command("touch", "/tmp/hello")
	err := cmd.Run()
	if err != nil {
		panic(err)
	}
	fmt.Println("ok")
}

3 실행결과 받기[ | ]

package main

import "fmt"
import "os/exec"

func main() {
	cmd := exec.Command("sh", "-c", "cat /etc/services | grep ^http")
	stdout, err := cmd.Output()
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Println(string(stdout))
}
package main

import "fmt"
import "os/exec"

func main() {
	cmd := exec.Command("cat", "/etc/services", "|", "grep", "^http")
	stdout, err := cmd.Output()
	if err != nil {
		panic(err)
	}
	fmt.Println(string(stdout))
}
package main

import (
	"bytes"
	"fmt"
	"log"
	"os/exec"
	"strings"
)

func main() {
	cmd := exec.Command("tr", "a-z", "A-Z")
	cmd.Stdin = strings.NewReader("some input")
	var out bytes.Buffer
	cmd.Stdout = &out
	err := cmd.Run()
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("in all caps: %q\n", out.String())
}

4 오류[ | ]

package main

import (
	"log"
	"os"
	"os/exec"
)

func main() {
	cmd := exec.Command("prog")
	cmd.Env = append(os.Environ(),
		"FOO=duplicate_value", // ignored
		"FOO=actual_value",    // this value is used
	)
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}

5 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}