因此,我有一個相當大的python應用程序使用wxPython,Matplotlib,Numpy,並且最初使用pySerial和minimalmodbus進行設備通信。該應用程序用於從USB分光輻射度計讀取和繪製數據。直到我們決定將通信從modbus轉換到usb以獲得速度之前,所有操作都很順利。我現在使用libusb0.1後端的pyusb。它的工作原理與一個相當惱人的例外大部分:sys.getrefcount(無)滾動到負值
致命的Python錯誤:解除分配無
這取約20000測量後彈出。它並不總是在同一個平臺上,但它很接近。得到錯誤後,我做了一些Google搜索,並決定在發送cmd並從USB設備接收數據之前和之後,在我的代碼中添加sys.getrefcount(None)。我不知道通常預期的數字是多少,但是在發出命令之前增加了大約4717個參考計數,直到數據被拉出。從閱讀結束到下一次發送開始,參考計數增加了20多萬。所以每次測量都將參考計數增加了大約22萬!
這似乎對我來說是一個無足輕重的金額,但我不熟悉這裏預期的數字種類。
問題是,看起來無論變量是否保存'None'的引用計數都是32位有符號整數。經過約9000次測量後,參考計數從2147483647溢出至-2147483648。然後以上述相同的速率穩步增加,直到它達到零,並殺死程序,出現上述的致命Python錯誤:釋放無。
更新:
事實證明,從pySerial切換到pyusb不是問題的根源。我發現這兩個版本的應用程序都有同樣的問題,現在由於我可以使用pyusb對光譜輻射計進行採樣的速度比現在要快10倍。
我已經從我的代碼中刪除了numpy的所有有意使用,雖然我知道matplotib使用numpy很重,並清理了其他一些區域。這降低了程序失敗的速度。現在我可以在事情失敗之前獲得近9萬次測量結果,但仍然失敗。在程序開始時使用gc庫和設置gc.set_debug(gc.DEBUG_LEAK)幫助我找到了很多需要修復的區域。該程序吐出了很多似乎是從matplotlib發出的引用。它經常重複這個序列:
gc: collectable <MarkerStyle 05575AB0>
gc: collectable <dict 066C8030>
gc: collectable <instancemethod 0532EB70>
gc: collectable <Affine2D 066BE690>
gc: collectable <WeakValueDictionary instance at 066AE300>
gc: collectable <weakref 066C51B0>
gc: collectable <function 066C11F0>
gc: collectable <tuple 066BE350>
gc: collectable <dict 066C85D0>
gc: collectable <list 05134760>
gc: collectable <set 05597C60>
gc: collectable <dict 066C8390>
gc: collectable <MarkerStyle 066BE790>
gc: collectable <dict 066C8540>
gc: collectable <instancemethod 0532EB48>
gc: collectable <Affine2D 066BE7B0>
gc: collectable <WeakValueDictionary instance at 066AEEB8>
gc: collectable <weakref 066C5210>
gc: collectable <function 066C1270>
gc: collectable <tuple 066BE5B0>
gc: collectable <dict 066C8AE0>
gc: collectable <list 051346E8>
gc: collectable <set 05597A80>
gc: collectable <dict 066C88A0>
gc: collectable <MarkerStyle 066BE850>
gc: collectable <dict 066C8A50>
gc: collectable <instancemethod 0532E760>
gc: collectable <Path 066BE870>
gc: collectable <IdentityTransform 066BE890>
gc: collectable <WeakValueDictionary instance at 066C9148>
gc: collectable <weakref 066C5270>
gc: collectable <function 066C12F0>
gc: collectable <tuple 066BE050>
gc: collectable <dict 066C8D20>
gc: collectable <list 05134530>
gc: collectable <set 05597990>
gc: collectable <dict 066C8F60>
剛開始應用程序發出967行gc:collectable'something something'。我不完全瞭解gc庫是如何工作的,或者爲什麼這些會顯示出來。我錯過了明顯的東西嗎?我如何讓這些垃圾消失?
聽起來像你正在使用的一些模塊有一個參考泄漏。 「無」的補償不應該這樣做。 – user2357112