bazel_namespace_package_hack.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. # Copyright 2019 The gRPC Authors
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import os
  15. import site
  16. import sys
  17. _GRPC_BAZEL_RUNTIME_ENV = "GRPC_BAZEL_RUNTIME"
  18. # TODO(https://github.com/bazelbuild/bazel/issues/6844) Bazel failed to
  19. # interpret namespace packages correctly. This monkey patch will force the
  20. # Python process to parse the .pth file in the sys.path to resolve namespace
  21. # package in the right place.
  22. # Analysis in depth: https://github.com/bazelbuild/rules_python/issues/55
  23. def sys_path_to_site_dir_hack():
  24. """Add valid sys.path item to site directory to parse the .pth files."""
  25. # Only run within our Bazel environment
  26. if not os.environ.get(_GRPC_BAZEL_RUNTIME_ENV):
  27. return
  28. items = []
  29. for item in sys.path:
  30. if os.path.exists(item):
  31. # The only difference between sys.path and site-directory is
  32. # whether the .pth file will be parsed or not. A site-directory
  33. # will always exist in sys.path, but not another way around.
  34. items.append(item)
  35. for item in items:
  36. site.addsitedir(item)