Go:无法将输出从git输出到自定义管道

时间:2015-04-06 14:15:56

标签: go exec stdout

我试图转发Stdout of" git clone somerepo ./"记录。不幸的是,只有第一行被管道传输而其他一切都被丢弃了。

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()
}

此代码导致:     2015/04/06 16:47:19 Git子命令:克隆到' ./ DATA' ...

稍作修改:

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

打印出正确的结果(但在cmd行的输出中,而不是自定义管道)

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

在这两种情况下,存储库都已成功克隆,只是输出没有被正确捕获。

CombinedOutput()以及Output()具有相同的破坏行为:

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)
}

我做错了什么?


使用扫描仪不会有任何帮助:

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()
}

结果:

2015/04/06 16:54:21 Scanner got: Cloning into './DATA'...

0 个答案:

没有答案