英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论