Example of how to use stdout and stdin from other programs in golang
Requires go
go run parentprocess.go
package main | |
import ( | |
"bufio" | |
"io" | |
"log" | |
"os" | |
"os/exec" | |
) | |
func main() { | |
cmd := exec.Command("./subprocess.sh") | |
cmd.Stderr = os.Stderr | |
stdin, err := cmd.StdinPipe() | |
if nil != err { | |
log.Fatalf("Error obtaining stdin: %s", err.Error()) | |
} | |
stdout, err := cmd.StdoutPipe() | |
if nil != err { | |
log.Fatalf("Error obtaining stdout: %s", err.Error()) | |
} | |
reader := bufio.NewReader(stdout) | |
go func(reader io.Reader) { | |
scanner := bufio.NewScanner(reader) | |
for scanner.Scan() { | |
log.Printf("Reading from subprocess: %s", scanner.Text()) | |
stdin.Write([]byte("some sample text\n")) | |
} | |
}(reader) | |
if err := cmd.Start(); nil != err { | |
log.Fatalf("Error starting program: %s, %s", cmd.Path, err.Error()) | |
} | |
cmd.Wait() | |
} |
#!/bin/bash | |
echo "Enter some text:" | |
read -r input | |
echo "you typed: $input" |
Yes you can use the aync example in this link. Just create a goroutine around the stdin, stdout, and take relevant action. Let me know if you need help...
Thanks for posting this. I have a question though. If I understand this correctly it is actually running everything at once. Is there a way to do a similar thing where it is more interactive? I'd like to wait for data to be presented by the program and then process it as it comes in.