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.1k Golang : Get a list of crosses(instruments) available to trade from Oanda account
+7.6k Golang : Convert word to its plural form example
+4.7k PHP : Convert CSV to JSON with YQL example
+20.6k SSL : How to check if current certificate is sha1 or sha2
+14.1k Golang : Get all local users and print out their home directory, description and group id
+9.9k Golang : How to transmit update file to client by HTTP request example
+16.7k Golang : Login and logout a user after password verification and redirect example
+18.7k Golang : How to count the number of repeated characters in a string?
+7.6k Golang: Prevent over writing file with md5 hash
+11.6k Golang : "https://" not allowed in import path