Mangled Output When Printing Strings From Ffprobe Stderr
I'm trying to make a simple function to wrap around FFProbe, and most of the data can be retrieved correctly. The problem is when actually printing the strings to the command line
Solution 1:
I solved this by the accepted answer in my related question.
I had forgotten about the return carriage at the end of each line. Solutions given are as follows:
- Use
universal_newlines=True
in the subprocess call.stderr = Popen(("ffprobe", file_path), shell=True, stderr=PIPE, universal_newlines=True).communicate()[1]
Stripping the whitespace around the line from
stderr
.*.communicate()[1].decode().rstrip()
to strip all whitespace at the end.*.communicate()[1].decode().strip()
to strip all wightspace around.*.communicate()[1].decode()[:-2]
to remove the last two characters.
Swallowing
\r
in the regex pattern.findall(r"(\w+)\s+:\s(.+)\r$", stderr, MULTILINE)
This is all very helpful, however I used none of these suggestions.
I didn't know that FFPROBE offers JSON output to STDOUT, but it does. The code to do that is below.
#! /usr/bin/env python3# -*- coding: utf-8 -*-from json import loads
from subprocess import check_output, DEVNULL, PIPE
defarg_builder(args, kwargs, defaults={}):
"""Build arguments from `args` and `kwargs` in a shell-lexical manner."""for key, val in defaults.items():
kwargs[key] = kwargs.get(key, val)
args = list(args)
for arg, val in kwargs.items():
ifisinstance(val, bool):
if val:
args.append("-" + arg)
else:
args.extend(("-" + arg, val))
return args
defrun_ffprobe(file_path, *args, **kwargs):
"""Use FFPROBE to get information about a media file."""return loads(check_output(("ffprobe", arg_builder(args, kwargs, defaults={"show_format": True}),
"-of", "json", file_path), shell=True, stderr=DEVNULL))
You might also get some use out of the arg_builder()
. It isn't perfect, but it's good enough for simple shell commands. It isn't made to be idiot proof, it was written with a few holes assuming that the programmer won't break anything.
Post a Comment for "Mangled Output When Printing Strings From Ffprobe Stderr"