Scripting Basics#

It is finally time to put your Python skill to good use, but before you start coding, take some time to make preparations will make your life much easier.

Scripting Workspace#

Blender has pre-configured a Scripting workspace, switch to it and you will find some new areas along with old familiar faces.

../../_images/script_wp.png

The Python Console area provides an interactive Python console with a history of your activities in the form of Python commands.

../../_images/py_console.png

The Text Editor area is where you can write your code in Blender, it has syntax highlight and some other basic tools.

Tip

No auto-completion at the time of writing (version 3.6.0).

../../_images/text_editor.png

The Outliner area is not new, but this time the Display Mode is set to Blender file, which lists all the data (including unused) currently in the file.

../../_images/outliner_bfile.png

Turn on Python Tooltips#

In Edit > Preferences > Interface > Display, tick Developer Extras and Python Tooltips. The tooltips give you the Python equivalent of the UI element, and you can copy it by Right Mouse Click the element and choose Copy Python Command/Copy Full Data Path.

../../_images/py_tooltip.png

First Script#

To make a new script, Left Mouse Click New on the header of the Text Editor. When writing Blender Python scripts, you always need to start with

Tip

You can also add the two convenience variables and convenience imports in the console to make things more consistant.

from mathutils import *
from amth import *
C = bpy.context
D = bpy.data
import bpy

and The bpy here is Blender in the form of a Python module. Now, let’s find out how to add a cube using Python. Add one in the 3D viewport using the Add menu, and you will find this new entry in the history below the Python console.

../../_images/add_cube.png

Running this function in the console confirms that it does add a cube to the scene, and you can find out more about it in its documentation.

Tip

The Python Console area does have auto-completion, press Tab to use it.

../../_images/console_cube.png

With this knowledge, we can write the following script to add cubes on the \(y = z^2\) curve.

import bpy

for i in range(10):
    bpy.ops.mesh.primitive_cube_add(size = 2, location = (0.0, i*i, i))

Left Mouse Click the on the header to run the script.

../../_images/first_cubes.gif

Using bpy module in Python#

Tip

A script that works in Blender GUI may not work in command line.

If you want to render the scene on a remote machine, you can do it through the command line interface. Blender can be installed as a Python module, download the latest version from the website. Make sure you have a compatible version of Python (it is not always the latest version), then unzip and use pip install to install the module. Alternatively, you can build it from the source.