# How to run a modal operator after file open?

I have the following register function:

def register():
bpy.utils.register_class(ModalOperator)
bpy.ops.object.modal_operator('INVOKE_DEFAULT')


It'll work if I run the code from Blender's Text Editor, but will give the following error if I try to use it as add-on:

AttributeError: '_RestrictContext' object has no attribute 'scene'


Is there a way of running my modal operator on Blender's start (or on opening new file)?

• You don't need to put bpy.ops.object.modal_operator('INVOKE_DEFAULT') in register function. – Alex Apr 22 '19 at 3:27
• But how should I start my modal operator then? – Den Den Apr 22 '19 at 21:05

You can use a handler to start your operator after a blend file is loaded, ensure the handler function is marked as persistent to keep it active between file loads.

This is of limited use on blender start, it will work if the addon is enabled and the splash screen is not shown on startup. If the splash screen is shown the operator does work but the display is not updated while the splash screen is visible, dismissing the splash screen also stops the operator.

from bpy.app.handlers import persistent

@persistent