Reputation: 515
Main.go
func main() {
bytearray=getbytearray()//getting an array of bytes
cmd := exec.Command("python3", "abc.py")
in:=cmd.Stdin
cmd.Run()
}
I want to send the byte array as input for the python script
abc.py
import sys
newFile.write(sys.stdin) //write the byte array got as input to the newfile
How do i send bytes from golang to python and save that into a file?
Upvotes: 1
Views: 2122
Reputation: 21055
You can access the process' stdin by calling Cmd.StdinPipe on your exec.Command
. This gives you a WriteCloser that closes automatically when the process terminates.
The write to stdin must be done in a separate goroutine from the cmd.Run
call.
Here is a simple example writing "Hi There!" (as a byte array) to stdin.
package main
import (
"fmt"
"os/exec"
)
func main() {
byteArray := []byte("hi there!")
cmd := exec.Command("python3", "abc.py")
stdin, err := cmd.StdinPipe()
if err != nil {
panic(err)
}
go func() {
defer stdin.Close()
if _, err := stdin.Write(byteArray); err != nil {
panic(err)
}
}()
fmt.Println("Exec status: ", cmd.Run())
}
You'll also want to actually read from stdin in python:
import sys
f = open('output', 'w')
f.write(sys.stdin.read())
Upvotes: 2