William
William

Reputation: 83

call 'go build' command from golang os.exec

in my project, i need to write some go code dynamically and need to test the code is valid. so need to call "go build" command use 'os.exec' function.

when i write go code in a temp directory like '/data/test/mycode.go'. and i try to call 'go build', they return a error as 'no such file or directory'. how i can do this correctly? thanks all:)

below is some code '

// is not work too
// goPath, err := exec.LookPath("go")

var out, stderr bytes.Buffer
cmd := exec.Command(fmt.Sprintf("%s/go build /data/test/mycode.go", goPath))
cmd.Stdout = &out
cmd.Stderr = &stderr
err = cmd.Run()

PS: but i call the command 'go build /data/test/mycode.go' directly in terminal. it can works.

Upvotes: 1

Views: 2760

Answers (1)

Uvelichitel
Uvelichitel

Reputation: 8490

fmt.Sprintf("%s/go build /data/test/mycode.go", goPath) string returns a single string internally divided by a blank space, but as a single string.

os/exec.Command(name string, arg ...string) *Cmd expects a few arguments. It won't divide one string itself.

Upvotes: 2

Related Questions