Python 子进程 + mencoder 不工作,相同的命令在终端中工作
我通过 python (2.6.1) 子进程使用 mencoder (SVN-r30531-4.2.1) 时遇到问题。我正在尝试加入两个大小、编解码器等完全相同的 mp4 文件。两者都没有音频。我用来测试的代码是:
import subprocess
mp4merge = [ "mencoder", "in1.mp4", "in2.mp4", "-ovc", "copy", "-oac", "copy", "-of", "lavf", "-o", "out.mp4" ]
try:
pMerge = subprocess.Popen(mp4merge, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while pMerge.poll() == None:
for l in pMerge.stderr.readlines():
print l
if pMerge.poll() is not None:
print "Complete"
except subprocess.CalledProcessError:
print "fail"
它不起作用,它只是无限期地挂起。但是,当我通过终端(OS X 10.6.4)运行完全相同的命令时,它可以工作。命令为:
mencoder in1.mp4 in2.mp4 -ovc copy -oac copy -of lavf -o out.mp4
您可以下载视频从这里。我非常有信心这些视频不是问题,因为它可以在终端上运行。
I am having a problem using mencoder (SVN-r30531-4.2.1) through a python (2.6.1) subprocess. I am trying to join two mp4 files which are exactly the same size, codec, etc. Both have no audio. The code I am using to test is:
import subprocess
mp4merge = [ "mencoder", "in1.mp4", "in2.mp4", "-ovc", "copy", "-oac", "copy", "-of", "lavf", "-o", "out.mp4" ]
try:
pMerge = subprocess.Popen(mp4merge, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while pMerge.poll() == None:
for l in pMerge.stderr.readlines():
print l
if pMerge.poll() is not None:
print "Complete"
except subprocess.CalledProcessError:
print "fail"
And it doesn't work, it just hangs indefinitely. However, when I run the exact same command through Terminal (OS X 10.6.4) it works. The command is:
mencoder in1.mp4 in2.mp4 -ovc copy -oac copy -of lavf -o out.mp4
You can download the videos from here. I am quite confident the videos aren't the probelm because of the fact that it works from Terminal.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是
pMerge.stderr.readlines()
永远阻塞,直到进程结束。它会在继续之前读取所有行。由于 mencoder 向 stdout 写入了大量数据,因此 stdout 缓冲区已满,mencoder 正在等待其清空,然后才能继续。所以这个过程永远不会结束。
这里有一种方法可以做到同样的事情,不会挂起:
另一个允许您逐行读取输出的选项是将 stderr 重定向到 stdout,然后只读取 stdout,(不要使用 readlines() 因为它会阻塞,直到读取所有行):
这会将 stderr 重定向到 stdout,这样缓冲区就不会填满。
The problem here is that
pMerge.stderr.readlines()
blocks forever until the process is over. It reads all lines before continuing.Since mencoder writes a lot to the stdout, the stdout buffer is filled and mencoder is waiting for it to empty before it can continue. So the process never ends.
Here's a way to do the same, that won't hang:
Another option that allows you to read the output line-by-line is to redirect stderr to stdout, and then read only stdout, (don't use readlines() since it blocks until all lines are read):
This redirects stderr to stdout so your buffer won't fill.