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