python memory leak

If your program is an infinite loop, do not stop codes, the following is the need to pay attention to the problem of memory.
Risks first, pillow library

# Memory will leak 
from PIL Import Image 

IM = Image.open ( '1.jpg') 
im.save () 

# to use with the program more secure 
from PIL Import Image 

with Open ( '1.jpg', 'rb') OPEN_FILE AS: 
    IM = Image.open (OPEN_FILE)

Second, the use of importlib.reload bring heavy load module using global variables bring risks
if taken without restarting the program mode, automatically reload the modified files, so the need for heavy-duty modules

run.py # 
Import the importlib 

the while True: 
    module_name = importlib.import_module ( '.', 'test_file and') 
    module_name = importlib.reload (module_name) 
    Result = module_name.main (the params) 

# test_file.py 
global_value = { 'dataList': [], 
                'Number': '',} 
Key = 'initial value' 

DEF main (the params): 

    # the params carrying the mission data 

    global_value [ 'Number'] = the params [ 'Number'] 
    get_data1 (the params) 
    get_data2 ( the params) 
    return global_value 

DEF get_data1 (the params): 
    Global key 
    # your program the new data obtained by the params 
    data_once = { 'key generated for each run': 'key generated for each run'}} 
    Key = 'new value'
    global_value['dataList'].append(data_once)

get_data2 DEF (params): 
    # your program and the new value via the params key, to obtain another data 
    data_once = { 'new key is generated for each run of': 'each time a new key generated by the operation'} 
    global_value [ ' dataList ']. append (data_once)

A risk for the above occurs, I used to think garbage collection mechanism is very reliable. But when every time overload module, global_value will use the new address, the same address also once stood on the data, not freed
even if you add in each cycle in gc.collect () can not quickly recover deleted on once the data, resulting in memory growth. . .


My approach is
(1) will be transferred into the inner global_value this function, the Senate will pass through get_data2 get_data1 and data integration in a variable
(2) all functions in a class, variable data can be avoided global survival time too long


Summary, although the use of global variables is very easy, do not pass argument, other functions change its value again is very easy to call other functions, but it will lead to memory leaks, because every time generated when the reload is a new memory address.

Guess you like

Origin www.cnblogs.com/7134g/p/11516818.html