如何使用 exec 命令将字节数据从 golang 发送到 python?
How to send bytes data from golang to python using exec command?
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 on your exec.Command
. This gives you a WriteCloser 访问进程的标准输入,当进程终止时它会自动关闭。
写入 stdin 必须在与 cmd.Run
调用不同的 goroutine 中完成。
这是一个将 "Hi There!"(作为字节数组)写入标准输入的简单示例。
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())
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 on your exec.Command
. This gives you a WriteCloser 访问进程的标准输入,当进程终止时它会自动关闭。
写入 stdin 必须在与 cmd.Run
调用不同的 goroutine 中完成。
这是一个将 "Hi There!"(作为字节数组)写入标准输入的简单示例。
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())