diff --git a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt index dac21c9a838179..c8ad229c8f04bb 100644 --- a/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt +++ b/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt @@ -8,6 +8,11 @@ import sys import subprocess import zipfile +# Stupid little utility to dedup entries in a list, while preserving order. +def DedupList(lst): + seen = [] + return [x for x in lst if not (x in seen or seen.append(x))] + # Return True if running on Windows def IsWindows(): return os.name == 'nt' @@ -25,7 +30,7 @@ def GetWindowsPathWithUNCPrefix(path): return path # Lets start the unicode fun - unicode_prefix = "\\\\?\\" + unicode_prefix = "\\\\?" if path.startswith(unicode_prefix): return path @@ -147,6 +152,17 @@ def RunfilesEnvvar(module_space): return (None, None) +def BuildUserCustomizeModule(import_paths): + return """\ +# AUTOGENERATED FILE PRODUCED BY PYTHON LAUNCHER STUB SCRIPT. DO NOT EDIT. +import sys + +import_paths = [ +%s +] +sys.path.extend(import_paths) +""" % "\n".join(' "%s",' % path for path in import_paths) + def Main(): args = sys.argv[1:] @@ -162,11 +178,19 @@ def Main(): python_path_entries += GetRepositoriesImports(module_space, %import_all%) python_path_entries = [GetWindowsPathWithUNCPrefix(d) for d in python_path_entries] + python_path_entries = DedupList(python_path_entries) + + # Write `usercustomize.py` file. This will be loaded during startup, and will append package + # directories to `sys.path`. + usercustomize_module = open("%s/usercustomize.py" % module_space, "w") + usercustomize_module.write(BuildUserCustomizeModule(python_path_entries)) + usercustomize_module.close() old_python_path = os.environ.get('PYTHONPATH') - python_path = os.pathsep.join(python_path_entries) if old_python_path: - python_path += os.pathsep + old_python_path + python_path = old_python_path + os.pathsep + module_space + else: + python_path = module_space if IsWindows(): python_path = python_path.replace("/", os.sep) diff --git a/src/test/shell/bazel/bazel_rules_test.sh b/src/test/shell/bazel/bazel_rules_test.sh index bd70148b2cbe7d..f4230c19a3c80e 100755 --- a/src/test/shell/bazel/bazel_rules_test.sh +++ b/src/test/shell/bazel/bazel_rules_test.sh @@ -457,6 +457,9 @@ def Fib(n): EOF cat > module2/bez.py < $TEST_log || fail "bazel run failed" - # Indicates that the local module overrode the system one. - expect_log "I am lib!" + # Presence would indicate that the local module overrode the system one. + expect_not_log "I am lib!" } run_suite "Tests for how the Python rules handle Python 2 vs Python 3"