error using xmlrpc thread for client/server connection

Hi, I am trying to control Blender from an external python script using xmlrpc in a simple script:


import bpy
from xmlrpc.server import SimpleXMLRPCServer as Server
from threading import Thread
    
def get_data(n):
    print("Size: %s" % n)
    print(bpy.context.active_object.active_material)

class TestServer(): 
    def __init__(self):        
        at = Thread(target=self.serve, args=()).start() 
    def serve(self):
        print("Serving")
        srv = Server(("localhost", 5017), allow_none=True) 
        srv.register_function(get_data)    
        srv.serve_forever()      
        
S = TestServer()

It can receive and print the incoming data corrently, but it cannot print the active object’s material (2nd line of the get_data function). The client brings up this error message:

<class ‘AttributeError’>:‘Context’ object has no attribute ‘active_object’">

Is it a problem with the thread I started for the xmlrpc server?
How can I solve it?

Thanks!

It is possible that your context is incorrect. I suspect that the context only has an ‘active_object’ when your mouse cursor is inside a 3D viewport window. If you are over a text window or logic editor, the context probably does not have one.

You might want to test it out by getting your mouse in the 3D viewport then sending the command.

It’s unsafe practice to access blender methods from a thread. You will run in unexpected behaviour. It’s wiser to have a thread post messages to the main (blender) thread which executes the things in blender. I usually use a Python Queue object for this pupose as it is thread safe.

I solved my original problem by using “bpy.context.scene.objects.active” instead of “bpy.context.active_object”.

Ok, understood. But how can I make the Blender main thread run in a Queue object and have it receive messages from another thread…? Could you post a simple example?