如何在创建后杀死一堂课的实例,以释放Python中的记忆



i具有一个python代码,该代码包括顺序初始化2类。我初始化A类(对齐(,做点什么,然后初始化B类,但是A类仍在存储器上,因此没有足够的空间来Init类B。这些类是用Python和TensorFlow编写的。这两个类都在GPU(单个GPU(上运行。现在,在运行B类之前,我该如何杀死A类?

另外,我尝试了Python Destructor,figreRef和gc.Collect((。

import os 
import sys
from subprocess import call
import weakref 
import gc
import time
sys.path.insert(0, 'alignment')
import alignment 

## initializing class A
align = alignment.Verification('./alignment/')
for subdir, dirs, files in os.walk(input_path):
    ## do something here
## end of the class A 
print('End of pre-processing ...')
## Here, the class A should be killed!
del align
gc.collect()
## start training (using tensorflow)
command = 'CUDA_VISIBLE_DEVICES="0" python3 train.py'
call([command], shell=True)

尝试通过释放alignment类所持的所有资源来覆盖破坏者。

几天后,我发现没有杀死python解释器中的python解释器,就无法释放内存。但是,这是一种棘手的方式!您可以使用子过程并将类附加到其中,然后杀死子过程以关闭TensorFlow会话。例如:

first = subprocess.Popen(["python", "class_A.py"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) first.communicate() # wait until session end first.kill()