python - 如何使用 exec 命令将字节数据从 golang 发送到 python?

标签 python go io stdin

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/

相关文章:

python - 用换行符替换一些特殊字符\n

go - 如何在Golang中使用gofpdi.importPage()导入下载的空白pdf文件?

java - 为什么将 FileOutputStream 打开到二进制文件会损坏它?

python - Pygame 碰撞检测有缺陷

python - 如何打印异常?

python - 如何合并 csv 文件并使用 python 添加标题行?

postgresql - Goroutines 阻塞连接池

go - 使用 govmomi 库在 golang 中实现零点偏差

java - 如何将多个不同的 InputStream 链接到一个 InputStream

c - 这个 C 程序究竟是如何从这个二进制文件中读取数据的?