2015-09-15 22 views
2

我的networkx代码有问题。我试图列出我的边缘的属性,但我不断收到KeyError,或者当我尝试捕获错误时,它会跳过整个代码。使用graphml处理python networkx keyerror

背景: 我有一个图形,其边缘代表防火墙规则,自定义属性为协议,源端口,目标端口,边缘标签包含动作(允许或拒绝),而边缘之间的节点是源和目的地址... 的协议,源和目的端口的默认值是IP,任意,任意...

什么即时试图做的: 我试着列出所有的边缘(规则)和其各自的属性一个接一个例如:

Rule has PROTOCOL: tcp ACTION: allow sPORT: 6667 dPORT: 6667 

问题:我使用的协议,源端口和目的端口,在某些情况下和默认值,因此值做没有任何显示,即使我尝试

for u,v,n in G.edges_iter(data=True): 
    print ('%s %s %s' % (u,v,n)) 

,当我尝试

print ('Rule has PROTOCOL: %s ACTION: %s sPORT: %s dPORT: %s' % (n['protocol'],n['label'], n['s_port'], n['d_port'])) 

我得到一个KeyError因为在某些边缘我没有任何协议或s_port或d_port声明。而当我尝试使用尝试和除了(继续)的KeyError它只是打破了for循环,并继续执行我的代码的其余部分。

问:我怎么处理KeyError异常或输入类似“任何”或“无”或“未声明”当边缘属性是不可用的,我想我的代码打印的东西,如:

Rule has PROTOCOL: tcp ACTION: allow sPORT: any dPORT: any 

时,即时通讯使用默认值,源和目的端口,而不是跳过代码

这是我的代码如下所示:

import os 
import sys 
import string 
import networkx as nx 

G = nx.read_graphml("fwha.graphml") 
count = 0 

edges = G.number_of_edges() 
nodes = G.number_of_nodes() 

print "Number of edges in diagram is: ", edges 

for u,v,n in G.edges_iter(data=True): 
    try: 
    print ('Rule has PROTOCOL: %s ACTION: %s sPORT: %s dPORT: %s' % (n['protocol'], n['label'], n['s_port'], n['d_port'])) 
    except KeyError: 
    continue 

print "Number of nodes in diagram is: ", nodes 
for m,k in G.nodes_iter(data=True): 
    print('%s %s' % (k,m)) 

回答

0

这只是一个常规的Python字典...你可以做的一系列事情像

n.get('protocol', 'any'), 

这是很多打字,所以你可以一次做这一切的图形初始化后:

for v in G.node: 
    G.node[v].setdefault('protocol', 'any') 

等然后像平常一样走路。

+0

感谢科利的工作对你的想法,但调整了一下,并提出了上面的答案完美的作品。 – ahmed

0

嗯,我尝试这样做,即使它不是太整齐,可以使用的功能整理一下,它适用于现在这样:)

for u,v,n in G.edges_iter(data=True): 
 
    try: 
 
    if not n['s_port']: 
 
     print "No Problem here" 
 
    except KeyError: 
 
     n['s_port'] = 'any' 
 

 
for u,v,n in G.edges_iter(data=True): 
 
    try: 
 
    if not n['d_port']: 
 
     print "No Problem here" 
 
    except KeyError: 
 
     n['d_port'] = 'any' 
 
    \t \t \t \t \t \t \t \t \t \t \t \t 
 
for u,v,n in G.edges_iter(data=True): 
 
    try: 
 
    count = count + 1 
 
    print ('Rule %d - Protocol: %s Action: %s SourcePort: %s Destination Port: %s' % (count,n['protocol'], n['label'], n['s_port'], n['d_port'])) 
 
    except KeyError, e: 
 
    count = count+1 
 
    print ('Number %s: It didnt execute and the error is %s' % (count, str(e)))