sys.path[0] breaks out of runfile tree. #382
Comments
Thanks for the report. This same problem is currently documented here bazelbuild/bazel#7091 but I cannot find a counterpart already in this project. The Python stub template has an example of a 'hack' to fix the problem https://github.com/bazelbuild/bazel/blob/master/src/main/java/com/google/devtools/build/lib/bazel/rules/python/python_stub_template.txt#L19. But that only fixes the problem in that python process, and the stub template starts the user's process and the problem is reintroduced like you observe. |
It seems like the stub template could use the https://docs.python.org/3/using/cmdline.html#cmdoption-s when it is building the command to execute: |
@person142, neither The problem will still exist because There are some potential solutions noted in the bazel issue:
I am unsure which would be the most appropriate in this case. I think 1 might not be trivial because IIUC the runfiles behaviour is part of core Bazel and not rules_python specific. |
Affected Rule
py_binary
,py_test
.Is this a regression?
No
Description
When Python initializes it adds the directory of the script to the
sys.path
:This would imply that a
py
target such as{REPO_DIR}/bazel-bin/{target_path}/{target}.runfiles/{script_path}/{python_script}.py
would cause{REPO_DIR}/bazel-bin/{target_path}/{target}.runfiles/{script_path}/
to be inserted assys.path[0]
.However, because the script is a symlink to the real python script in the repository, Python follows the symlink and appends the actual underlying directory to
sys.path[0]
, in this case:{REPO_DIR}/{script_path}/
. This issue was raised in Python's bug tracker and noted as expected behaviour that won't be fixed issue17639.This allows the script to "break out" of the runfiles tree and import code from the same directory which it does not necessarily have access to via
src
ordeps
.This causes issues when creating multiple targets in the same directory which should not automatically depend on each other.
For example, given:
main
can depend onfoo
without the file being explicitly listed in the BUILD file.src/BUILD
src/main.py
src/foo.py
The output of
bazel run //src:main
will be:Which should not be possible where
foo.py
is not an input to//src:main
.Operating System:
Output of
bazel version
:Rules_python version:
Anything else relevant?
The most obvious solution that comes to mind for this would be to copy into the runfile tree rather than symlinking. It seems unlikely this is going to change upstream in Python.
The text was updated successfully, but these errors were encountered: