gpt4 book ai didi

go - 如何获取命令的输出

转载 作者:行者123 更新时间:2023-12-01 22:08:51 24 4
gpt4 key购买 nike

我正在从Go代码中调用python脚本:

package main
import (
"os/exec"
"os"
"fmt"
"time"
"encoding/json"
)

func main() {
cmd := exec.Command("python","/home/devendra/Desktop/sync/blur_multithread.py","http://4.imimg.com/data4/TP/ED/NSDMERP-28759633/audiovideojocks.png")
var logs=make(map[string]interface{})
logs["tes"]=os.Stdout
_ = cmd.Run()
WriteLogs(logs)//Writelog is my function which logs everything in a file
}

func WriteLogs(logs map[string]interface{}){
currentTime := time.Now().Local()
jsonLog, err := json.Marshal(logs)
if err != nil {
fmt.Println(err.Error())
}

jsonLogString := string(jsonLog[:len(jsonLog)])
logfile := "/home/devendra/ImageServiceLogs/"+ "ImageServiceLogs_" + currentTime.Format("2006-01-02") + ".txt"
if logfile == "" {
fmt.Println("Could not find logfile in configuration ...!!!")
} else {

jsonLogFile, err := os.OpenFile(logfile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0644)
defer jsonLogFile.Close()
if err != nil {
fmt.Println(err.Error())
}

jsonLogFile.WriteString(jsonLogString + "\n")
}
}

但是当我的python脚本给我输出时,tes字段的日志值是null。如何在我的代码中获取python脚本的输出?

最佳答案

根据官方文档示例,exec.Cmd.Ouput() ([]byte, error)将在命令运行完成后为您提供命令的sdout。

https://golang.org/pkg/os/exec/#Cmd.Output

package main

import (
"fmt"
"log"
"os/exec"
)

func main() {
out, err := exec.Command("date").Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("The date is %s\n", out)
}

要同时接收该过程的stdout和stderr,编写者应使用 exec.Cmd.CombinedOutput https://golang.org/pkg/os/exec/#Cmd.CombinedOutput

如果有人想实时接收到其终端的命令输出,则编写者应将 exec.Cmd.Stdoutexec.Cmd.Stderr属性分别设置为 os.Stdoutos.Stderr,并调用 exec.Cmd.Run() error方法。

https://golang.org/pkg/os/exec/#Cmd
https://golang.org/pkg/os/exec/#Cmd.Run
package main

import (
"fmt"
"log"
"os"
"os/exec"
)

func main() {
cmd := exec.Command("date")
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("The date is %s\n", out)
}

要转发输出并同时捕获输出,编写者应寻求 io包的帮助以使用 io.MultiWriter
https://golang.org/pkg/io/#MultiWriter
package main

import (
"fmt"
"io"
"log"
"os"
"os/exec"
)

func main() {
stdout := new(bytes.Bufer)
stderr := new(bytes.Bufer)
cmd := exec.Command("date")
cmd.Stdout = io.MultiWriter(os.Stdout, stdout)
cmd.Stderr = io.MultiWriter(os.Stderr, stderr)
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
fmt.Printf("The date is %s\n", out)
}

或者,您可以使用 exec.Cmd.{Stdout,Stderr}Pipe()参见官方文档示例 https://golang.org/pkg/os/exec/#Cmd.StdoutPipe

关于go - 如何获取命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58766508/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com