duansengcha9114 2018-06-29 01:54
浏览 131
已采纳

如何将xml解码器连接到go exec的stdoutPipe()

I'm having some trouble linking things up here. What am I doing incorrectly?

package main

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

func checkError(err error) {
    if err != nil {
        log.Fatalf("Error: %s", err)
    }
}

func metrics() {
    cmd := exec.Command(
        "nvidia-smi",
        "--query",
        "--xml-format")

    out, err := cmd.StdoutPipe()
    checkError(err)

    cmd.Start()

    defer cmd.Wait()

    go func() {
        var data interface{}
        dec := xml.NewDecoder(out)
        dec.Decode(&data)
        fmt.Printf("Data: %+v
", data)
    }()

    //go io.Copy(os.Stdout, out)
}

func main() {
    metrics()
}

Result after running program is: Data:

  • 写回答

1条回答 默认 最新

  • douzhi19900102 2018-06-29 02:52
    关注

    Things seem to be "linked" correctly.

    Problem is likely to be here:

    var data interface{}
    

    You then do:

    dec.Decode(&data)
    

    But that won't work.

    You need to pass in a struct that can actually be used to decode the fields in the XML that the nvidia-smi command returns.

    Find below a modified example (replacing your nvidia-smi for an echo command to make it return a sample XML).

    You should adjust the struct to be able to map to the actual XML you'll receive.

    By the way:

    • You should check the error returned by decode just in case
    • I don't understand why you are decoding in a separate goroutine. I left it like that in the modified example, but it would work if you do it right in the same goroutine as well.

    Example:

    package main
    
    import (
        "log"
        "os/exec"
        "fmt"
        "encoding/xml"
    )
    
    func checkError(err error) {
        if err != nil {
            log.Fatalf("Error: %s", err)
        }
    }
    
    type Result struct {
        Value int `xml:"value"`
    }
    
    func metrics() {
        cmd := exec.Command(
            "echo", "-n",
            `<result><value>1</value></result>`)
    
        out, err := cmd.StdoutPipe()
        checkError(err)
    
        cmd.Start()
    
        defer cmd.Wait()
    
        go func() {
            var data Result
            dec := xml.NewDecoder(out)
            err = dec.Decode(&data)
            checkError(err)
            fmt.Printf("Data: %+v
    ", data)
        }()
    
        //go io.Copy(os.Stdout, out)
    }
    
    func main() {
        metrics()
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 组策略中的计算机配置策略无法下发
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题