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?
Asked
Active
Viewed 1,466 times
5

General Grievance
- 4,555
- 31
- 31
- 45

anselm
- 842
- 2
- 9
- 22
-
1I don't think you can get more then what the help shows you. You can call it using the `os/exec` package. – Jun 05 '17 at 11:49
2 Answers
1
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/

Stephen
- 11
- 1
-2
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.
-
The first argument to exec.Command is the name of the program. The name of the program is `go`, not `go run lib/main.go`. See the @Stephen's answer for correct way to run the go command. – Charlie Tumahai Aug 26 '20 at 23:51