调用 python 脚本并捕获二进制输出

我想在 go 中操作图像,并且我已经有一个 python 脚本来修改图像。我只需要从 python 脚本发送图像即可。为此,我按以下方式进行:


Python脚本:


image = image_in_bytes


print (image)

去脚本:


cmd := exec.Command("python", "image.py")

stdout, err := cmd.StdoutPipe()

if err != nil {

    panic(err)

}

err = cmd.Start()

if err != nil {

    panic(err)

}


body, _ := ioutil.ReadAll(stdout) //I need the image in []byte

cmd.Wait()

但是使用上面的代码 golang 会永远等待,没有任何输出......


任何想法?


慕沐林林
浏览 82回答 1
1回答

HUX布斯

对我来说工作完美,如下所述:>>> with open("osx.png","rb") as imageFile:...&nbsp; &nbsp; &nbsp;img = repr(imageFile.read())>>> imageFile.close()>>> with open("sample.py","w") as pyfile:...&nbsp; &nbsp; &nbsp;pyfile.write(img)>>> pyfile.close()然后,我手动编辑 pyfile 看起来像img = '\x89PNG\r\n\x1a\n[remainder skipped for brevity]'print(img)最后但并非最不重要的是,我运行了以下代码:&nbsp; &nbsp; cmd := exec.Command("python", "sample.py")&nbsp; &nbsp; stdout, err := cmd.StdoutPipe()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; err = cmd.Start()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; body, err := ioutil.ReadAll(stdout) //I need the image in []byte&nbsp; &nbsp; cmd.Wait()&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("error reading bytes: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; log.Printf("Read %d bytes", len(body))&nbsp; &nbsp; o, err := os.OpenFile("img.png", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0660)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("opening img.png: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; defer o.Close()&nbsp; &nbsp; n, err := o.Write(body)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatalf("writing image to file: %s", err)&nbsp; &nbsp; }&nbsp; &nbsp; if n < len(body) {&nbsp; &nbsp; &nbsp; &nbsp; log.Fatal("short write")&nbsp; &nbsp; }完整代码可在https://gist.github.com/mwmahlberg/eb47495f68bed4e3cb8073447efdb53d下找到我想可以肯定的是,您在 Python 文件中存储图像数据的方式有些奇怪。
打开App,查看更多内容
随时随地看视频慕课网APP