3

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?

1
  • I don't know perl, but I bet you can do it in Python too without spawning perl interpreter. For a solution, try deleting 2>&1 Commented Sep 10, 2011 at 21:13

3 Answers 3

3

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice! perhaps add a link to docs.python.org where the shlex-trick is described?
3

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

Comments

0

Note the “shell” argument to subprocess.Popen: this specifies whether the command you pass is parsed by the shell or not.

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.

The Python sequence that most closely mimics the original would probably be more like

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.