0
$\begingroup$

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
from threading import Timer

bl_info = {"name": "Auto Reload Addon", "category": "Object"}
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

def autoreload():
    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\\')
                img.reload()

def register():
    print("Auto Reloading Enabled")
    startup()
    rt = RepeatedTimer(1, autoreload) 

def unregister():
    print("Auto Reloading Disabled")

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.

$\endgroup$
1
  • $\begingroup$ 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. $\endgroup$
    – batFINGER
    Commented Dec 21, 2017 at 17:57

1 Answer 1

1
$\begingroup$

You cannot access Blender from a different thread. To create a periodically called function, use a modal operator with a timer.

$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .