• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
15import os
16import site
17import sys
18
19_GRPC_BAZEL_RUNTIME_ENV = "GRPC_BAZEL_RUNTIME"
20
21
22# TODO(https://github.com/bazelbuild/bazel/issues/6844) Bazel failed to
23# interpret namespace packages correctly. This monkey patch will force the
24# Python process to parse the .pth file in the sys.path to resolve namespace
25# package in the right place.
26# Analysis in depth: https://github.com/bazelbuild/rules_python/issues/55
27def sys_path_to_site_dir_hack():
28    """Add valid sys.path item to site directory to parse the .pth files."""
29    # Only run within our Bazel environment
30    if not os.environ.get(_GRPC_BAZEL_RUNTIME_ENV):
31        return
32    items = []
33    for item in sys.path:
34        if os.path.exists(item):
35            # The only difference between sys.path and site-directory is
36            # whether the .pth file will be parsed or not. A site-directory
37            # will always exist in sys.path, but not another way around.
38            items.append(item)
39    for item in items:
40        site.addsitedir(item)
41