* Button tool tips show Python attributes and operator names.
* Right clicking on buttons and menu items directly links to API documentation.
* For more examples, the text menu has a templates section where some example operators can be found.
* To examine further scripts distributed with Blender, see ``~/.blender/scripts/startup/bl_ui`` for the user interface and ``~/.blender/scripts/startup/bl_op`` for operators.
The two most common ways to execute python scripts are using the built-in text editor or entering commands in the python console.
Both the **Text Editor** and **Python Console** are space types you can select from the view header.
Rather then manually configuring your spaces for Python development, you may prefer to use the **Scripting** screen, included default with Blender, accessible from the top headers screen selector.
From the text editor you can open ``.py`` files or paste then from the clipboard, then test using **Run Script**.
The Python Console is typically used for typing in snippets and for testing to get immediate feedback, but can also have entire scripts pasted into it.
Scripts can also run from the command line with Blender but to learn Blender/Python this isn't essential.
Python accesses Blender's data in the same way as the animation system and user interface; this implies that any setting that can be changed via a button can also be changed from Python.
Once you have a data block, such as a material, object, groups etc., its attributes can be accessed much like you would change a setting using the graphical interface. In fact, the tooltip for each button also displays the Python attribute which can help in finding what settings to change in a script.
For testing what data to access it's useful to use the "Console", which is its own space type. This supports auto-complete, giving you a fast way to dig into different data in your file.
Those of you familiar with other python api's may be surprised that new datablocks in the bpy api can't be created by calling the class:
>>> bpy.types.Mesh()
Traceback (most recent call last):
File "<blender_console>", line 1, in <module>
TypeError: bpy_struct.__new__(type): expected a single argument
This is an intentional part of the API design.
The blender/python api can't create blender data that exists outside the main blender database (accessed through bpy.data), because this data is managed by blender (save/load/undo/append... etc).
Data is added and removed via methods on the collections in bpy.data, eg:
Python can access properties on any datablock that has an ID (data that can be linked in and accessed from :mod:`bpy.data`. When assigning a property, you can make up your own names, these will be created when needed or overwritten if they exist.
This data is saved with the blend file and copied with objects.
Example:
..code-block:: python
bpy.context.object["MyOwnProperty"] = 42
if "SomeProp" in bpy.context.object:
print("Property found")
# Use the get function like a python dictionary
# which can have a fallback value.
value = bpy.data.scenes["Scene"].get("test_prop", "fallback value")
# dictionaries can be assigned as long as they only use basic types.
While it's useful to be able to access data directly by name or as a list, it's more common to operate on the user's selection. The context is always available from '''bpy.context''' and can be used to get the active object, scene, tool settings along with many other attributes.
Common-use cases:
>>> bpy.context.object
>>> bpy.context.selected_objects
>>> bpy.context.visible_bones
Note that the context is read-only. These values cannot be modified directly, though they may be changed by running API functions or by using the data API.
So ``bpy.context.object = obj`` will raise an error.
But ``bpy.context.scene.objects.active = obj`` will work as expected.
The context attributes change depending on where they are accessed. The 3D view has different context members than the console, so take care when accessing context attributes that the user state is known.
Operators are tools generally accessed by the user from buttons, menu items or key shortcuts. From the user perspective they are a tool but Python can run these with its own settings through the :mod:`bpy.ops` module.
Examples:
>>> bpy.ops.mesh.flip_normals()
{'FINISHED'}
>>> bpy.ops.mesh.hide(unselected=False)
{'FINISHED'}
>>> bpy.ops.object.scale_apply()
{'FINISHED'}
..note::
The menu item: Help -> Operator Cheat Sheet" gives a list of all operators and their default values in Python syntax, along with the generated docs. This is a good way to get an overview of all blender's operators.
Many operators have a "poll" function which may check that the mouse is a valid area or that the object is in the correct mode (Edit Mode, Weight Paint etc). When an operator's poll function fails within python, an exception is raised.
For example, calling bpy.ops.view3d.render_border() from the console raises the following error:
..code-block:: python
RuntimeError: Operator bpy.ops.view3d.render_border.poll() failed, context is incorrect
In this case the context must be the 3d view with an active camera.
To avoid using try/except clauses wherever operators are called you can call the operators own .poll() function to check if it can run in the current context.
Used for vectors, quaternion, eulers, matrix and color types, accessible from :mod:`mathutils`
Some attributes such as :class:`bpy.types.Object.location`, :class:`bpy.types.PoseBone.rotation_euler` and :class:`bpy.types.Scene.cursor_location` can be accessed as special math types which can be used together and manipulated in various useful ways.
The first is through key properties directly, which is similar to inserting a keyframe from the button as a user. You can also manually create the curves and keyframe data, then set the path to the property. Here are examples of both methods.
Both examples insert a keyframe on the active object's Z axis.