对象不执行__del__

时间:2014-03-21 07:29:47

标签: python arrays

我正在尝试在打开新端口时从数组创建一个对象,当它是壁橱时将其删除。

#!/usr/bin/python
import thread
import psutil
import time
thelist = []

class connection:
     def __init__(self, name):
         self.name = name
         print "open van stream"  + str(self.name)

     def __del__(self):
         print "close van stream "

def contains(list, filter):
     for x in list:
         if filter(x):
             return True
     return False

if __name__ == '__main__':
     try:
         PROCNAME = "tvheadend"
         for proc in psutil.process_iter():
             if proc.name == PROCNAME:
                 process = proc
         if not process:
             print "not found tvheadend"
             exit()
         print "Found " + str(process)

         while(1):
             for list in process.get_connections(kind='udp'):

                 if not contains(thelist, lambda x: x.name == list.local_address[0]):
                    thelist.append(connection(list.local_address[0]))

             for list in thelist:
                 print thelist
                 if not contains(process.get_connections(kind='udp'), lambda x: x.local_address[0] == list.name):
                     thelist.remove(list)
                     print "removed"
             time.sleep(0.5)

     except SystemExit, KeyboardInterrupt:
         exit()

但是当我打开一个新的时,它只打印“close van stream”。不是当我关闭一个。使用“打印列表”功能,我可以看到该对象已从数组中删除,但它不会打印“close van stream”

1 个答案:

答案 0 :(得分:0)

只要您仍然从list引用它,它就不会消失。

只要您重新分配list,它就会消失。

只有这样,此对象的引用计数器才会降为0并且将调用__del__

顺便说一下,调用变量list是个坏主意,因为这会影响内置类型list

而且,BTW,__del__ should not be relied on。相反,您应该考虑定义和使用上下文管理器。

编辑:这里显然不可能使用上下文管理器,但您应明确.close(),而不是依赖于__del__()被调用。