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 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序