[英]Convert complex command into python subprocess
I have the following command: 我有以下命令:
$ ffmpeg -i http://url/1video.mp4 2>&1 | perl -lane 'print $1 if /(\d+x\d+)/'
640x360
I'm trying to set the output of this command into a python variable. 我正在尝试将此命令的输出设置为python变量。 Here is what I have so far:
这是我到目前为止:
>>> from subprocess import Popen, PIPE
>>> p1 = Popen(['ffmpeg', '-i', 'http://url/1video.mp4', '2>&1'], stdout=PIPE)
>>> p2=Popen(['perl','-lane','print $1 if /(\d+x\d+)/'], stdin=p1.stdout, stdout=PIPE)
>>> dimensions = p2.communicate()[0]
''
What am I doing incorrectly here, and how would I get the correct value for dimensions? 我在这里做错了什么,以及如何获得尺寸的正确值?
In general, you can replace a shell pipeline with this pattern: 通常,您可以使用以下模式替换shell管道 :
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
p1.stdout.close() # Allow p1 to receive a SIGPIPE if p2 exits.
output = p2.communicate()[0]
However, in this case, no pipeline is necessary: 但是,在这种情况下,不需要管道:
import subprocess
import shlex
import re
url='http://url/1video.mp4'
proc=subprocess.Popen(shlex.split('ffmpeg -i {f}'.format(f=url)),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
dimensions=None
for line in proc.stderr:
match=re.search(r'(\d+x\d+)',line)
if match:
dimensions=match.group(1)
break
print(dimensions)
No need to call perl
from within python. 无需在python中调用
perl
。
If you have the output from ffmpeg in a variable, you can do something like this: 如果你在变量中有ffmpeg的输出,你可以这样做:
print re.search(r'(\d+x\d+)', str).group()
Note the “ shell
” argument to subprocess.Popen
: this specifies whether the command you pass is parsed by the shell or not. 请注意
subprocess.Popen
的“ shell
”参数:this指定您传递的命令是否由shell解析。
That “ 2>&1
” is one of those things that needs to be parsed by a shell, otherwise FFmpeg (like most programs) will try to treat it as a filename or option value. “
2>&1
”是需要由shell解析的东西之一,否则FFmpeg(像大多数程序一样)会尝试将其视为文件名或选项值。
The Python sequence that most closely mimics the original would probably be more like 最接近模仿原始的Python序列可能更像
p1 = subprocess.Popen("ffmpeg -i http://url/1video.mp4 2>&1", shell = True, stdout = subprocess.PIPE)<BR>
p2 = subprocess.Popen(r"perl -lane 'print $1 if /(\d+x\d+)/'", shell = True, stdin = p1.stdout, stdout = subprocess.PIPE)<BR>
dimensions = p2.communicate()[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.