Python interactive execution golang

Look! there's a flower!·2024년 9월 19일

Sometimes we need to execute a python script line by line programmatically.
python interactive mode with replaced stdin, stdout, stderr can handle it.
Overall flow control is as follows:

import ( 
  "bufio"
  "io"
  "os/exec" 
  others...
)

cmd := exec.Command("python3", "-i")
stdin, err := cmd.StdinPipe()
stdout, err := cmd.StdoutPipe()
stderr, err := cmd.StderrPipe()
err = cmd.Start()

go func(r io.Reader) { // show output and error from stdout and stderr
  scanner := bufio.NewScanner(r)
  for scanner.Scan() {
      fmt.Println(scanner.Text())
  }
}(io.MultiReader(stdout, stderr))

read each lines from file and feed it to stdin
   io.WriteString(stdin, line)

stdin.Close()
err = cmd.Wait() // wait until finish
profile
Why don't you take a look around for a moment?

0개의 댓글