Main.go
func main() {
bytearray=getbytearray()//getting an array of bytes
cmd := exec.Command("python3", "abc.py")
in:=cmd.Stdin
cmd.Run()
}
我想发送字节数组作为 python 脚本的输入
abc.py
import sys
newFile.write(sys.stdin) //write the byte array got as input to the newfile
我如何将字节从 golang 发送到 python 并将其保存到文件中?
最佳答案
您可以通过调用 Cmd.StdinPipe 来访问进程的标准输入在你的 exec.Command
上。这给你一个 WriteCloser进程终止时自动关闭。
对标准输入的写入必须在与 cmd.Run
调用不同的 goroutine 中完成。
这是一个简单的例子,写“你好!” (作为字节数组)到标准输入。
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())
}
您还想在 python 中实际读取标准输入:
import sys
f = open('output', 'w')
f.write(sys.stdin.read())
关于python - 如何使用 exec 命令将字节数据从 golang 发送到 python?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48276670/