Module 22 · Lesson 44 of 64

Buildroot external trees and Python packages

Extend Buildroot with a board configuration and a Python package, then generate the configuration and build the image from a Python wrapper.

  • Beginner to advanced
  • 11 min read
  • 60 min lab
What you will need

Ubuntu 24.04 in WSL2 or a VM, a Buildroot checkout with its host prerequisites installed, Python 3, and GNU Make. A Raspberry Pi 4 is optional for boot verification.

Your place in the module
By the end you can 4 objectives
  • Register a BR2_EXTERNAL tree and explain how Buildroot discovers its configuration and recipes.
  • Write a setuptools-based python-package recipe and enable it in a defconfig.
  • Generate and apply a defconfig from a Python wrapper with an out-of-tree build directory.
  • Choose the correct build hook for root filesystem changes and final image assembly.
Video coming soonBuildroot external trees and Python packages
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Build systems and subprocess wrappers
  • BitBake schedules Yocto recipe tasks, while Buildroot uses GNU Make and Kconfig to build a configured system.
  • Python adds value when builds need consistent inputs, per-run logs or integration with a larger workflow.
  • The child process return code determines build success, while diagnostic lines help locate failures.
01

Register a Buildroot external tree

3 min read

In the previous lesson you drove builds from Python with subprocess. This lesson extends Buildroot with an external tree, defconfigs and post-image scripts, and packages Python code the Buildroot way.

Buildroot already ships configs/raspberrypi4_64_defconfig for a 64-bit Raspberry Pi 4 build. The steps below were run for real against a Buildroot checkout at version 2026.11-rc3 (the development tree at the time of this review) in a Ubuntu 24.04 container: the external tree, the named defconfig, the Python wrapper's configuration step and a build of the package target all worked as written. Suppose your image also needs a Python diagnostic program maintained in your project. Use that board configuration as the starting point and keep your additions in a separate repository. The Buildroot checkout supplies the board baseline and package infrastructure. Your repository records what the product adds, so you can review those changes and apply them again when you update the checkout.

A must contain at least three files at its root, according to the Buildroot manual. In external.desc, set a name that can appear in a Make variable:

text
name: EMBEDDEX
desc: Embeddex Raspberry Pi 4 example

Buildroot uses that name to expose the tree's location as BR2_EXTERNAL_EMBEDDEX_PATH. The root Config.in loads this lesson's package configuration:

text
source "$BR2_EXTERNAL_EMBEDDEX_PATH/package/python-board-health/Config.in"

The root external.mk loads the corresponding recipe:

makefile
include $(BR2_EXTERNAL_EMBEDDEX_PATH)/package/python-board-health/python-board-health.mk

The two includes are independent. The Kconfig source statement loads a fragment that declares a symbol and its dependencies. The Make include loads the version, source location and build rules for the package. When a package is missing from menuconfig, check the Kconfig include and the symbol's dependencies. When the symbol is enabled but the build cannot find the package target, check the Make include and the recipe name.

What Buildroot loads from the external treeExternal treeexternal.descNames the treeConfig.inLoads Kconfig fragmentsexternal.mkIncludes Make recipesconfigs/Named board defconfigspackage/Package symbols and recipessrc/Local Python sourceExternal treeexternal.descNames the treeConfig.inLoads Kconfig fragmentsexternal.mkIncludes Make recipesconfigs/Named board defconfigspackage/Package symbols and recipessrc/Local Python source
The external tree registers its Kconfig entries and Make recipes and supplies named defconfigs.

Buildroot discovers named defconfigs in the external tree's configs/ directory. Copy the checkout's configs/raspberrypi4_64_defconfig to configs/embeddex_pi4_defconfig in the external tree. Make paths in the examples absolute. Here BUILDROOT and EXTERNAL point to the two source directories, and OUT points to a dedicated output directory:

bash
make -C "$BUILDROOT" O="$OUT" BR2_EXTERNAL="$EXTERNAL" embeddex_pi4_defconfig
make -C "$BUILDROOT" O="$OUT" BR2_EXTERNAL="$EXTERNAL" menuconfig

The first command loads the named defconfig and produces the active .config in OUT; in the test run that file contained BR2_EXTERNAL_NAMES="EMBEDDEX" and BR2_EXTERNAL_EMBEDDEX_PATH set to the tree's path. The manual also notes that Buildroot remembers the BR2_EXTERNAL value in a hidden .br2-external.mk file in the output directory, so later make calls in the same output directory need not repeat it. The second lets you inspect or edit that configuration. A is suitable for version control. To capture menu changes, use savedefconfig with BR2_DEFCONFIG="$EXTERNAL/configs/embeddex_pi4_defconfig" to specify the destination. Review the resulting diff. A minimal defconfig depends on the defaults of the checkout that reads it, so record which Buildroot revision goes with it.

The board defconfig carries settings for the architecture, kernel, firmware and image generation. Preserve those settings when adding an application. Give each board or build profile its own output directory. If you remove a package from an existing configuration, a subsequent build can leave files from the previous installation in the target directory. Use a fresh output directory when you need to verify what a reduced configuration actually ships.

02

Package the Python program

4 min read

generic-package provides the common package stages, including fetching, extracting, patching, building and installing. With that infrastructure, you supply package-specific commands where needed, such as <PKG>_BUILD_CMDS or <PKG>_INSTALL_TARGET_CMDS. python-package, implemented in Buildroot's package/pkg-python.mk, supplies build and installation behavior for supported Python packaging backends. The recipe declares the setup type. Setuptools is the choice for this example. The list of accepted values depends on the Buildroot release. In the 2026.11-rc3 checkout, package/pkg-python.mk accepts setuptools, setuptools-rust, pep517, flit, hatch, poetry and maturin (plus flit-bootstrap for host packages) and stops with an error for anything else, so the old distutils type is not available there. Older tutorials that use distutils need to be converted, and you should check pkg-python.mk in the checkout you pinned before choosing a type.

Create package/python-board-health/Config.in in the external tree:

text
config BR2_PACKAGE_PYTHON_BOARD_HEALTH
    bool "python-board-health"
    depends on BR2_PACKAGE_PYTHON3
    help
      Install a small Python program that reports the running kernel release.

The dependency makes the package selectable when target Python 3 is enabled. Selecting Python on your Ubuntu host has no effect on this symbol. Add BR2_PACKAGE_PYTHON3=y and BR2_PACKAGE_PYTHON_BOARD_HEALTH=y to enable both in the board defconfig. On another board, inspect the resolved .config before building. Kconfig may leave a requested option disabled if the board's toolchain cannot satisfy its dependencies.

Create package/python-board-health/python-board-health.mk:

makefile
PYTHON_BOARD_HEALTH_VERSION = 0.1.0
PYTHON_BOARD_HEALTH_SITE = $(BR2_EXTERNAL_EMBEDDEX_PATH)/src/board-health
PYTHON_BOARD_HEALTH_SITE_METHOD = local
PYTHON_BOARD_HEALTH_SETUP_TYPE = setuptools
PYTHON_BOARD_HEALTH_LICENSE = MIT
PYTHON_BOARD_HEALTH_LICENSE_FILES = LICENSE

$(eval $(python-package))

The recipe prefix comes from the Buildroot package name, python-board-health. The source directory contains setup.py, board_health.py and the LICENSE file for the example project. Include the MIT license text with the appropriate copyright notice so the declaration and the source agree. The license variable describes the source, and the license-files variable tells Buildroot which file to collect for legal information.

python
# src/board-health/setup.py
from setuptools import setup

setup(
    name="board-health",
    version="0.1.0",
    py_modules=["board_health"],
    entry_points={"console_scripts": ["board-health=board_health:main"]},
)
python
# src/board-health/board_health.py
import os


def main():
    print(os.uname().release)

The setuptools entry point makes the installed command board-health call main(). In the test build (make python-board-health, with the Python 3 interpreter the board configuration then builds, version 3.14), the log showed the package being synced from the local source directory, configured, built and installed to the target, and the target tree then contained usr/bin/board-health (a small script that imports board_health and calls main()) and usr/lib/python3.14/site-packages/board_health.py. Buildroot prepares the Python build dependencies for the host and installs the result for the target. This distinction matters even more when a Python package contains a C extension. That extension must match the target architecture and Python environment. Installing a package into an Ubuntu virtual environment tests that host installation, while the Buildroot recipe controls what goes into the device image.

How a selected Python package reaches the filesystemEnabletargetPythonEnableapplicationLoad PythonrecipeSetuptoolssetup typeBuild onhostInstall fortargetModule andconsolecommandEnabletargetPythonEnableapplicationLoad PythonrecipeSetuptoolssetup typeBuild onhostInstall fortargetModule andconsolecommand
Kconfig enables the recipe, and the Python package infrastructure installs the module and command for the target.

For a package published on PyPI, Buildroot provides utils/scanpypi. The tool is spelled scanpypi, with pypi at the end, and it needs Python's setuptools on the host. For a br2-external tree the Buildroot manual shows the -o flag, which writes the generated package directories somewhere other than package/. A real run of python3 utils/scanpypi pyserial -o gen created python-pyserial/python-pyserial.mk, python-pyserial.hash and Config.in in that directory, and ended with a reminder to update the DEVELOPERS file and package/Config.in. The generated .mk file set PYTHON_PYSERIAL_VERSION = 3.5, PYTHON_PYSERIAL_SETUP_TYPE = setuptools and PYTHON_PYSERIAL_LICENSE_FILES = LICENSE.txt, but it set the license to the placeholder FIXME: please specify the exact BSD version. The manual warns that the license is only guessed and that dependencies on Python core modules cannot be guessed, so always review the output. Inspect the results, then register the package's Config.in and .mk in your external tree's root Config.in and external.mk, as you did for python-board-health.

Compare the generated version, source URL, hashes and license information with the upstream release. Check the build backend and distinguish build dependencies from modules imported at runtime. For example, if your application imports requests, the image needs the Buildroot package that supplies that import. A setuptools dependency declaration alone does not enable a target package in Kconfig. Review the generated Kconfig dependencies and the recipe's Make dependencies for the role each dependency plays. For the local board-health example, the standard library provides everything the program imports, so a hand-written recipe is sufficient.

03

Generate the configuration and build the image

4 min read

Use Python to produce a defconfig when an explicit build choice determines which settings to apply. This wrapper uses the external tree's named defconfig as its baseline and owns two symbols. The --with-health profile enables Python and the diagnostic command. The default profile leaves those two settings to the board's Kconfig defaults and any other selected packages. Keep the baseline launchable on its own, and keep generated configuration files in the build output.

Save build_image.py at the root of the external tree. Run it with a Buildroot checkout path and an output directory. The wrapper uses a subdirectory for each profile so a build without the diagnostic command does not reuse the target filesystem from a build that installed it.

python
import argparse
from pathlib import Path
import subprocess

parser = argparse.ArgumentParser()
parser.add_argument("buildroot", type=Path)
parser.add_argument("output", type=Path)
parser.add_argument("--with-health", action="store_true")
args = parser.parse_args()

external = Path(__file__).resolve().parent
baseline = external / "configs" / "embeddex_pi4_defconfig"
profile = "health" if args.with_health else "base"
output = args.output.resolve() / profile
output.mkdir(parents=True, exist_ok=True)
generated = output / "generated_defconfig"

symbols = ("BR2_PACKAGE_PYTHON3", "BR2_PACKAGE_PYTHON_BOARD_HEALTH")
prefixes = tuple(f"{symbol}=" for symbol in symbols)
unset_lines = {f"# {symbol} is not set" for symbol in symbols}
lines = [
    line for line in baseline.read_text(encoding="utf-8").splitlines()
    if not line.startswith(prefixes) and line not in unset_lines
]
if args.with_health:
    lines.extend(f"{symbol}=y" for symbol in symbols)
generated.write_text("\n".join(lines) + "\n", encoding="utf-8")

make = [
    "make", "-C", str(args.buildroot.resolve()),
    f"O={output}", f"BR2_EXTERNAL={external}",
]
subprocess.run([*make, f"BR2_DEFCONFIG={generated}", "defconfig"], check=True)

if args.with_health:
    resolved = set((output / ".config").read_text(encoding="utf-8").splitlines())
    for symbol in symbols:
        if f"{symbol}=y" not in resolved:
            raise SystemExit(f"Kconfig did not enable {symbol}")

subprocess.run(make, check=True)

BR2_DEFCONFIG tells the defconfig target which input file to read. Removing both the assignment and unset forms keeps the generated input from expressing conflicting choices. The .config check tests the resolved result before the expensive build. Run python3 build_image.py "$BUILDROOT" "$OUT" --with-health, then look for health/target/usr/bin/board-health and health/images/sdcard.img under OUT. The first verifies installation into the filesystem tree and the second verifies that the board's image workflow produced its disk image. The review run checked only the first: it built the package target, not the whole image, because a full Raspberry Pi 4 image also builds a kernel and firmware and takes much longer. The sdcard.img name comes from the board's own genimage template (image sdcard.img in board/raspberrypi4-64/genimage.cfg.in), but it was not produced here. On a booted Pi 4, compare board-health with uname -r. Both report the release of the running kernel. Running the command on Ubuntu would measure the host kernel.

From generated defconfig to disk imageGeneratedefconfigResolve.configPopulatetarget treeRunpost-buildhookGeneratefilesystemimagesRunpost-imagehookAssembledisk imagewithgenimageGeneratedefconfigResolve.configPopulatetarget treeRunpost-buildhookGeneratefilesystemimagesRunpost-imagehookAssembledisk imagewithgenimage
Buildroot resolves the generated configuration, populates the target filesystem and produces the board image.
Going deeperExplore the mechanism

Use BR2_ROOTFS_POST_BUILD_SCRIPT for changes to the populated target filesystem before Buildroot generates filesystem images. Examples include installing a board marker under /etc or adjusting a generated configuration file. According to the Buildroot manual, a relative script path is relative to the Buildroot tree, scripts run with that tree as the current directory, and the target directory is passed as the first argument; the manual lists BR2_CONFIG, CONFIG_DIR, HOST_DIR, STAGING_DIR, TARGET_DIR, BUILD_DIR, BINARIES_DIR and BASE_DIR as available environment variables. In the 2026.11-rc3 checkout the Raspberry Pi 4 baseline already sets BR2_ROOTFS_POST_BUILD_SCRIPT="board/raspberrypi4-64/post-build.sh" (it adds a getty on tty1) and a matching post-image script, so add your own script to that list instead of replacing it. Use BR2_ROOTFS_POST_IMAGE_SCRIPT for work on completed image artifacts. A post-image script receives the images directory as its first argument. Give your script a shebang and executable permissions so it can run under its intended interpreter. The Linux execution interface defines how the interpreter and process environment are passed to such scripts.

Buildroot also provides TARGET_DIR, BUILD_DIR and BINARIES_DIR to these scripts. TARGET_DIR names the target filesystem tree. BUILD_DIR contains package build directories and can hold build-time scratch files. BINARIES_DIR contains artifacts such as filesystem images and kernel binaries. Quote paths in shell scripts, use the supplied directories, and assign scratch files a dedicated location. Scripts run on the build host. Editing TARGET_DIR in a post-image hook is too late for that edit to appear in filesystem images already generated.

genimage assembles artifacts according to a layout configuration that describes the disk image, its partitions and their inputs. Buildroot can build it as the host tool host-genimage. In a Raspberry Pi SD-card workflow, a genimage configuration can place a boot filesystem and a root filesystem into a single flashable image. Inspect the hooks and genimage configuration named by the board baseline before adding your own. Preserve the existing post-image hook when the baseline uses it to produce sdcard.img. A post-build change reaches that image through the regenerated root filesystem. A change to the disk layout belongs in the genimage configuration used during post-image processing.

Keep the checked-in defconfig, generated defconfig and resolved .config distinct when reviewing a build. The first records the board baseline, the second records the wrapper's requested choices, and the third shows what Buildroot will use. The next lesson, Yocto recipes and kas, takes up the same questions of package selection and repeatable configuration in a Yocto project.

Key takeaways

  • An external tree registers Kconfig symbols, Make recipes and named defconfigs alongside the Buildroot checkout.
  • The Kconfig entry makes a package selectable, and the Make recipe implements its build and installation.
  • A defconfig records selected settings, and Buildroot resolves them into the active .config.
  • A post-build script can change the target filesystem before packaging, and a post-image script can assemble the resulting artifacts into a disk image.
Reflect
  1. Explain to a colleague, in two sentences: register a BR2_EXTERNAL tree and explain how Buildroot discovers its configuration and recipes.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Find your next step

↑ ↓ to move · Enter to open · Esc to close