2015-07-20 79 views
1

我运行的代码手柄/挂钩RuntimeWarnings

testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl") 

有时抛出的警告

RuntimeWarning: Cannot shuffle graph, maybe there is only a single one? at gengraph_graph_molloy_hash.cpp:332 

我想抓住这个警告,所以我可以停止工作度数序列只有一个图。

我试图

degseq = [1,2,2,3] 
try: 
    testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl") 
except RuntimeWarning: 
    print degseq 
else: 
    print "go on" 

返回警告,然后 “继续”。

我试图警告与

warnings.simplefilter('error', 'Cannot shuffle graph') 
degseq = [1,2,2,3] 
try: 
    testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl") 
except RuntimeWarning: 
    print degseq 
else: 
    print "go on" 

升级到异常等等,而现在很奇怪发生!它返回

testgraph = igraph.Graph.Degree_Sequence(degseq,method = "vl") 
MemoryError: Error at src/attributes.c:284: not enough memory to allocate attribute hashes, Out of memory 

如何使python捕获RuntimeWarning?为什么当我将警告升级为异常时会发生新的异常?

回答

0

你可以试试这个一IGRAPH在通话过程中捕获所有的警告:

from warnings import catch_warnings 
with catch_warnings(record=True) as caught_warnings: 
    testgraph = igraph.Graph.Degree_Sequence(degseq, method="vl") 
    if caught_warnings: 
     # caught_warnings is a list of warnings; do something with them here 

关于你看到的MemoryError:它实际上是在IGRAPH的Python接口的错误。在内部,igraph库的C核心(它不知道嵌入的宿主语言)提示了你的学位顺序。然后这变成了一个Python警告,然后由警告处理程序变成异常。然而,igraph库的C核心并不预期igraph核心警告有时会变成例外,因此它愉快地继续执行代码Graph.Degree_Sequence,注意到那个已经变成例外的警告后来几次内部调用,并错误地将它归因于其他内存分配失败(与您的原始警告无关)。

+0

我已经添加了一个bug报告给python-igraph关于MemoryError的问题跟踪器:https://github.com/igraph/python-igraph/issues/38 –