【问题标题】:JSON Python check for dataJSON Python 检查数据
【发布时间】:2017-07-23 12:06:10
【问题描述】:

所以我正在尝试编写一个脚本,该脚本正在查看 JSON 文件并检查索引为 1 的流是否存在。现在我的程序不这样做。这是程序本身。我想检查(data["streams"][1]) 是否存在,如果存在则打印所有可用音频流的编解码器、采样率和比特率。

#!/usr/bin/env python
import subprocess
import json
import os.path

# Saving the file path and the name path into input_file

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

# Loop until the user enters a valid input file

while os.path.isfile(input_file) == False:
        print "Please try again, the specified file / path don't exist!"
        input_file = raw_input("Please enter the input file path again: ")

# Execution of the ffprobe command to list the general statistics of the file. I have separated both scripts because the script for analyzing the frames is taking longer time.

returned_data = subprocess.check_output(['ffprobe', '-v', 'quiet', '-print_format', 'json', '-show_format', '-show_streams', input_file])

# Loading of the json file

data = json.loads(returned_data.decode('utf-8'))
t = (data["streams"][0]["avg_frame_rate"])
fps = [float(x) for x in t.split('/')]

# Printing of the general information about the video file

print "========================== Video ============================="
print
print "Codec: %s" %(data["streams"][0]["codec_long_name"])
print "Profile: %s" %(data["streams"][0]["profile"])
print "Resolution: %d x %d" %((data["streams"][0]["width"]), (data["streams"][0]["height"]))
print "Pixel Format: %s" %(data["streams"][0]["pix_fmt"])
print "Bits per sample: %s" %(data["streams"][0]["bits_per_raw_sample"])
print
print "========================== Audio ============================="
print
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)

这是 JSON 文件的输出。

{
    "streams": [
        {
            "index": 0,
            "codec_name": "mpeg4",
            "codec_long_name": "MPEG-4 part 2",
            "profile": "Simple Profile",
            "codec_type": "video",
            "codec_time_base": "1/24",
            "codec_tag_string": "FMP4",
            "codec_tag": "0x34504d46",
            "width": 854,
            "height": 480,
            "coded_width": 854,
            "coded_height": 480,
            "has_b_frames": 0,
            "sample_aspect_ratio": "1:1",
            "display_aspect_ratio": "427:240",
            "pix_fmt": "yuv420p",
            "level": 1,
            "chroma_location": "left",
            "refs": 1,
            "quarter_sample": "false",
            "divx_packed": "false",
            "r_frame_rate": "24/1",
            "avg_frame_rate": "24/1",
            "time_base": "1/24",
            "start_pts": 0,
            "start_time": "0.000000",
            "duration_ts": 14315,
            "duration": "596.458333",
            "bit_rate": "2500431",
            "nb_frames": "14315",
            "disposition": {
                "default": 0,
                "dub": 0,
                "original": 0,
                "comment": 0,
                "lyrics": 0,
                "karaoke": 0,
                "forced": 0,
                "hearing_impaired": 0,
                "visual_impaired": 0,
                "clean_effects": 0,
                "attached_pic": 0,
                "timed_thumbnails": 0
            }
        },
        {
            "index": 1,
            "codec_name": "ac3",
            "codec_long_name": "ATSC A/52A (AC-3)",
            "codec_type": "audio",
            "codec_time_base": "1/48000",
            "codec_tag_string": "[0] [0][0]",
            "codec_tag": "0x2000",
            "sample_fmt": "fltp",
            "sample_rate": "48000",
            "channels": 6,
            "channel_layout": "5.1(side)",
            "bits_per_sample": 0,
            "dmix_mode": "-1",

【问题讨论】:

    标签: python json ffmpeg ffprobe


    【解决方案1】:

    你应该可以简单地使用:

    if data["streams"][1]:
        print(..........)
    

    【讨论】:

      【解决方案2】:

      您可以使用len 函数来检查列表中是否存在特定索引。比如:

      if len(data["streams"]) > 1: print data["streams"][1]

      【讨论】:

        【解决方案3】:

        我已经解决了我的问题:)

        for i in range(1, len(data["streams"])):
                if (data["streams"][i]["codec_type"]) == "audio":
                        print
                        print "Audio Channel Number: %d" %(i)
                        print "Codec: %s" %(data["streams"][i]["codec_name"])
                        print "Sample Rate: %.3f KHz" %(int(data["streams"][i]["sample_rate"])/1000)
                        print "Bitrate: %d Kbps" %(int(data["streams"][i]["bit_rate"])/1000)
                        print
                else:
                        print
                        print "No valid audio streams!"
                        print
        

        【讨论】:

          【解决方案4】:

          你可以简单地使用

          if data["streams"][1]:
          

          【讨论】:

            【解决方案5】:

            安全

            for i in range(len(data["streams"])): if "index" in data["streams"][i].keys() and data["streams"][i]["index"]==1: try: print "Codec: %s" %(data["streams"][i]["codec_name"]) print "Sample Rate: %.3f KHz" %(int(data["streams"][i]["sample_rate"])/1000) print "Bitrate: %d Kbps" %(int(data["streams"][i]["bit_rate"])/1000) except: pass break 如果有超过 1 个索引为 1 的文件(似乎不太可能)松开 break 语句

            for i in range(len(data["streams"])):
                if "index" in data["streams"][i].keys() and  data["streams"][i]["index"]==1:
                    try:
                        print "Codec: %s" %(data["streams"][i]["codec_name"])
                        print "Sample Rate: %.3f KHz" %(int(data["streams"][i]["sample_rate"])/1000)
                        print "Bitrate: %d Kbps" %(int(data["streams"][i]["bit_rate"])/1000)
                    except:
                        pass
            

            如果您确定比特率、采样率和编解码器在索引 1 存在时将始终存在,请松开 try catch

            for i in range(len(data["streams"])):
                if "index" in data["streams"][i].keys() and  data["streams"][i]["index"]==1:
                    print "Codec: %s" %(data["streams"][i]["codec_name"])
                    print "Sample Rate: %.3f KHz" %(int(data["streams"][i]["sample_rate"])/1000)
                    print "Bitrate: %d Kbps" %(int(data["streams"][i]["bit_rate"])/1000)
            

            如果你知道如果 data["streams"] 的元素松散了 if 中的第一个条件,则 "index" 将始终存在

            for i in range(len(data["streams"])):
                if  data["streams"][i]["index"]==1:
                    print "Codec: %s" %(data["streams"][i]["codec_name"])
                    print "Sample Rate: %.3f KHz" %(int(data["streams"][i]["sample_rate"])/1000)
                    print "Bitrate: %d Kbps" %(int(data["streams"][i]["bit_rate"])/1000)
            

            如果您现在只有在索引 0 出现时才会出现索引 1,并且将始终出现在 data["streams"] 数组中的位置 1

            try:
                if  data["streams"][1]["index"]==1:
                    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)
            except:
                pass
            

            【讨论】:

              猜你喜欢
              • 2015-05-07
              • 2012-10-05
              • 2022-06-11
              • 1970-01-01
              • 2015-06-30
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多