douxiyi2418 2016-02-05 10:16
浏览 369
已采纳

Golang读取命令每行输出一行

I would like to read an output command line per line. For this I use the StdoutPipe method and the bufio library:

package main

import (
        "encoding/json"
        "fmt"
        "log"
        "os/exec"
        "bufio"
)


func main() {
        cmd := exec.Command("printf", "{\"Name\": \"Bob\", \"Age\": 1}
%.0s", "{1..5}")
        stdout, err := cmd.StdoutPipe()
        if err != nil {
                log.Fatal(err)
        }
        scanner := bufio.NewScanner(stdout)
        if err := cmd.Start(); err != nil {
                log.Fatal(err)
        }
        var person struct {
                Name string
                Age  int
        }
        for scanner.Scan() {
                if err := json.Unmarshal([]byte(scanner.Text()), &person); err != nil {
                        log.Fatal(err)
                } else {
                        fmt.Printf("%s is %d years old
", person.Name, person.Age)
                }
        }
        if err := cmd.Wait(); err != nil {
                log.Fatal(err)
        }
}

I should obtain 5 lines:

$ printf "{\"Name\": \"Bob\", \"Age\": 1}
%.0s" {1..5}
{"Name": "Bob", "Age": 1}
{"Name": "Bob", "Age": 1}
{"Name": "Bob", "Age": 1}
{"Name": "Bob", "Age": 1}
{"Name": "Bob", "Age": 1}

The point is that I only get the first line. I am quite new on Goand I guess the usage of the StdoutPipe is incorrect.

  • 写回答

1条回答 默认 最新

  • dpppic5186 2016-02-05 11:50
    关注

    {1..5} is expanded to 1 2 3 4 5 by the shell, so you must do it yourself:

    cmd := exec.Command("printf", `{"Name": "Bob", "Age": %s}
    `, `1`, `2`) // etc.
    

    Also note the use of raw strings, its much more convenient than constantly escaping everything. And on a related note, instead of []byte(scanner.Text()) you should really use scanner.Bytes().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何通过交互分析得出某高危患者对放疗获益更多
  • ¥15 相关性分析中,p<0.05, r=0.29,怎么评价相关性呢
  • ¥15 docker部署Mongodb后输入命令报错?
  • ¥15 将下列流程图转变成python程序代码
  • ¥15 我需要全国每个城市的最新小区名字等数据。
  • ¥15 开发一个小区生态的小程序
  • ¥15 如何解决Excel中dependent dropdown list 的问题
  • ¥15 MddBootstrapInitialize2失败
  • ¥15 LCD Flicker
  • ¥15 esp32在micropython环境下使用ssl/tls连接mqtt服务器出现以下报错Connected on 192.168.154.223发生意外错误: 5无法连接到 MQTT 代理,如何解决?