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

报告相同问题?

悬赏问题

  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?
  • ¥15 错误 LNK2001 无法解析的外部符号
  • ¥50 安装pyaudiokits失败
  • ¥15 计组这些题应该咋做呀
  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题