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
+5.2k Golang : Create new color from command line parameters
+19k Golang : Secure(TLS) connection between server and client
+3k Golang : PGX CopyFrom to insert rows into Postgres database
+26.4k Golang : Move file to another directory
+11.4k Golang : "https://" not allowed in import path
+11.8k Golang : Convert IPv4 address to packed 32-bit binary format
+4.7k Golang : Grab news article text and use NLP to get each paragraph's sentences
+18.9k Golang : Count number of digits from given integer value
+14.9k Golang : Find out mime type from bytes in buffer
+22.9k Golang : Call function from another package
+4.3k Gogland : Datasource explorer