4 ***********************
5 Quickstart Introduction
6 ***********************
11 This API is generally stable but some areas are still being added and improved.
13 The Blender/Python API can do the following:
15 - Edit any data the user interface can (Scenes, Meshes, Particles etc.)
16 - Modify user preferences, keymaps and themes
17 - Run tools with own settings
18 - Create user interface elements such as menus, headers and panels
20 - Create interactive tools
21 - Create new rendering engines that integrate with Blender
22 - Define new settings in existing Blender data
23 - Draw in the 3D view using OpenGL commands from Python
26 The Blender/Python API **can't** (yet)...
28 - Create new space types.
29 - Assign custom properties to every type.
30 - Define callbacks or listeners to be notified when data is changed.
36 This document isn't intended to fully cover each topic.
37 Rather, its purpose is to familiarize you with Blender Python API.
40 A quick list of helpful things to know before starting:
42 - Blender uses Python 3.x; some online documentation still assumes 2.x.
43 - The interactive console is great for testing one-liners.
44 It also has autocompletion so you can inspect the API quickly.
45 - Button tool tips show Python attributes and operator names.
46 - Right clicking on buttons and menu items directly links to API documentation.
47 - For more examples, the text menu has a templates section where some example operators can be found.
48 - To examine further scripts distributed with Blender, see:
50 | ``~/.blender/scripts/startup/bl_ui`` for the user interface,
51 | ``~/.blender/scripts/startup/bl_op`` for operators.
57 The two most common ways to execute Python scripts are using the built-in
58 text editor or entering commands in the Python console.
60 Both the *Text Editor* and *Python Console* are space types you can select from the view header.
62 Rather than manually configuring your spaces for Python development,
63 you may prefer to use the *Scripting* screen, included default with Blender,
64 accessible from the top headers screen selector.
66 From the text editor you can open ``.py`` files or paste then from the clipboard, then test using *Run Script*.
68 The Python Console is typically used for typing in snippets and for testing to get immediate feedback,
69 but can also have entire scripts pasted into it.
71 Scripts can also run from the command line with Blender but to learn Blender/Python this isn't essential.
83 Python accesses Blender's data in the same way as the animation system and user interface;
84 this implies that any setting that can be changed via a button can also be changed from Python.
86 Accessing data from the currently loaded blend file is done with the module :mod:`bpy.data`.
87 This gives access to library data. For example:
90 <bpy_collection[3], BlendDataObjects>
93 <bpy_collection[1], BlendDataScenes>
95 >>> bpy.data.materials
96 <bpy_collection[1], BlendDataMaterials>
102 You'll notice that an index as well as a string can be used to access members of the collection.
104 Unlike Python's dictionaries, both methods are acceptable;
105 however, the index of a member may change while running Blender.
107 >>> list(bpy.data.objects)
108 [bpy.data.objects["Cube"], bpy.data.objects["Plane"]]
110 >>> bpy.data.objects['Cube']
111 bpy.data.objects["Cube"]
113 >>> bpy.data.objects[0]
114 bpy.data.objects["Cube"]
120 Once you have a data block, such as a material, object, groups etc.,
121 its attributes can be accessed much like you would change a setting using the graphical interface.
122 In fact, the tooltip for each button also displays the Python attribute
123 which can help in finding what settings to change in a script.
125 >>> bpy.data.objects[0].name
128 >>> bpy.data.scenes["Scene"]
129 bpy.data.scenes['Scene']
131 >>> bpy.data.materials.new("MyMaterial")
132 bpy.data.materials['MyMaterial']
135 For testing what data to access it's useful to use the "Console", which is its own space type.
136 This supports auto-complete, giving you a fast way to dig into different data in your file.
138 Example of a data path that can be quickly found via the console:
140 >>> bpy.data.scenes[0].render.resolution_percentage
142 >>> bpy.data.scenes[0].objects["Torus"].data.vertices[0].co.x
146 Data Creation/Removal
147 ^^^^^^^^^^^^^^^^^^^^^
149 Those of you familiar with other Python API's may be surprised that
150 new datablocks in the bpy API can't be created by calling the class:
153 Traceback (most recent call last):
154 File "<blender_console>", line 1, in <module>
155 TypeError: bpy_struct.__new__(type): expected a single argument
158 This is an intentional part of the API design.
159 The Blender/Python API can't create Blender data that exists outside the main Blender database
160 (accessed through :mod:`bpy.data`), because this data is managed by Blender (save/load/undo/append... etc).
162 Data is added and removed via methods on the collections in :mod:`bpy.data`, eg:
164 >>> mesh = bpy.data.meshes.new(name="MyMesh")
166 <bpy_struct, Mesh("MyMesh.001")>
168 >>> bpy.data.meshes.remove(mesh)
174 Python can access properties on any datablock that has an ID
175 (data that can be linked in and accessed from :mod:`bpy.data`.
176 When assigning a property, you can make up your own names,
177 these will be created when needed or overwritten if they exist.
179 This data is saved with the blend file and copied with objects.
183 .. code-block:: python
185 bpy.context.object["MyOwnProperty"] = 42
187 if "SomeProp" in bpy.context.object:
188 print("Property found")
190 # Use the get function like a Python dictionary
191 # which can have a fallback value.
192 value = bpy.data.scenes["Scene"].get("test_prop", "fallback value")
194 # dictionaries can be assigned as long as they only use basic types.
195 group = bpy.data.groups.new("MyTestGroup")
196 group["GameSettings"] = {"foo": 10, "bar": "spam", "baz": {}}
198 del group["GameSettings"]
201 Note that these properties can only be assigned basic Python types.
204 - array of ints/floats
205 - dictionary (only string keys are supported, values must be basic types too)
207 These properties are valid outside of Python. They can be animated by curves or used in driver paths.
213 While it's useful to be able to access data directly by name or as a list,
214 it's more common to operate on the user's selection.
215 The context is always available from ``bpy.context`` and can be used to get the active object, scene,
216 tool settings along with many other attributes.
220 >>> bpy.context.object
221 >>> bpy.context.selected_objects
222 >>> bpy.context.visible_bones
224 Note that the context is read-only.
225 These values cannot be modified directly,
226 though they may be changed by running API functions or by using the data API.
228 So ``bpy.context.object = obj`` will raise an error.
230 But ``bpy.context.scene.objects.active = obj`` will work as expected.
233 The context attributes change depending on where they are accessed.
234 The 3D view has different context members than the console,
235 so take care when accessing context attributes that the user state is known.
237 See :mod:`bpy.context` API reference.
243 Operators are tools generally accessed by the user from buttons, menu items or key shortcuts.
244 From the user perspective they are a tool but Python can run these with its own settings
245 through the :mod:`bpy.ops` module.
249 >>> bpy.ops.mesh.flip_normals()
251 >>> bpy.ops.mesh.hide(unselected=False)
253 >>> bpy.ops.object.scale_apply()
258 The menu item: :menuselection:`Help --> Operator Cheat Sheet`
259 gives a list of all operators and their default values in Python syntax, along with the generated docs.
260 This is a good way to get an overview of all Blender's operators.
266 Many operators have a "poll" function which may check that the cursor
267 is in a valid area or that the object is in the correct mode (Edit Mode, Weight Paint etc).
268 When an operator's poll function fails within Python, an exception is raised.
270 For example, calling ``bpy.ops.view3d.render_border()`` from the console raises the following error:
272 .. code-block:: python
274 RuntimeError: Operator bpy.ops.view3d.render_border.poll() failed, context is incorrect
276 In this case the context must be the 3d view with an active camera.
278 To avoid using try/except clauses wherever operators are called you can call the operators
279 own ``poll()`` function to check if it can run in the current context.
281 .. code-block:: python
283 if bpy.ops.view3d.render_border.poll():
284 bpy.ops.view3d.render_border()
290 Python scripts can integrate with Blender in the following ways:
292 - By defining a rendering engine.
293 - By defining operators.
294 - By defining menus, headers and panels.
295 - By inserting new buttons into existing menus, headers and panels
298 In Python, this is done by defining a class, which is a subclass of an existing type.
304 .. literalinclude:: ../../../release/scripts/templates_py/operator_simple.py
306 Once this script runs, ``SimpleOperator`` is registered with Blender
307 and can be called from the operator search popup or added to the toolbar.
311 #. Highlight the above code then press :kbd:`Ctrl-C` to copy it.
313 #. Press :kbd:`Ctrl-Right` twice to change to the Scripting layout.
314 #. Click the button labeled ``New`` and the confirmation pop up in order to create a new text block.
315 #. Press :kbd:`Ctrl-V` to paste the code into the text panel (the upper left frame).
316 #. Click on the button **Run Script**.
317 #. Move your cursor into the 3D view, press spacebar for the operator search menu, and type "Simple".
318 #. Click on the "Simple Operator" item found in search.
321 .. seealso:: The class members with the ``bl_`` prefix are documented in the API
322 reference :class:`bpy.types.Operator`
326 The output from the ``main`` function is sent to the terminal;
327 in order to see this, be sure to :ref:`use the terminal <use_the_terminal>`.
332 Panels register themselves as a class, like an operator.
333 Notice the extra ``bl_`` variables used to set the context they display in.
335 .. literalinclude:: ../../../release/scripts/templates_py/ui_panel_simple.py
339 #. Highlight the above code then press :kbd:`Ctrl-C` to copy it
341 #. Press :kbd:`Ctrl-Right` twice to change to the Scripting layout
342 #. Click the button labeled ``New`` and the confirmation pop up in order to create a new text block.
343 #. Press :kbd:`Ctrl-V` to paste the code into the text panel (the upper left frame)
344 #. Click on the button **Run Script**.
349 #. Select the the default cube.
350 #. Click on the Object properties icon in the buttons panel (far right; appears as a tiny cube).
351 #. Scroll down to see a panel named **Hello World Panel**.
352 #. Changing the object name also updates **Hello World Panel's** Name: field.
354 Note the row distribution and the label and properties that are available through the code.
356 .. seealso:: :class:`bpy.types.Panel`
362 Blender defines a number of Python types but also uses Python native types.
364 Blender's Python API can be split up into 3 categories.
370 In simple cases returning a number or a string as a custom type would be cumbersome,
371 so these are accessed as normal Python types.
373 - Blender float/int/boolean -> float/int/boolean
374 - Blender enumerator -> string
376 >>> C.object.rotation_mode = 'AXIS_ANGLE'
378 - Blender enumerator (multiple) -> set of strings
380 .. code-block:: python
382 # setting multiple camera overlay guides
383 bpy.context.scene.camera.data.show_guide = {'GOLDEN', 'CENTER'}
385 # passing as an operator argument for report types
386 self.report({'WARNING', 'INFO'}, "Some message!")
392 Used for Blender datablocks and collections: :class:`bpy.types.bpy_struct`
394 For data that contains its own attributes groups/meshes/bones/scenes... etc.
396 There are 2 main types that wrap Blenders data, one for datablocks
397 (known internally as ``bpy_struct``), another for properties.
399 >>> bpy.context.object
400 bpy.data.objects['Cube']
403 bpy.data.scenes['Scene'].objects
405 Note that these types reference Blender's data so modifying them is immediately visible.
411 Used for vectors, quaternion, eulers, matrix and color types, accessible from :mod:`mathutils`
413 Some attributes such as :class:`bpy.types.Object.location`,
414 :class:`bpy.types.PoseBone.rotation_euler` and :class:`bpy.types.Scene.cursor_location`
415 can be accessed as special math types which can be used together and manipulated in various useful ways.
417 Example of a matrix, vector multiplication:
419 .. code-block:: python
421 bpy.context.object.matrix_world * bpy.context.object.data.verts[0].co
425 mathutils types keep a reference to Blender's internal data so changes can
431 .. code-block:: python
433 # modifies the Z axis in place.
434 bpy.context.object.location.z += 2.0
436 # location variable holds a reference to the object too.
437 location = bpy.context.object.location
440 # Copying the value drops the reference so the value can be passed to
441 # functions and modified without unwanted side effects.
442 location = bpy.context.object.location.copy()
448 There are 2 ways to add keyframes through Python.
450 The first is through key properties directly, which is similar to inserting a keyframe from the button as a user.
451 You can also manually create the curves and keyframe data, then set the path to the property.
452 Here are examples of both methods.
454 Both examples insert a keyframe on the active object's Z axis.
458 .. code-block:: python
460 obj = bpy.context.object
461 obj.location[2] = 0.0
462 obj.keyframe_insert(data_path="location", frame=10.0, index=2)
463 obj.location[2] = 1.0
464 obj.keyframe_insert(data_path="location", frame=20.0, index=2)
466 Using Low-Level Functions:
468 .. code-block:: python
470 obj = bpy.context.object
471 obj.animation_data_create()
472 obj.animation_data.action = bpy.data.actions.new(name="MyAction")
473 fcu_z = obj.animation_data.action.fcurves.new(data_path="location", index=2)
474 fcu_z.keyframe_points.add(2)
475 fcu_z.keyframe_points[0].co = 10.0, 0.0
476 fcu_z.keyframe_points[1].co = 20.0, 1.0