Skip to main content
 首页 » 编程设计

python之如何从 DOT 文件中获取端口信息

2025年05月04日9cloudgamer

我有以下拓扑 DOT 文件 (test.dot)。此点文件以交换机端口名称方式维护网络拓扑。

digraph G { 
   "R1":"swp1" -> "R3":"swp3"; // Port swp1 of switch R1 is connected to port swp3 of R3 
   "R1":"swp2" -> "R4":"swp3"; 
   "R1":"swp3" -> "R5":"swp3"; 
   "R1":"swp4" -> "R6":"swp3"; 
 } 

我在 python 中使用 pygraphviz 库来读取图表。

源代码:

#!/usr/bin/env python 
from pygraphviz import * 
 
G = AGraph("test.dot") 
 
for edge in G.edges(): 
    print edge 

输出:

(u'R1', u'R6') 
(u'R1', u'R4') 
(u'R1', u'R3') 
(u'R1', u'R5') 

我面临的问题是 API 没有提供端口信息。
如何从 API 获取端口信息?

请您参考如下方法:

这不是一个非常漂亮的界面。但是你可以通过这种方式获取数据:

In [2]: G.get_edge('R1','R3').attr['headport'] 
Out[2]: u'swp3' 
 
In [3]: for e in G.edges(): 
    print e,e.attr 
   ...:      
(u'R1', u'R3') {u'tailport': u'swp1', u'headport': u'swp3'} 
(u'R1', u'R4') {u'tailport': u'swp2', u'headport': u'swp3'} 
(u'R1', u'R5') {u'tailport': u'swp3', u'headport': u'swp3'} 
(u'R1', u'R6') {u'tailport': u'swp4', u'headport': u'swp3'}