简体   繁体   中英

FFMPEG python check if dictionary key exists

I want to check if there is a dictionary key: "data["streams"][1]["codec_name"]" and if there is one to print the values of couple of keys and if not to print "No Audio". Actually if there is no audio the whole data["streams"][1] is missing. Right now the script is always returning No Audio even if the audio exists. What I am doing wrong?

#!/usr/bin/env python
import subprocess
import json

input_file = raw_input("Please enter the input file path: ")

returned_data = subprocess.check_output(['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', input_file])
data = json.loads(returned_data.decode('utf-8'))
print "==========================Audio============================="
if 'data["streams"][1]["codec_name"]' in data:
        print "Codec: %s" %(data["streams"][1]["codec_name"])
        print "Sample Rate: %.3f KHz" %(int(data["streams"][1]["sample_rate"])/1000)
        print "Bitrate: %d Kbps" %(int(data["streams"][1]["bit_rate"])/1000)
else:
        print "NO AUDIO"

When you do this

if 'data["streams"][1]["codec_name"]' in data:

You are asking if data has a key called data["streams"][1]["codec_name"] which it doesn't so it will never show up. Additionally, you are trying to reference a dict key within a list within another dict, the pythonic way of doing this would be:

try:
    codec = data["streams"][1]["codec_name"]
    # print your information here
except (KeyError, IndexError):
    print('no audio')

What this does is attempt to access that variable. You catch KeyError if either key codec_name or streams does not exist, and you catch IndexError if [1] does not exist.

However, as an ffmpeg nerd I would suggest a different way of doing this. It sounds like your goal is to print audio information if a file has audio, and print no audio if it doesn't have any audio. The problem with the example I just gave is that it will only work for you if the audio is the second stream of the media file. Audio usually comes after video, but sometimes it is out of order, and sometimes there are multiple audio streams so what I recommend is that you loop over each stream, check to see if it is an audio stream and then if it is audio, print the information. This will show more than 1 audio stream regardless of its order:

audio_streams = 0

if 'streams' in data:
    for stream in streams:
        if stream['codec_type'] == 'audio':
            # print your info here (I'm abbreviating)
            print(stream['codec_name'])

if audio_streams == 0:
    print('no audio...')

If you really only want data from 1 audio stream, I would still do the loop but put a break statement after you print the information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM