Snap_Cursor_To_Selected error

Hello, I’m trying to do a simple script, something like this.

import bpy

bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.editmode_toggle()
bpy.ops.object.origin_set(type=‘ORIGIN_CURSOR’)

I’m writing this in the text editor in Blender, but when I Run Script it gives me “Python script fail, look in the console for now …”

And nothing more.


When I write the Console

import bpy
bpy.ops.view3d.snap_cursor_to_selected()

I get this:


bpy.ops.view3d.snap_cursor_to_selected()
Traceback (most recent call last):
File “<blender_console>”, line 1, in <module>
File “C:\Program Files\Blender Foundation\Blender\2.71\scripts\modules\bpy\ops.py”, line 188, in call
ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.view3d.snap_cursor_to_selected.poll() failed, context is incorrect

What am I doing wrong, because I’ve seen some videos that they only write what I’ve written in the text editor and works ?

Thanks

If you run it from text editor, the context is “text editor”, but the operator requires a 3d view context.

You don’t really need these operators, you can do it even without mode switching:

import bpy
import bmesh
from mathutils import Vector, Matrix

ob = bpy.context.object
#ob.update_from_editmode()

mat = ob.matrix_world
me = ob.data

bm = bmesh.from_edit_mesh(me)
v = [v.co for v in bm.verts if v.select]
#v = [v.co for v in me.vertices if v.select]
loc = mat * (sum(v, Vector()) / len(v))

#print(loc)
#bpy.context.scene.cursor_location = loc

mat.translation = loc
#me.transform(Matrix.Translation(-loc))
bm.transform(Matrix.Translation(-loc))
bmesh.update_edit_mesh(me, False, False)

Thanks for the code, but I just wanted to do a simple operation, something like:

  1. When I’m in Edit Mode - I select a vertice
  2. Run the Script that puts 3D Cursor To the Selected Vertice
  3. Tabs out of Edit Mode
  4. Sets the origin to the 3D Cursor

This is what I wanted :), but ty for the script maybe I’ll need it sometime. :slight_smile:

  1. If you run this command from the Blender text editor:

import bpy

bpy.ops.view3d.snap_cursor_to_selected()

You get an error message:
RuntimeError: Operator bpy.ops.view3d.snap_cursor_to_selected.poll() failed, con
text is incorrect

  1. If you run this command from the Blender text editor:

import bpy

bpy.context.area.type = ‘VIEW_3D’
bpy.ops.view3d.snap_cursor_to_selected()

The cursor is successfully snapped to selected, but your text editor has changed to a 3D view window.

  1. If you run this command from the Blender text editor:

import bpy

bpy.context.area.type = ‘VIEW_3D’
bpy.ops.view3d.snap_cursor_to_selected()
bpy.context.area.type = ‘TEXT_EDITOR’

The cursor is successfully snapped to selected, and your text editor window remains a text editor window.