从golang os.exec调用'go build'命令 [英] call 'go build' command from golang os.exec

查看:48
本文介绍了从golang os.exec调用'go build'命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的项目中,我需要动态编写一些go代码,并需要测试代码是否有效.因此需要使用"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.

当我在'/data/test/mycode.go'这样的临时目录中编写go代码时.而我尝试调用开始构建",则它们返回错误,例如无此类文件或目录".我怎样才能正确地做到这一点?谢谢大家:)

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:)

下面是一些代码'

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

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

推荐答案

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

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(名称字符串,arg ... string)* Cmd 期待一些争论.它本身不会分割一个字符串.

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

这篇关于从golang os.exec调用'go build'命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆