调用`go build`命令可以使用Golang的`os/exec`包。

huangapple go评论89阅读模式
英文:

call 'go build' command from golang os.exec

问题

在我的项目中,我需要动态编写一些Go代码,并且需要测试代码是否有效。因此,我需要使用os.exec函数调用"go build"命令。

当我将Go代码写入临时目录,例如"/data/test/mycode.go",并尝试调用"go build"时,它们返回一个错误,指示"没有该文件或目录"。
我应该如何正确地做这个?谢谢大家:)

以下是一些代码:

// 也不起作用
// 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:但是我在终端中直接调用命令"go build /data/test/mycode.go"是可以工作的。

英文:

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

得分: 2

fmt.Sprintf("%s/go build /data/test/mycode.go", goPath) 返回一个由空格分隔的单个字符串,但作为一个整体字符串。

os/exec.Command(name string, arg ...string) *Cmd 需要一些参数。它不会自己分割一个字符串。

英文:

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.

huangapple
  • 本文由 发表于 2015年2月3日 19:48:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/28298154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定