dongtui9168
dongtui9168
2018-01-16 08:12

如何使用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 dongzou1964 3年前

    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())
    
    点赞 评论 复制链接分享