Reset python console

Well, I had a look at the console_python module. It seems like blender simply uses the class InteractiveConsole of the standard library, and stores instances for every python console of the gui in a dictionary console_python.get_console.consoles. The key is hash(region).

Would it be safe, to simply remove the key and its value from the dictionary, like

del console_python.get_console.consoles[hash(region)]

to reset the console?


import bpy
import sys
import console_python

for area in bpy.context.screen.areas:
    if area.type == 'CONSOLE':
        break
    
for region in area.regions:
    if region.type == 'WINDOW':
        break

#if a console has been used - otherwise the dictionary consoles might not exist     
print(sys.getrefcount(
    console_python.get_console.consoles.pop(hash(region))
    ))
#>>> 1

context = bpy.context.copy()
context['region'] = region
context['area'] = area
bpy.ops.console.clear(context)

Interesting, it seems to work except for the history. You could try to paste a lot of code to the console, reset and compare memory utilization - if it doesn’t decrease after reset, then I’d say it’s “not safe”.


    #~30 mb
    b = b'\x00' * 30 * 2**20

Seems the memory is being released when the console is removed. Expanded this: Full script.