在Golang中使用管道执行命令

huangapple go评论89阅读模式
英文:

Running command with pipe in Golang exec

问题

我正在尝试使这里的示例工作,使用phantomjs记录网页并将stdout(即图像)传输到ffmpeg命令以创建视频。所需运行的命令如下:

phantomjs runner.js | ffmpeg -y -c:v png -f image2pipe -r 25 -t 10  -i - -c:v libx264 -pix_fmt yuv420p -movflags +faststart dragon.mp4

如果我直接在终端中运行类似版本的命令,它可以正常工作。问题是我需要通过Golang的os/exec包运行上述命令。使用以下方法:

cmd := exec.Command(parts[0], parts[1:]...)

方法中,第一个参数是要执行的命令的基本可执行文件,并且它不支持管道。我希望能够通过一个命令使其工作,这样我就不必将所有图像写入文件,然后再运行第二个ffmpeg命令来读取所有这些图像。有什么建议吗?

英文:

I am trying to get the example from here working to record a webpage with phantomjs and pipe the stdout, which are images, to the ffmpeg command to create the video. The command stated that you need to run is:

phantomjs runner.js | ffmpeg -y -c:v png -f image2pipe -r 25 -t 10  -i - -c:v libx264 -pix_fmt yuv420p -movflags +faststart dragon.mp4

If I run a similar version of that command directly in the terminal, I can get it working just fine. The issue is that I need to run the above command through the Golang os/exec package. With the:

cmd := exec.Command(parts[0], parts[1:]...)

method, the first parameter is the base executable of the command being executed and it is not honoring the pipe. I would like to get this working in one command so I don't have to write all the images to files and then run a second ffmpeg command to read from all of those images. Any suggestions?

答案1

得分: 11

我认为这会对你有所帮助。

cmd := "phantomjs runner.js | ffmpeg -y -c:v png -f image2pipe -r 25 -t 10 -i - -c:v libx264 -pix_fmt yuv420p -movflags +faststart dragon.mp4"
output, err := exec.Command("bash","-c",cmd).Output()
if err != nil {
return fmt.Sprintf("执行命令失败:%s", cmd)
}
fmt.Println(string(output))

英文:

I think this will help you.

     cmd := "phantomjs runner.js | ffmpeg -y -c:v png -f image2pipe -r 25 -t 10  -i - -c:v libx264 -pix_fmt yuv420p -movflags +faststart dragon.mp4"
     output, err := exec.Command("bash","-c",cmd).Output()
     if err != nil {
            return fmt.Sprintf("Failed to execute command: %s", cmd)
     }
     fmt.Println(string(output))

huangapple
  • 本文由 发表于 2016年9月15日 01:40:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/39496572.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定