2015-07-20 46 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 –