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

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度