使用graphml处理python networkx keyerror

时间:2015-09-15 12:36:47

标签: python networkx keyerror graphml

我的网络代码有问题。我试图列出边缘的属性,但我一直得到KeyError,或者当我尝试捕获错误时,它会跳过整个代码。

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

我想做什么: 我试图逐个列出所有边(规则)及其各自的属性,例如:

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上使用try和except(continue)时,它会突破for循环并继续执行我的代码的剩余部分。

问题:如何处理KeyError或输入" any"或"无"或"未声明"当一个edge属性不可用时,我想让我的代码打印出类似的东西:

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))

2 个答案:

答案 0 :(得分:0)

它只是一个普通的python词典......你可以做一系列的事情,比如

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

这是很多打字,因此您可以在图表初始化后立即完成所有操作:

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

等。然后像往常一样走路。

答案 1 :(得分: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'
 												
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)))