dongtui9168 2018-01-16 08:12
浏览 121
已采纳

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

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?

  • 写回答

1条回答 默认 最新

  • dongzou1964 2018-01-16 08:44
    关注

    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())
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog