Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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?

like image 233
David542 Avatar asked Jul 29 '26 09:07

David542


2 Answers

In general, you can replace a shell pipeline with this pattern:

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)
like image 147
unutbu Avatar answered Aug 01 '26 00:08

unutbu


No need to call perl from within python.

If you have the output from ffmpeg in a variable, you can do something like this:

print re.search(r'(\d+x\d+)', str).group()
like image 28
Fredrik Pihl Avatar answered Jul 31 '26 23:07

Fredrik Pihl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!