Skip to content

Instantly share code, notes, and snippets.

@jamesrr39
Last active July 12, 2023 18:21
Show Gist options
  • Save jamesrr39/c45a1aff4d3fd9dc2949 to your computer and use it in GitHub Desktop.
Save jamesrr39/c45a1aff4d3fd9dc2949 to your computer and use it in GitHub Desktop.
Using stdout and stdin from other programs in Golang

Go program interaction

Example of how to use stdout and stdin from other programs in golang

Requires go

Run

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"
@etwhalen
Copy link

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.

@eff-kay
Copy link

eff-kay commented Aug 2, 2018

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...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment