Python对接Dump1090的JSON飞机检测循环逻辑优化咨询
原代码核心问题修正说明
现有代码逻辑缺陷
- 无外层持续运行的循环,仅执行一次数据拉取就退出,完全不符合“重启循环重新检测”的需求
- 无飞机判断逻辑错误:
None in aircraft_json['aircraft']不符合Dump1090的返回规则,无飞机时返回的是空列表[],而非列表元素为None - 等待逻辑错位:遍历每架飞机时单独触发sleep,若存在多架飞机会重复等待10分钟,而非处理完所有飞机后统一等待
hex字段的异常捕获逻辑写反:try块内赋值默认值0,except块内才尝试读取真实值,逻辑完全颠倒- 裸异常捕获会吞掉Ctrl+C等正常退出信号,导致程序无法手动终止;网络波动、JSON解析失败时无容错能力,会直接崩溃
- 单次数据拉取写死在循环外,无法获取最新的飞机状态
- 冗余判断无效:
if dat in aircraft_json['aircraft']属于遍历过程中的冗余判断,无实际作用
修正后完整可运行代码
注意请将代码内的DUMP1090_URL替换为你实际的Dump1090服务地址
import urllib.request import json from time import sleep # 基础配置 DUMP1090_URL = "http://localiP/data/aircraft.json" WAIT_NO_PLANE = 5 # 无飞机时等待5秒 WAIT_HAS_PLANE = 10 * 60 # 有飞机时等待10分钟 # 如需使用telepot发送消息,取消下方代码的注释 # import telepot # TOKEN = '1401649465:AAEMyJ87FilPAk-dbQYa7ovx4fxn5uJ1K-w' # bot = telepot.Bot(TOKEN) def fetch_aircraft_data(): """拉取Dump1090飞机数据,拉取失败返回空列表""" try: # 加10秒超时,避免网络异常时程序永久卡顿 with urllib.request.urlopen(DUMP1090_URL, timeout=10) as url: aircraft_json = json.loads(url.read().decode()) return aircraft_json.get('aircraft', []) except Exception as e: print(f"数据拉取失败:{str(e)}") return [] def parse_aircraft_info(aircraft_item): """解析单架飞机字段,缺失值统一返回默认0,兼容原有逻辑""" # 几何高度从英尺转米 try: altitude = aircraft_item["alt_geom"] * 0.3048 except (KeyError, TypeError): altitude = 0 # 航班号,Dump1090返回的航班号带首尾空格,做了自动裁剪 try: flight = aircraft_item["flight"].strip() except (KeyError, AttributeError): flight = 0 # 应答机Squawk代码 try: squawk = aircraft_item["squawk"] except KeyError: squawk = 0 # 马赫数转时速(km/h) try: speed = aircraft_item["mach"] * 1234.8 except (KeyError, TypeError): speed = 0 # 紧急状态 try: emergency = aircraft_item["emergency"] if emergency == "0": emergency = 0 except KeyError: emergency = 0 # 经纬度 try: lat = aircraft_item["lat"] long = aircraft_item["lon"] except KeyError: lat = 0 long = 0 # 飞机ICAO十六进制编码,修正原有逻辑颠倒的问题 try: hex_code = aircraft_item["hex"] except KeyError: hex_code = 0 return { "flight": flight, "altitude": altitude, "speed": speed, "squawk": squawk, "emergency": emergency, "lat": lat, "long": long, "hex": hex_code } if __name__ == "__main__": while True: aircraft_list = fetch_aircraft_data() # 无飞机场景逻辑 if len(aircraft_list) == 0: print("No Plane!") sleep(WAIT_NO_PLANE) continue # 有飞机场景逻辑,先处理所有飞机数据 for dat in aircraft_list: info = parse_aircraft_info(dat) print( f"Vol: {info['flight']} | " f"Alt: {round(info['altitude'], 2)}m | " f"Vitesse: {round(info['speed'], 2)}Km/h" ) # 如需调用telepot发消息,在此处添加消息发送逻辑 # 所有飞机数据处理完成后,统一等待10分钟再进入下一轮检测 sleep(WAIT_HAS_PLANE)
逻辑匹配说明
- 无飞机场景:拉取到空飞机列表时打印提示,等待5秒后自动进入下一轮检测,完全匹配需求
- 有飞机场景:遍历处理完所有检测到的飞机数据后,统一等待10分钟再拉取新数据,核查新增飞机
- 兼容原有输出格式:所有字段解析规则和你原有代码一致,仅修正逻辑错误和异常捕获问题
- 新增容错能力:数据拉取超时控制、异常捕获细化,避免轻微网络波动导致程序崩溃
内容的提问来源于stack exchange,提问作者Dimdimtri
相关产品推荐
相关产品推荐

