Search code examples
gosubprocesspipeexecpiping

Pipe string into STDIN of command in Golang


I want to replicate the following subprocess.run function call in Golang. What would be the correct way to do it?

subprocess.run(['kinit', username], input=password.encode())

So far, I've figured out how to use exec.Command to run external commands, but what's confusing me is passing strings as input to STDIN of that command. Python's subprocess.run has a handy input parameter that takes care of this, how can I achieve similar results in Golang?


Solution

  • I figured out how to do it.

    package main
    
    import "os/exec"
    import "strings"
    
    func main() {
        cmd := exec.Command("kinit", username)
        cmd.Stdin = strings.NewReader(password)
        err := cmd.Run()
    }
    

    The Stdin attribute of the Command object is the STDIN pipe, we can set it to a strings.NewReader object containing the input string to achieve the same effect as of the Python snipped mentioned in the question.