Often a program needs to start other programs. Not everything can be done in a single Go program. So we can invoke external processes.
Then we create a Command with 1 or 2 arguments (we pass the process name, and its arguments in separately).
To begin, we Start a Firefox process. You will need to adjust the path to the Firefox application yourself—on Linux this is firefox-bin.
func
, and a Firefox window pops upon the computer. Start()
does not wait for the process to end.package main import ( "fmt" "os/exec" ) func main() { // Create command. // ... The application is not executed yet. cmd := exec.Command("/home/sam/Downloads/firefox/firefox-bin") fmt.Println("Starting command") // Run firefox-bin. // ... This starts a web browser instance. // It does not wait for it to finish. cmd.Start() fmt.Println("DONE") }Starting command DONE
Here we start an external process with an argument. We pass the argument string
to the Command, after the process name itself.
package main import ( "fmt" "os/exec" ) func main() { // New command with 1 argument. browser := "/home/sam/Downloads/firefox/firefox-bin" argument := "https://en.wikipedia.org/"; cmd := exec.Command(browser, argument) // Run firefox-bin and load URL specified in argument. cmd.Start() fmt.Println("DONE") }DONE
Unlike Start, the Run()
func
waits for the process to end before returning. Here we Run()
a Python program. When the program ends, we read its exit value (which is 100 here).
package main import ( "fmt" "os/exec" ) func main() { // Run this Python program from Go. cmd := exec.Command("python", "/home/sam/test.py") fmt.Println("Running") // Wait for the Python program to exit. err := cmd.Run() fmt.Println("Finished:", err) }Running Finished: exit status 100# This is a Python program. exit(100)
LookPath
, slice argumentsThis is a more complex, and probably useful, example. Sometimes we need to use LookPath
to get the actual program location to invoke it correctly.
string
slice to the exec.Command
method for the arguments.string
slice is to be passed to the variable-argument method Command()
.string
. Use LookPath
to get the program's location.package main import ( "fmt" "os/exec" ) func main() { // Get path for cwebp program. exe, _ := exec.LookPath("cwebp") // Build up argument string with slice. arguments := []string{} arguments = append(arguments, "/Users/sam/todo.png") arguments = append(arguments, "-o") arguments = append(arguments, "/Users/sam/todo.webp") // Call exec.Command with arguments string. cmd := exec.Command(exe, arguments...) // Run program. err := cmd.Run() fmt.Println(err) }<nil>
With Command, we launch external processes like Firefox and Python (or any EXE or script). We must invoke Start()
or Run()
to execute the code.