From f173e55c6207c7cb95907c01a22184f011f91907 Mon Sep 17 00:00:00 2001 From: Tom Birch Date: Fri, 24 Jan 2025 08:44:22 +1100 Subject: [PATCH] fix: set PYTHONNOUSERSITE Set PYTHONNOUSERSITE to prevent adding user directories outside bazel. I found a py_test run with `bazel test` was importing modules from ~/.local/lib/python3.10/site-packages/ which allowed it to run successfully on my machine but fail on other hosts. Before: USER_SITE directory in sys.path when running python code via `bazel run` or `bazel test` After: sys.path only contains paths relative to the `bazel-out` directory --- python/private/python_bootstrap_template.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/python/private/python_bootstrap_template.txt b/python/private/python_bootstrap_template.txt index e3b39e30cd..404236d212 100644 --- a/python/private/python_bootstrap_template.txt +++ b/python/private/python_bootstrap_template.txt @@ -528,6 +528,10 @@ def Main(): # See: https://docs.python.org/3.11/using/cmdline.html#envvar-PYTHONSAFEPATH new_env['PYTHONSAFEPATH'] = '1' + # Set the PYTHONNOUSERSITE environment variable to prevent Python from adding + # directories uknown to bazel to sys.path. This is important for reproducibility. + new_env['PYTHONNOUSERSITE'] = '1' + main_filename = os.path.join(module_space, main_rel_path) main_filename = GetWindowsPathWithUNCPrefix(main_filename) assert os.path.exists(main_filename), \