# \[PATCH v2 2/2\] perf tools: Put Python bytecode in output directory

- From: Ian Rogers \<irogers@google.com\>
- Date: 2026-09-21 17:57:39 
- List: linux-trace-kernel
- Page: https://ratatoskr.run/linux-trace-kernel/2026/09/17616987
- Thread: https://ratatoskr.run/linux-perf-users/2026/05/17015404/t.md

```text
From: Ben Hutchings <redacted>

The PMU events are processed into C sources by Python scripts, which
normally results in writing bytecode for each module into the source
tree.  This prevents a fully out-of-tree build.

To fix this, set $PYTHONPYCACHEPREFIX to relocate the bytecode cache
directory in an out-of-tree build. Note, this environment variable is
only supported by python 3.8+, but the file Documentation/Changes
states the minimum supported python for builds is 3.9.x. In an in-tree
build in tools/perf setting the variable causes a single __pycache__
directory in the source tree.

Expand python-clean to also clean the __pycache__ and perf.pyi.

Signed-off-by: Ben Hutchings <redacted>
Signed-off-by: Ian Rogers <irogers@google.com>
---
v2: Rebase. Add clean step and commit message comment wrt older python
    versions (Sashiko). Make setting the environment variable true for
    in-tree builds, that simplifies the clean.
---
 tools/perf/Makefile.perf | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)

diff --git a/tools/perf/Makefile.perf b/tools/perf/Makefile.perf
index 438102bcae6c..715642630067 100644
--- a/tools/perf/Makefile.perf
+++ b/tools/perf/Makefile.perf
@@ -397,7 +397,8 @@ PYTHON_EXTBUILD_LIB := $(PYTHON_EXTBUILD)lib/
 PYTHON_EXTBUILD_TMP := $(PYTHON_EXTBUILD)tmp/
 export PYTHON_EXTBUILD_LIB PYTHON_EXTBUILD_TMP
 
-python-clean := $(call QUIET_CLEAN, python) $(RM) -r $(PYTHON_EXTBUILD) $(OUTPUT)python/perf*.so
+# Put Python bytecode in output directory
+export PYTHONPYCACHEPREFIX := $(OUTPUT)/__pycache__
 
 ifneq ($(quiet),)
 python_setup_quiet=--quiet
@@ -919,7 +920,12 @@ $(INSTALL_DOC_TARGETS):
 ### Cleaning rules
 
 python-clean:
-	$(python-clean)
+	$(call QUIET_CLEAN, python) $(RM) -r $(PYTHON_EXTBUILD) $(OUTPUT)__pycache__ \
+		$(OUTPUT)python/perf*.so
+	@if [ "$(abspath python/perf.pyi)" != "$(abspath $(OUTPUT)python/perf.pyi)" ]; \
+	then \
+		$(RM) $(OUTPUT)python/perf.pyi; \
+	fi
 
 $(LIBAPI_OUTPUT) $(LIBBPF_OUTPUT) $(LIBPERF_OUTPUT) $(LIBSUBCMD_OUTPUT) $(LIBSYMBOL_OUTPUT):
 	$(Q)$(MKDIR) -p $@
-- 
2.55.0.1082.g2b9226bbc0-goog

```
