Problem rendering at the end of rigid body animation with script
I assume you are using Blender 2.79, it may not work.
But in Blender 2.80, this is how I would do:

if __name__ == "__main__":
    bpy.ops.screen.animation_play()
    write_image()


Does the issue persist with Blender 2.80?