douyue4334
douyue4334
2015-02-03 11:48
浏览 101
已采纳

从golang os.exec调用'go build'命令

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条回答 默认 最新

  • douji7399
    douji7399 2015-02-03 13:10
    已采纳

    fmt.Sprintf("%s/go build /data/test/mycode.go", goPath) string return single string internally devided by blanc space, but single string.

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

    点赞 评论

相关推荐