Python循环创建关联多维数组:WireGuard配置解析问题
解析WireGuard配置:将多Peer条目转为数组的解决方法
刚学Python处理wg.conf解析时,很容易踩“覆盖Peer条目”的坑——把多个Peer最后变成单个字典,而不是数组。下面直接针对你的问题给出修正方案:
配置文件示例(wg.conf)
[Interface] PrivateKey = abc123 Address = 10.0.0.1/24 ListenPort = 51820 [Peer] PublicKey = def456 AllowedIPs = 10.0.0.2/32 [Peer] PublicKey = ghi789 AllowedIPs = 10.0.0.3/32 Endpoint = example.com:51820
期望的结构化结果
{ "Interface": { "PrivateKey": "abc123", "Address": "10.0.0.1/24", "ListenPort": "51820" }, "Peers": [ { "PublicKey": "def456", "AllowedIPs": "10.0.0.2/32" }, { "PublicKey": "ghi789", "AllowedIPs": "10.0.0.3/32", "Endpoint": "example.com:51820" } ] }
当前问题代码
config = {} peer = {} with open('wg.conf', 'r') as f: for line in f: line = line.strip() if not line or line.startswith('#'): continue if line.startswith('[Interface]'): config['Interface'] = {} current_section = config['Interface'] elif line.startswith('[Peer]'): # 核心问题:每次遇到新Peer直接覆盖,没有追加到数组 config['Peers'] = peer current_section = peer else: key, value = line.split('=', 1) key = key.strip() value = value.strip() current_section[key] = value
实际错误输出
最后一个Peer会覆盖之前的,且Peers是单个字典而非数组:
{ "Interface": { "PrivateKey": "abc123", "Address": "10.0.0.1/24", "ListenPort": "51820" }, "Peers": { "PublicKey": "ghi789", "AllowedIPs": "10.0.0.3/32", "Endpoint": "example.com:51820" } }
修正后的代码
# 提前初始化好结构:Interface为空字典,Peers为空数组 config = { "Interface": {}, "Peers": [] } current_peer = None with open('wg.conf', 'r') as f: for line in f: line = line.strip() if not line or line.startswith('#'): continue if line.startswith('[Interface]'): current_section = config['Interface'] elif line.startswith('[Peer]'): # 遇到新Peer时,创建新字典并追加到Peers数组 current_peer = {} config['Peers'].append(current_peer) current_section = current_peer else: key, value = line.split('=', 1) key = key.strip() value = value.strip() current_section[key] = value
关键修改说明
- 初始化结构:一开始就把
Peers设为空数组,避免后续覆盖 - 处理Peer段:每次碰到
[Peer],就新建一个空字典,用append()加入Peers数组,再把当前操作的段指向这个新字典 - 避免覆盖:不再用单个
peer变量反复赋值,而是每个Peer对应独立的字典,全部存在数组里
运行修正后的代码,就能得到你想要的多Peer数组结构。
内容的提问来源于stack exchange,提问作者Михаил Макрашин
相关产品推荐
相关产品推荐

