# frame_change_post/pre not working when Rendering Animation [duplicate]

I've got this script file that works flawlessly in the viewport, but stops completely when I start rendering it as an Animation.

import bpy
import math

def my_handler(scene):
print('testing') # this will be printed out 3 times each frame when rendering the animation, but once only in the viewport.
#assigning variables to objects
a=bpy.data.objects['EmptyTop']
b=bpy.data.objects['EmptyRight']
text=bpy.data.objects['TextRightSide']

# formula for calculating distance
distance=str(int(math.hypot(a.location.x - b.location.x, a.location.y - b.location.y)*10))
text.data.body=distance

bpy.app.handlers.frame_change_post.append(my_handler)


(my_handler) is refreshed every frame as I've tested it by printing a test text in it. However, the main problem is that it does not do anything with the next code (bpy.data.objects). I've tried to change (bpy.data) to (scene) as shown

import bpy
import math

def my_handler(scene):
print('testing')
#assigning variables to objects
a=scene.objects['EmptyTop']
b=scene.objects['EmptyRight']
text=scene.objects['TextRightSide']

# formula for calculating distance
distance=str(int(math.hypot(a.location.x - b.location.x, a.location.y - b.location.y)*10))
text.data.body=distance

bpy.app.handlers.frame_change_post.append(my_handler)


Worked just fine in the viewport but gave me this message when rendering the it as An animation

(line 7, in my_handler