Last Updated: February 25, 2016
·
9.313K
· murphyrandle

Run a subprocess and connect to it with golang

The following code will allow you to run a subprocess with golang, and then connect it's stdout, stdin, sterr, etc. Great for triggering ssh calls!

Also, handy note, see the args ...string? That's like Python's splat. It'll expect a variable number of arguments to the function, and then using args... will pass all of those arguments on.

package main

import (
    "fmt"
    "os/exec"
        "os"
)

func exec_command(program string, args ...string) {
    cmd := exec.Command(program, args...)
    cmd.Stdin = os.Stdin;
    cmd.Stdout = os.Stdout;
    cmd.Stderr = os.Stderr;
    err := cmd.Run() 
    if err != nil {
        fmt.Printf("%v\n", err)
    }
}

func main() {
        exec_command("vagrant", "ssh")
}

1 Response
Add your response

thank you, that's I want

over 1 year ago ·