duanjue2576 2015-04-06 14:15
浏览 13

前往:无法将git的输出传送到自定义管道

I'm trying to forward the Stdout of "git clone somerepo ./" to log. Unfortunately, only the first line gets piped and everything else discarded.

package main

import (
    "os/exec"
    "log"
)


type pipe struct {}

func (p *pipe) Write(d []byte) (n int, err error) {
    log.Printf("Git subcommand: %s", d)
    return len(d), nil
}

func main() {
    e := exec.Command("git", "clone", "https://github.com/some/repo", "./DATA")
    p := &pipe{}
    e.Stdout = p
    e.Stderr = p
    _ = e.Run()
}

This code results in: 2015/04/06 16:47:19 Git subcommand: Cloning into './DATA'...

Whilst a slight modification:

    e.Stdout = os.Stdout
    e.Stderr = os.Stderr

Prints out the correct result (but in the output of the cmd line, not a custom pipe)

Cloning into 'D:\Local\Temp\915593bb-0aae-4678-adf0-56930d519ee1'...
remote: Counting objects: 118, done.
remote: Compressing objects: 100% (16/16), done.
rRemote: Total 118 (delta 7), reused 0 (delta 0), peceiving objects:  38% (45/
Receiving objects:  40% (48/118)
Receiving objects: 100% (118/118), 22.35 KiB | 0 bytes/s, done.
Resolving deltas: 100% (53/53), done.
Checking connectivity... done.
Cloning repository was successful

In both cases, the repository got cloned successfully, just the output isn't being catched right.

CombinedOutput() as well as Output() have the same broken behaviour:

func main() {
    o, err := exec.Command("git", "clone", "https://github.com/some/repo.git", "./DATA").CombinedOutput()
    if err != nil {
        log.Fatal(err)
    }
    log.Printf("%s", o)
}

What am I doing wrong?


Using scanners doesn't help either:

func main() {
    e := exec.Command("git", "clone", "https://github.com/some/repo", "./DATA")
    op, _ := e.StdoutPipe()
    ep, _ := e.StderrPipe()
    go func() {
        scanner := bufio.NewScanner(op)
        for scanner.Scan() {
            log.Printf("Scanner got: ", scanner.Text())
        }
    }()
    go func() {
        scanner := bufio.NewScanner(ep)
        for scanner.Scan() {
            log.Printf("Scanner got: %s", scanner.Text())
        }
    }()
    _ = e.Run()
}

Results in:

2015/04/06 16:54:21 Scanner got: Cloning into './DATA'...
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 linux驱动,linux应用,多线程
    • ¥20 我要一个分身加定位两个功能的安卓app
    • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
    • ¥15 IAR程序莫名变量多重定义
    • ¥15 (标签-UDP|关键词-client)
    • ¥15 关于库卡officelite无法与虚拟机通讯的问题
    • ¥15 目标检测项目无法读取视频
    • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
    • ¥100 求采集电商背景音乐的方法
    • ¥15 数学建模竞赛求指导帮助