Search code examples
pythonscriptingblenderbpy

How to use the rotate operator on Blender Python if you execute the script on the background?


I am importing a model that consists of multiple individual meshes. Right after import (where everything is selected), I want to rotate the imported selected objects based on a [X, Y, Z] angle parameter. Also I want to run the script as a blender "--background" shell process.

I tried doing something like this but it doesn't seem to work.

bpy.ops.transform.rotate(value=math.radians(param.x), orient_axis='X'); bpy.ops.transform.rotate(value=math.radians(param.y), orient_axis='Y'); bpy.ops.transform.rotate(value=math.radians(param.z), orient_axis='Z');

I get this error:

RuntimeError: Operator bpy.ops.transform.rotate.poll() failed, context is incorrect

I tried searching the internet for solutions but I couldn't understand exactly what is going wrong. Also I think this error doesn't appear because I am running with "--background", but because I am running it as a terminal command.

Thanks in advance! I am using Blender 2.9.


Solution

  • Im running the same issue. I have some scripts that worked so fine in blender 2.83 as module using bpy.ops.transformm.rotate, now this is not working on the new bpy (blender as module) version 2.93.

    I realized that bpy.ops.transform.rotate.poll() return false using the module, from python script, while the function bpy.ops.transform.translate.poll() returns true.

    However when I run the same function in the scripting console of the blender 2.93 GUI, the function bpy.ops.transform.rotate.poll() returns true.

    So I think is a bug in the new version.

    However I was able to fix this passing a VIEW_3D context as first argument in the operator:

    >>> ov=bpy.context.copy()
    >>> ov['area']=[a for a in bpy.context.screen.areas if a.type=="VIEW_3D"][0]
    >>> bpy.ops.transform.rotate(ov)
    {'FINISHED'}
    

    In your case:

    # ... already selected objects, ov is for override, I'm lazy.
    >>> ov=bpy.context.copy()
    >>> ov['area']=[a for a in bpy.context.screen.areas if a.type=="VIEW_3D"][0]
    >>> bpy.ops.transform.rotate(ov, value=math.radians(param.x), orient_axis='X')
    {'FINISHED'}