Golang : How to pipe input data to executing child process?
Problem :
Your program is executing a child process via os/exec
and you want to pipe input data to the executing process.
Solution :
Use the StdinPipe()
method and issue a .Write([]byte(your data))
to input data to the executing child process.
For example :
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("cat")
stdin, err := cmd.StdinPipe()
stdin.Write([]byte("Hello World!")) // <------ here
stdin.Close()
if err != nil {
panic(err)
}
data, err := cmd.Output()
if err != nil {
panic(err)
}
for k, v := range data {
fmt.Printf("key : %v, value : %v \n", k, string(v))
}
}
See also : Golang : Pipe output from one os.Exec(shell command) to another command
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+4.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+11.3k Golang : Remove or trim extra comma from CSV
+4.5k Clean up Visual Studio For Mac installation failed disk full problem
+16.1k Golang : Find smallest number in array
+5.6k Golang : How to determine if request or crawl is from Google robots
+44.5k Golang : Encode image to base64 example
+12.9k Golang : concatenate(combine) strings
+21.1k Golang : Read a file into an array or slice example
+28.3k Golang : Get and Set User-Agent examples
+4.1k Swift : Convert (cast) Float to Int or Int32 value
+10.2k Golang : Post data with url.Values{}