duanla4959
2012-05-28 08:26
浏览 39
已采纳

如何在Go中传递多个命令?

How can I pipe several external commands together in Go? I've tried this code but I get an error that says exit status 1.

package main

import (
    "io"
    "log"
    "os"
    "os/exec"
)

func main() {
    c1 := exec.Command("ls")
    stdout1, err := c1.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }

    if err = c1.Start(); err != nil {
        log.Fatal(err)
    }
    if err = c1.Wait(); err != nil {
        log.Fatal(err)
    }

    c2 := exec.Command("wc", "-l")
    c2.Stdin = stdout1

    stdout2, err := c2.StdoutPipe()
    if err != nil {
        log.Fatal(err)
    }

    if err = c2.Start(); err != nil {
        log.Fatal(err)
    }
    if err = c2.Wait(); err != nil {
        log.Fatal(err)
    }

    io.Copy(os.Stdout, stdout2)
}

图片转代码服务由CSDN问答提供 功能建议

如何在Go中将多个外部命令传递到一起? 我已经尝试过此代码,但收到错误消息,提示退出状态1

 包main 
 
import(
“ io”  
“ log” 
“ os” 
“ os / exec” 
)
 
func main(){
 c1:= exec.Command(“ ls”)
 stdout1,err:= c1。  StdoutPipe()
,如果错误!= nil {
 log.Fatal(err)
} 
 
,如果错误= c1.Start();  err!= nil {
 log.Fatal(err)
} 
如果err = c1.Wait();  err!= nil {
 log.Fatal(err)
} 
 
 c2:= exec.Command(“ wc”,“ -l”)
 c2.Stdin = stdout1 
 
 stdout2,err  := c2.StdoutPipe()
如果错误!= nil {
 log.Fatal(err)
} 
 
如果错误= c2.Start();  err!= nil {
 log.Fatal(err)
} 
如果err = c2.Wait();  err!= nil {
 log.Fatal(err)
} 
 
 io.Copy(os.Stdout,stdout2)
} 
   
 
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

6条回答 默认 最新

  • douyi3760 2012-05-28 08:31
    最佳回答

    StdoutPipe returns a pipe that will be connected to the command's standard output when the command starts. The pipe will be closed automatically after Wait sees the command exit.

    (from http://golang.org/pkg/os/exec/#Cmd.StdinPipe )

    The fact you do c1.Wait closes the stdoutPipe.

    I made a working example (just a demo, add error catching!) :

    package main
    
    import (
        "bytes"
        "io"
        "os"
        "os/exec"
    )
    
    func main() {
        c1 := exec.Command("ls")
        c2 := exec.Command("wc", "-l")
    
        r, w := io.Pipe() 
        c1.Stdout = w
        c2.Stdin = r
    
        var b2 bytes.Buffer
        c2.Stdout = &b2
    
        c1.Start()
        c2.Start()
        c1.Wait()
        w.Close()
        c2.Wait()
        io.Copy(os.Stdout, &b2)
    }
    
    评论
    解决 无用
    打赏 举报
查看更多回答(5条)

相关推荐 更多相似问题