Programmatic way to call go tools

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

Programmatic way to call go tools

问题

有没有一种方法可以在另一个Go程序中以库调用的方式调用Go工具(如go build),并获得比命令行调用的文本输出更结构化的输出?

英文:

Is there a way to call the Go tools (like go build) programmatically from within another Go program with a library call and to get more structured output compared to the text output from the command line invocation?

答案1

得分: 1

如果您想以编程方式运行构建,您还可以使用os/exec包。

func runBuild() {
    cmd := exec.Command("go", "build", "./main.go")
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
}

您还可以传递其他标志。例如:buildmode标志

cmd := exec.Command("go", "build", "-buildmode=plugin", "./main.go")

参考:https://golang.org/pkg/os/exec/

英文:

If you're trying to run build programmatically you can also use the os/exec package.

func runBuild() {
    cmd := exec.Command("go", "build", "./main.go")
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }

}

You can pass other flags too. E.g: the buildmode flag

cmd := exec.Command("go", "build", "-buildmode=plugin", "./main.go")

Reference: https://golang.org/pkg/os/exec/

答案2

得分: -2

在另一个Go程序中,可以使用os/exec包执行控制台命令,示例如下:

func main() {
   cmd := exec.Command("go run lib/main.go")
   if err := cmd.Run(); err != nil {
       log.Fatal(err)
   }
}

不过,我认为这并不是非常有用。

英文:

Within another go program it is possible to execute console commands using the os/exec package like so:

func main (){
   cmd := exec.Command("go run lib/main.go")
   if err := cmd.Run(); err != nil{
       log.Fatal(err)
   }
}

I don't see this being very useful though.

huangapple
  • 本文由 发表于 2017年6月5日 19:36:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/44368080.html
匿名

发表评论

匿名网友

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

确定