1

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.

1
  • You are executing a program named something like "/usr/local/bin/go build /data/test/mycode.go" with exactly zero arguments. You should provide each argument ("build" and "/data/test/mycode.go") individually, that's what exec.Command arg ...string is good for. Commented Feb 3, 2015 at 13:08

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.