Python脚本仅触发首个IF条件不执行后续elif分支问题求助
问题排查与修复方案
核心问题原因
if...elif...属于串联分支结构,只要有任意一个前置判断条件成立,后续所有elif分支都会直接跳过,不会执行。你的ports字典中存在tcp键,第一个if ports.get("tcp")判断为真后,后续的rant、cm等端口类型的判断逻辑永远不会触发,这就是只能处理第一个键的根本原因。- 额外注意:你初始将
tcpport、udpport定义为列表类型,后续分支中又直接赋值为布尔值True,类型不一致容易引发后续逻辑报错,建议初始化时就统一为布尔类型:tcpport = False、udpport = False。
修复方案
将所有elif替换为独立的if,让每个端口类型的判断完全独立,互不干扰:
import itertools as it # 请确保你用到的自定义函数compile_port2、compile_rant_port2已提前定义 def compile_port2(port_list): # 你的原有实现 pass def compile_rant_port2(ran_list): # 你的原有实现 pass ports = {'tcp': [['10', '20']], 'rant': [['100', '200']], 'cm': ['https']} if __name__ == "__main__": obj = [] tcpport = False udpport = False mxport = [] if ports.get("tcp"): tcp2 = ports.get("tcp") tcpport = True for t in compile_port2(tcp2): obj.append(t) print("compiled tcp only objects") if ports.get("udp"): udpport = True udp2 = ports.get("udp") for u in compile_port2(udp2): obj.append(u) print("compiled udp only objects") if ports.get("rant"): rant2 = ports.get("rant") tcpport = True ran_tcp2 = (list(it.zip_longest(*[iter(rant2[0])] * 2))) for rt in compile_rant_port2(ran_tcp2): obj.append(rt) print("compiled tcp only range objects") if ports.get("ranu"): ranu2 = ports.get("ranu") udpport = True ran_udp2 = (list(it.zip_longest(*[iter(ranu2[0])] * 2))) # split strings by groups of 2 for port ranges for ru in compile_rant_port2(ran_udp2): obj.append(ru) print("compiled udp only range objects") if ports.get("cm"): tcpport = True cm2 = ports.get("cm") for c in compile_port2(cm2): obj.append(c) print("compiled worded objects\n\n") if not obj: print("no items found")
内容的提问来源于stack exchange,提问作者dispell
相关产品推荐
相关产品推荐

