Page MenuHome

snap_cursor_to_selected Fails in Python
Closed, ArchivedPublic

Description

System Information
Operating system: Windows-10-10.0.19041-SP0 64 Bits
Graphics card: GeForce RTX 2070/PCIe/SSE2 NVIDIA Corporation 4.5.0 NVIDIA 461.92

Blender Version
Broken: version: 2.93.1, branch: master, commit date: 2021-06-22 05:57, hash: rB1b8d33b18c2f
Worked: it Failed in 2.83 too

Short description of error
The snap_cursor_to_selected works with the shortcut but Fails in Python with an Error Message:

RuntimeError: Operator bpy.ops.view3d.snap_cursor_to_selected.poll() failed, context is incorrect
Error: Python script failed, check the message in the system console

Exact steps for others to reproduce the error

  • open the Blend File
  • Select the cube
  • Run the Script
import bpy

bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.view3d.snap_cursor_to_selected()

Event Timeline

Leul Mulugeta (Leul) updated the task description. (Show Details)

Unfortunately the context is incorrect message means that you are writing and using this piece of code incorrectly. Most likely you are running the line from a wrong place, or trying to use it with a wrong object. This is a pretty common scripting mistake. Basically this is not a bug rather it is a feature of the Python API.

Turn your script into a real add-on or look into context overriding.

But the problem is if you just use the shortcuts:

  • Select a Cube
  • Tab to go to Edit
  • A to select all
  • Shift S to snap_cursor_to_selected

everything works as Expected and in the codes shown in the info Viewer will be

bpy.ops.object.editmode_toggle()
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.view3d.snap_cursor_to_selected()

i just cant use them in Python, hopefully am not missing anything :/

bpy.ops.view3d.snap_cursor_to_selected needs to be called in the correct context.
It is possible to have more than one view3d open and the code cannot predict which one to use.
Try overriding the context --> https://docs.blender.org/api/current/bpy.ops.html#overriding-context

In fact this does not seem to be a bug.
For help using Blender, please try one of the community websites: https://www.blender.org/community/

The thing is: you are running the code in the context of the text editor.

Please check
https://docs.blender.org/api/2.93/bpy.ops.html#execution-context
https://docs.blender.org/api/2.93/bpy.ops.html#overriding-context

So you should be able to override context with something like this:

import bpy

for window in bpy.context.window_manager.windows:
    screen = window.screen

    for area in screen.areas:
        if area.type == 'VIEW_3D':
            override = {'window': window, 'screen': screen, 'area': area}
            bpy.ops.object.editmode_toggle()
            bpy.ops.mesh.select_all(action='SELECT')
            bpy.ops.view3d.snap_cursor_to_selected(override)
            break

This seems to work