Trying to create a simple add-on but Python keeps throwing errors

I am trying to create a simple add-on that will automatically reload images in Blender. I managed to find a few scripts that helped me and when I press "Run Script" it works as expected. However, when I try to add it to the Add-On in Blender, I get this error:

AttributeError: '_RestrictData' object has no attribute 'images'

The line causing the problem is:

images = bpy.data.images


Here is the full script:

import bpy
import os

last_mod = {}

def startup():
images = bpy.data.images
for img in images :
if img.source == 'FILE' :
path = img.filepath_from_user()
statbuf = os.stat(path)
last_mod[img.filepath_raw] = statbuf.st_mtime

images = bpy.data.images
for img in images :
if img.source == 'FILE' :
path = img.filepath_from_user()
statbuf = os.stat(path)
if statbuf.st_mtime > last_mod[img.filepath_raw]:
last_mod[img.filepath_raw] = statbuf.st_mtime
img.filepath = img.filepath.replace('\\old_folder\\','\\new_folder\\')

def register():
startup()

def unregister():

if __name__ == "__main__":
register()


The RepeatedTimer is a class I found online that run a function every X seconds

I searched online and The kinds of solutions I saw is to use bpy.data after the register(), and it didn't let me call it like this:

if __name__ == "__main__":
register() # This is called
startup() # This wont even be called when the Add-on is enabled!


I understand that this has something to do with the import but I can't figure out what is wrong. I tried a few things that didn't even run.

Am I doing something really wrong here? again, the "Run Script" button works as expected, but I want to be able to disable and enable the script.

• Blender and threading don't play too well together. The _RestrictData comes about as you're not allowed to access bpy.context or bpy.data at registration time, neither in the register() function, nor in any function that is called in inside the register() function. – batFINGER Dec 21 '17 at 17:57