How to toggle to camera view via python?

Is there a way to programmatically achieve the same thing as pressing the 0 key the numpad?

• are you looking for the operator ? – Chebhou May 9 '15 at 12:07
• if it is a bpy.ops thing that's fine, but I already "own" the camera and if I could assign it to a "view-slot" or something that would be awesome.. – Peter Varo May 9 '15 at 12:10
• do you want to set which camera is used for this view ?, the 3d view can have it's own active camera without affecting thescene camera – Chebhou May 9 '15 at 12:12
• What do you mean by "view slot"? Do you want to bind the camera to another key? – p2or May 9 '15 at 12:27
• @poor nvm the phrase "view slot", I'm looking for a way to achieve what the first answer is about, but without swicthing the area-type – Peter Varo May 9 '15 at 12:31

The operator for switching the 3D view which is associated with numpad keys is view3d.viewnumpad(). You have to be in the right context (3d_view) to use it and select which view you want to set:

import bpy

for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
override = bpy.context.copy()
override['area'] = area
break


Another way, without the operator would be:

import bpy

for area in bpy.context.screen.areas:
if area.type == 'VIEW_3D':
area.spaces[0].region_3d.view_perspective = 'CAMERA'
break


Which is equivalent to:

import bpy

area = next(area for area in bpy.context.screen.areas if area.type == 'VIEW_3D')
area.spaces[0].region_3d.view_perspective = 'CAMERA'


Other options are [‘PERSP’, ‘ORTHO’, ‘CAMERA’]

• that is working if the area type is 'VIEW_3D', but is there another way, to achieve this thing without temporarily switch the area? – Peter Varo May 9 '15 at 12:29
• the context should be VIEW_3D , but you can do it without switching, I will edit – Chebhou May 9 '15 at 12:30
• just to be sure: there is no other way, then using the bpy.ops, right? (btw switching back and forth is way shorter than the solution you have provided after the edit -- but I have no idea, what is the advantage of you way vs. the "switching" way) – Peter Varo May 9 '15 at 12:51