Skip to content

Blender API basics

Introduction

Blender embeds a Python interpreter, which is used for multiple tasks. It is a central feature of Blender, as large parts of the user interface are set up and controlled from Python, as well as all add-ons (import/export, tools, etc) are written in Python.

As a user you can run scripts directly on this interpreter and also access Python modules provided by Blender, like bpy and mathutils to access scene elements. The bpy module gives access to Blender's data, functions and classes. In this section we will focus on using the Python API for automation, custom data import and manipulating geometry, but this is not all that is possible with the API, of course. The official API manual states the following things are possible using the Python API:

  • Edit any data the user interface can (Scenes, Meshes, Particles etc.).
  • Modify user preferences, key-maps and themes.
  • Run tools with own settings.
  • Create user interface elements such as menus, headers and panels.
  • Create new tools.
  • Create interactive tools.
  • Create new rendering engines that integrate with Blender.
  • Subscribe to changes to data and it's properties.
  • Define new settings in existing Blender data.
  • Draw in the 3D view using Python.

All in all, the Python API is very powerful.

More detailed Python API reference

In these chapters we provide an introduction to the Python API, using a number of examples. After finishing these chapters you can find a more extensive description of often-used Python API features in the separate API section.

Good to know

Before we continue, we list some bits of information and some tricks that are good to know.

  • Blender uses Python 3.x, specifically 3.11 in Blender 4.1
  • You can access the online API documentation from within Blender with Help > Python API Reference
  • Starting Blender from the console will allow you to see important outputs channels (warnings, exceptions, output of print() statements, etc). See the next section how to do this.
  • The Python Console area in Blender is great for testing Python one-liners. It also has auto-completion so you can inspect the API quickly. Example code shown with >>> lines in our course notes is assumed to be running in the Python Console.

    Python Console versus terminal console

    The Python Console is something different than the console we refer to below. The Python Console is an area within the Blender user interface in which you can enter and execute Python commands:

    While the other type of "console" is a terminal window or DOS box from which you start Blender. This console will then contain any output and exceptions from Python scripts that you run:

    • By enabling the Python Tooltips option in the Preferences under Interface > Display you can hover over almost any button, option, menu, etc and after a second a tool-tip is shown. This tool-tip shows information on how to access this element from the Python API.
    • Right clicking on almost any button, option, menu, etc in Blender gives you the option to 1) directly go to the API documentation with Online Manual or 2) Copy Data Path. Option 2 copies Python API properties related to that element to your clipboard to paste into your script. Note however, that not always the full path is copied, but only the last part.

In the upcoming sections we will first look at how to run Python scripts in Blender. Then we look at how to access Blenders data through scripts and we follow this up with creating geometry, vertex colors and materials in the last section.

Starting Blender from the command line

It is important, when scripting, to start Blender from a command line interface (macOS and Linux). Warnings, messages and print() statements will output into the console. How to start Blender from the command line depends on your operating system.

  • For macOS it would be like this:

    /Applications/Blender.app/Contents/MacOS/Blender
    
  • For Linux it would be something like:

    $ <blender installation directory>/blender
    
  • On Windows you can start Blender normally (i.e. from the Start menu) and then use Window > Toggle System Console to open the console window from within Blender.

More information on where the Blender executable is located on your system and where Blender directories of interest are located see this manual page.

💻 Starting Blender from the console

Exercise:

  1. Find the Blender executable on your machine.
  2. Open Blender through the console.
  3. Delete the cube in the default project of Blender, what output is shown in the console?

Running scripts within the Blender interface

When scripting inside Blender it is convenient to use the Scripting workspace (see the arrow in Fig. 1 below). For running scripts within Blender you have two main options:

  • Using the interactive Python Console (Fig. 1A)
  • Using the built-in Text Editor (Fig. 1B)

The Python Console is very useful for testing lines of Python code, and exploring the API using auto-complete (with TAB) to see what is available. The keyboard shortcuts are a bit different than you might be used to in other text editors. See this section in the Blender manual for an overview of menu options and shortcut keys.

Blender also has its own built-in text editor which you can use (Fig. 1B) to edit Python code and execute it by pressing the button in the top bar, or using Alt-P. Note that you can have multiple different text blocks, each with their own code.

If you want to use your own editor to edit your scripts you can do this by opening the script in both the Blender Text Editor and your own editor. To refresh the Blender Text Editor use Text > Reload or Alt R (or Option R on the Mac). You can also make a script that you open in the Blender Text Editor that executes an external script you edit in your own editor. See for example the script in Fig. 1B.

Figure 1: The Scripting workspace in Blender

Running scripts from the command-line

You can also run Python scripts in Blender directly from the command-line interface. An example of executing a script (-P) without opening the Blender GUI (-b, for background) would be:

blender -b -P script.py

You can combine running a Python script with, say, rendering the first frame (-f 1) from an example test.blend file. The output will go to the directory of the blender file (-o //...) and it will generate a PNG image file (-F PNG):

blender -b test.blend -o //render_ -F PNG -f 1

More information on command line arguments is here in the Blender manual.

Custom script arguments

You might want to pass extra arguments to your script, for example to provide a frame range, or file name, or anything else that makes sense for your script but not Blender. For this, Blender provides the -- marker option. Any arguments passed to Blender that follow -- will not get processed by Blender, but are passed in sys.argv:

# useargs.py
import sys

args = []
idx = sys.argv.index('--')
if idx != -1:
    args = sys.argv[idx+1:]

print(args)
# Do something with values in args
$ blender -b -P useargs.py -- -myopt 1,2,3
Blender 4.1.0 Release Candidate (hash 3641b4b884ab built 2024-03-20 01:31:58)
Read prefs: "/home/melis/.config/blender/4.1/config/userpref.blend"
['-myopt', '1,2,3']

Blender quit

You can then use these arguments in your script, even parse them using a regular option parsing Python module like argparse.

Using modules and external scripts

As we've shown above there's multiple ways to run Python code within Blender, either from a text editor block, the Python Console or from the command-line. Usually, you want to use Python modules or other scripts from the code you're running. Below we describe some common situations and how to handle them.

See this manual page for more tips and tricks related to working with Python scripting in Blender.

NumPy

The official binaries of Blender from blender.org include the numpy Python module, so if you need NumPy then import numpy should work out of the box.

Loading modules in Blender

For modules you want to import you can use the normal Python method of editing sys.path (as needed) and importing the module:

# Example code run from a text block within Blender
import sys

# A path somewhere on your file system
sys.path.append("/some_directory/")

# Or a path relative to the current blender file
blendfile_location = os.path.dirname(bpy.data.filepath)
sys.path.append(blendfile_location)

# Import module
import my_python_module

# Call a function from the module
my_python_module.do_something()

However, suppose you you keep Blender running and edit my_python_module.py to update do_something(). Re-executing the above code will not pick up the changes in the module you're importing. The reason for this is that the Python interpreter doesn't reload a module if it is already loaded. So the import my_python_module has no effect the second time it is called.

To force a module to get reloaded you can use the importlib module:

import my_python_module

# Force reload
import importlib
importlib.reload(my_python_module)

my_python_module.do_something()

Note that this will re-load the module from disk every time you run the above piece of Python code.

Executing external scripts

To execute an arbitrary Python script in an external file you can use the following:

# Execute script_file 
exec(compile(open(script_file).read(), script_file, 'exec'))

You could, for example, put this snippet of code in a Blender text block and execute it every time you need to run it (or even paste it in the Python Console). This is a fairly simple way of executing externally stored Python code, while still being able to edit the external script as needed.

Using an external editor

You might want to use your own favorite editor to write your Python scripts. In Blender you can open an existing file in the editor by clicking on the file icon (1 in the image below). If you then edit this file in your own editor outside of Blender, the editor in Blender will indicate that the file has changed with a red question mark (2). It might take one or two seconds for Blender to notice the file has changed.

Clicking on the question mark gives you three options:

  • Reload from disk - this will overwrite the script in the Text Block with whatever is loaded from file
  • Make text internal (separate copy) - this will ignore the changed file on disk from now, the text in the Text Block will be decoupled from it
  • Ignore - the script in the Text Block will stay unchanged, any future changes in the file on disk will retrigger the question mark

To load the newest version of your file into Blender, you can use Text > Reload (or Alt-R).

Adding startup scripts

You might want to permanently run one or more Python scripts when Blender starts. You can add these scripts in a special configuration directory. The location to place these scripts is system-dependent (see this manual page) for details. In general you want to place the scripts within the "USER" location of the platform you're working on:

  • Windows: %USERPROFILE%\AppData\Roaming\Blender Foundation\Blender\4.1\
  • Linux: $HOME/.config/blender/4.1/
  • macOS: /Users/$USER/Library/Application Support/Blender/4.1/

Inside the above directory create a scripts/startup directory. Any .py files placed there will be automatically executed when Blender starts. See this page for other special directories within the system-specific USER directory.


Last update: 28 August 2024 16:23:33