Making a render sequence script stoppable

Hi! I made this script to render a group of objects in sequence and automatically(I have undreds of them), and to make the output file name with the object name. The script looks for all the object in the to_render group, unhide each one and renders it, and the hide it back. Then proceed with the next object. It work well, but when I run the script I can’t stop it until all the objects are rendered. This is not really good for me, so I’m asking for a way to make it stoppable, for example, pressing Esc.

This is the code. Can somebody suggest me a line to add to make it stoppable? Thanks!

import bpy

output_folder = bpy.data.scenes['Scene'].render.filepath  #tiene in memoria il percorso neutro

for obj in bpy.data.groups["to_render"].objects:
    obj.hide = False
    obj.hide_render = False
    output = bpy.data.scenes['Scene'].render.filepath + obj.name
    bpy.data.scenes['Scene'].render.filepath = output
    bpy.ops.render.render(animation = False, write_still = True, use_viewport = False, layer = "RenderLayer", scene="Scene")
    bpy.app.handlers.render_complete
    bpy.data.groups["to_render"].objects.unlink(obj)
    bpy.data.groups["rendered"].objects.link(obj)
    obj.hide = True
    obj.hide_render = True
    bpy.data.scenes['Scene'].render.filepath = output_folder  #ripristina il percorso neutro

related:
Q: Abort script that renders frames
Q: Python command within script to abort without killing Blender
A: Is there a way to stop Blender from performing an action once started?

Hi! Thankyou for the links. I read them deeply. But I can’t figure out how to implement those things in my script.

My actual condition is that, when I run the script, Blender freeze, so I can’t do anything, and most important problem is that I can’t stop the renders that are processing. I want to obtain that pressing Esc, it stops, or at that moment, or at the end of the current render.

Let’s suppose I put my code in a function that is called for every object to render, how could I stop this function to be called again?

Thanks.