ik5xxa
Last Updated: February 25, 2016
·
3.031K
· murphyrandle
621103 10151814410385600 1552271139 o

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")
}
Say Thanks
Respond

1 Response
Add your response

14089
288ae354167f1838789a2e04db8b97b6

thank you, that's I want

over 1 year ago ·