Blender Python: Script Set-up

<<< Return to the Blender Python Notebook

Summary

Creating a script and running it is very easy. This page will show you the basic workflow along with some tips for getting into the API within Blender.

Import Libraries

Importing the Blender Python API is the first step for any Blender script… you can import other libraries as needed in the standard way.

import bpy #Imports the Blender Python API
import mathutils #Imports Blender vector math utilities
import math #Imports the standard Python math library

Printing to the Blender Console

The print command will print results to the Blender Console. You can access the console through the Window menu or by calling the console through Python.

#Set up some variables... standard Python rules apply...
a = 'hello'
b = ' world!'
 
#Print the addition to the system console
print (a+b)
 
#open the system console
bpy.ops.wm.console_toggle()
BlenderConsole.JPG

Exploring the API

Blender offers two ways of exploring the API: The Python Console, and the Info viewport. Unfortunately, Blender does not have code completion built into the code editor… but one can dream!

Cube Example

Blender's 'Info' view port shows you all recent Blender activity as executable Python commands. This is very handy for prototyping a process using modeling methods and then assembling them into a script.

This is what the Info window returns after placing some objects in the scene…

BlenderInfo.JPG

The selected text from above can be copied and pasted into the Text Editor. We can delete any unneeded options from the command. This script will create a single mesh cube in the scene.

import bpy #Imports the Blender Python API
import mathutils #Imports Blender vector math utilities
import math #Imports the standard Python math library
 
# Create a mesh cube in the scene
bpy.ops.mesh.primitive_cube_add(location=(0.936607, -0.484878, 1.66298))

We can swap out the location values with some variables to give us some better control over the location…

x = 5
y = 5
z = 0
 
# Create a mesh cube in the scene
bpy.ops.mesh.primitive_cube_add(location=(x, y, z))
BlenderInfo-Cube.JPG

…or we can put the command in a For Loop to create a row of cubes…

for i in range (0, 5):
 
    x = i*3
    y = 0
    z = 0
 
    # Create a mesh cube in the scene
    bpy.ops.mesh.primitive_cube_add(location=(x, y, z))
BlenderInfo-Cube-Row.JPG

… or a nested For Loop for a grid of cubes!

for i in range (0, 10):
    for j in range (0, 10):
 
        x = i*3
        y = j*3
        z = 0
 
        # Create a mesh cube in the scene
        bpy.ops.mesh.primitive_cube_add(location=(x, y, z))
BlenderInfo-Cube-Grid.JPG

Don't get too carried away with bpy.ops.mesh.primitive_monkey_add()

BlenderMonkeyGrid.JPG
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License