doutuan8887 2018-11-17 11:13
浏览 221
已采纳

管道命令并使用命令重定向golang中的输出

Here is my code :

package main

import (
    "fmt"
    "os"
    "os/exec"
    "strconv"
    "time"
)

func main() {
    year, month, day := time.Now().Date()
    monthI := int(month)
    fmt.Println("toto")
    date := strconv.Itoa(year)+"_"+strconv.Itoa(monthI)+"_"+strconv.Itoa(day)
    nameSnapshot := "storedb@backup_"+date
    args := []string{"snapshot",nameSnapshot}
    cmd := exec.Command("zfs", args...)
    err := cmd.Run()
    if err != nil {
        os.Stderr.WriteString(err.Error())
    }
    args = []string{"send",nameSnapshot,"|","gzip",">","backup_"+date+".gz"}
    cmd = exec.Command("zfs", args...)
    err = cmd.Run()
    if err != nil {
        os.Stderr.WriteString(err.Error())
    }


}

I would like to do it in one command.

My second line the zfs send command seems not working.

How to pipe and redirect the ouput in golang with cmd.exec ?

Regards

  • 写回答

1条回答 默认 最新

  • douou8954 2018-11-17 12:39
    关注

    This is a simplified version of how you would achieve this:

    outfile, _ := os.OpenFile("backup.gz", os.O_RDWR|os.O_CREATE, 0755)
    
    // your zfs command
    zfs := exec.Command("zfs", "send", "storedb@backup")
    gzip := exec.Command("gzip", "-cf") // gzip to stdout (-cf)
    gzip.Stdin, _ = zfs.StdoutPipe()    // zfs stdout to gzip stdin
    gzip.Stdout = outfile               // write output of gzip to outfile
    gzip.Start()                        // gzip start waiting for input
    zfs.Run()                           // zfs start command
    gzip.Wait()                         // gzip wait for pipe to close
    outfile.Close()
    

    It is equivalent to this command in the shell:

    zfs send stored@backup | gzip -cf > backup.gz
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算