NetworkX,当节点不在图中时,如何成功捕获 network.exception.NetworkXError?

NetworkX, How do I successfully catch network.exception.NetworkXError when node is not in the graph?

当节点不在图中时,我得到异常错误。当我试图抓住并处理它时,我做不到(所以我一定是做错了什么)。如何捕获和处理 networkx.exception.NetworkXError?

这里是错误:

<snip> raise NetworkXError("The node %s is not in the digraph."%(n,)) networkx.exception.NetworkXError: The node 33293542 is not in the digraph.

以下是我尝试捕捉和处理它的方法:

try:
    path_len = nx.shortest_path_length(G,uNode, vNode)
except (nx.NetworkXNoPath, nx.exception.NetworkXError) as e:
    print e
    continue 

我也试过:

try:
        path_len = nx.shortest_path_length(G,uNode, vNode)
except (nx.NetworkXNoPath, KeyError) as e:
        print e
        continue 

我在两个列表中维护 uNodevNode,我可以做一个:if v in target_nodes:,但在我这样做之前,我想知道是否有一种优雅的方式来处理这个NetworkX exception?

如果您所做的只是确保您不会尝试获取不存在节点的路径长度,那么为什么不直接使用 has_node:

if G.has_node(uNode) and G.has_node(vNode):
    path_len = nx.shortest_path_length(G,uNode, vNode)

编辑

以下对我有用:

In [76]:    
import networkx as nx
G=nx.Graph()
G.add_edge(2,3)
try:
    nx.shortest_path_length(G,0,1)
except nx.NetworkXError:
    print("not found")

not found

应该是nx.exception.NetworkXError,所以:

import networkx as nx

try:
    nx.shortest_path_length(G,0,1)
except nx.exception.NetworkXError:
    print("not found")