donglu7816 2019-08-21 08:18
浏览 90
已采纳

如何隐藏终端命令的输出

I have a complex ffmpeg command to execute and I need to execute using Go. The command is working, the problem is coming when I try to hide the output of command using > /dev/null 2>&1

This is my code:

cmd := exec.Command(
    "ffmpeg",
    "-y",
    "-loglevel", "warning",
    "-i", ConvertImage,
    "-i", videoInput,
    "-c:v", cv,
    "-c:a", audioCodec,
    "-crf", fmt.Sprintf("%d", crf),
    "-map", "[v]",
    "-map", "1:a?",
    "-r", fmt.Sprintf("%d", Res.FrameRate),
    "-strict",
    "-2",
    outputFile,
    "> /dev/null 2>&1",
)

Without last field "> /dev/null 2>&1", code is working ok when I try to hide the output of command, command skip without the run.

What did I do wrong? How can I fix it?

  • 写回答

1条回答 默认 最新

  • douding7189 2019-08-21 09:39
    关注

    You can simply put the output to a bytes.Buffer variable like following:

    cmd := exec.Command(
        "ffmpeg",
        "-y",
        "-loglevel", "warning",
        "-i", ConvertImage,
        "-i", videoInput,
        "-c:v", cv,
        "-c:a", audioCodec,
        "-crf", fmt.Sprintf("%d", crf),
        "-map", "[v]",
        "-map", "1:a?",
        "-r", fmt.Sprintf("%d", Res.FrameRate),
        "-strict",
        "-2",
        outputFile,
    )
    
    var execOut bytes.Buffer
    var execErr bytes.Buffer
    cmd.Stdout = &execOut
    cmd.Stderr = &execErr
    

    By doing this, both the output and the error are in the corresponding buffer.

    Now, if you want to print them, then you can use the following code snippet along with the above code:

    err := cmd.Run()
    if err != nil {
        fmt.Println("Cannot Execute cmd: ", err.Error())
    }
    outStr := execOut.String()
    errStr := execErr.String()
    if len(outStr) > 0 {
        fmt.Print(outStr)
    }
    if len(errStr) > 0 {
        fmt.Print(errStr)
    }
    

    Update: Or, if you do not need the stdout and stderr totally, then you can set the cmd.Stdout and cmd.Stderr to nil just like following:

    cmd.Stdout = nil
    cmd.Stderr = nil
    
    err := cmd.Run()
    if err != nil {
        fmt.Println("Cannot Execute cmd: ", err.Error())
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥100 chrome插件开发如何在textarea插入文本
  • ¥15 vs 创建windows 窗体应用(.net framework)项目时,出现问题,无法进入下一步
  • ¥15 如何实现安卓Socks5代理服务端,并且实现内网穿透?
  • ¥50 自有服务器搭建正向代理及负载均衡应对高并发
  • ¥15 Expected a list, got: <class 'list'>. Correct! 为什么它不输出答案而是答案的类型
  • ¥15 pbootcms筛选怎么调用出来
  • ¥15 开发板和电机具体的参数?
  • ¥100 如何对超大数据分段并进行对比处理
  • ¥50 mmc在一个管理单元检测到错误
  • ¥15 如何正确使用pyside6,使其符合LGPL?
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部