在工作中写了一个脚本,用python类实现,想在__del__中记录日志信息:
def __del__(self):
self.log.info("析构进程退出!")
self.cursor.close()
self.conn.close()
调用方法:
if __name__ == '__main__':
begin_time = time.time()
cell = MobileCell()
cell.truncateTables()
print("耗时:{:<5f}秒".format(time.time()-begin_time))
但每次执行的时候都会报错,错误信息如下:
耗时:0.221156秒
--- Logging error ---
Traceback (most recent call last):
File "/app/ofcs/ofcs/tools/python3/lib/python3.7/logging/handlers.py", line 69, in emit
if self.shouldRollover(record):
File "/app/ofcs/ofcs/tools/python3/lib/python3.7/logging/handlers.py", line 183, in shouldRollover
self.stream = self._open()
File "/app/ofcs/ofcs/tools/python3/lib/python3.7/logging/__init__.py", line 1116, in _open
return open(self.baseFilename, self.mode, encoding=self.encoding)
NameError: name 'open' is not defined
Call stack:
File "equip_cell.py", line 16, in __del__
self.log.info("析构进程退出!")
Message: '析构进程退出!'
Arguments: ()
原因是程序退出之后log已经关闭.
百度的方法一点用都没有。后来想了下,为何不主动删除对象呢?
调用方法改成:
if __name__ == '__main__':
begin_time = time.time()
cell = MobileCell()
cell.truncateTables()
print("耗时:{:<5f}秒".format(time.time()-begin_time))
#必须手动添加删除对象,否则self.log.info会报错
del cell
主要增加了del 对象名
而不是在退出程序由GC自动销毁对象
结果发现程序能够调用析构函数 del 了。