Programmatic way to call go tools

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

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包。

  1. func runBuild() {
  2. cmd := exec.Command("go", "build", "./main.go")
  3. err := cmd.Run()
  4. if err != nil {
  5. log.Fatal(err)
  6. }
  7. }

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

  1. 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.

  1. func runBuild() {
  2. cmd := exec.Command("go", "build", "./main.go")
  3. err := cmd.Run()
  4. if err != nil {
  5. log.Fatal(err)
  6. }
  7. }

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

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

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

答案2

得分: -2

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

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

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

英文:

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

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

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:

确定