Scripting error using view3d Here is what I am trying to do:

import bpy
bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.editmode_toggle()
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
bpy.ops.view3d.snap_cursor_to_center()
bpy.ops.view3d.snap_selected_to_cursor(use_offset=False)
bpy.ops.object.editmode_toggle()


But this gave error on line 1 that something is wrong with using view3d.
After reading some previous solutions I modified this code to make it work like this

import bpy
for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
    ctx = bpy.context.copy()
    ctx['area'] = area
    ctx['region'] = area.regions[-1]
    bpy.ops.view3d.snap_cursor_to_selected(ctx)
bpy.ops.object.editmode_toggle()
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
bpy.ops.view3d.snap_cursor_to_center(ctx)
bpy.ops.view3d.snap_selected_to_cursor(use_offset=False)==&gt;ERROR LINE
bpy.ops.object.editmode_toggle()


Now I don't know what to do with that error line. Blender closes and I cannot read any error report. I am not a programmer. Hope anyone helps. Thank you.
Some commands require a specific context. For instance, to use the view3d commands you must switch to the VIEW_3D context first. This should do it:


import bpy
#switch context
previous_context = bpy.context.area.type
bpy.context.area.type = 'VIEW_3D'

#do stuff
bpy.ops.view3d.snap_cursor_to_selected()
bpy.ops.object.editmode_toggle()
bpy.ops.object.origin_set(type='ORIGIN_CURSOR')
bpy.ops.view3d.snap_cursor_to_center()
bpy.ops.view3d.snap_selected_to_cursor(use_offset=False)
bpy.ops.object.editmode_toggle()

#restore previous context
bpy.context.area.type = previous_context