Skip to content

Commit

Permalink
Get python3-config outside of Matter build env
Browse files Browse the repository at this point in the history
  • Loading branch information
arkq committed Jan 11, 2024
1 parent 5a27f60 commit 1795724
Showing 1 changed file with 61 additions and 5 deletions.
66 changes: 61 additions & 5 deletions build/config/python/python3_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,68 @@
# limitations under the License.

import json
import os
import re
import shutil
import subprocess


def is_subpath(path: str, parent: str):
"""Check if path is a subpath of parent."""
try:
return os.path.commonpath([path, parent]) == parent
except ValueError:
return False


def find_command(command: str, exclude: list[str]):
"""Extended shutil.which() with exclude parameters."""
for path in os.getenv("PATH", os.defpath).split(os.pathsep):
if any(is_subpath(path, x) for x in exclude):
continue
app = shutil.which(command, path=path)
if app is not None:
return app
return None


class Python3Config:

@staticmethod
def _get_config(*args):
return subprocess.check_output(["python3-config", *args], text=True)
# List of python3-config commands to try in order. This is needed because
# not all environments have python3-config symlinked in the PATH.
COMMANDS = [
"python3-config",
"python3.12-config",
"python3.11-config",
"python3.10-config",
"python3.9-config",
]

def __init__(self):

exclude = []

# Exclude directory with python3 installed by CIPD manager in Matter
# build environment. The python3-config provided by CIPD is broken - it
# returns wrong include/link paths and does not provide python shared
# library.
if os.getenv("PW_PYTHON_CIPD_INSTALL_DIR"):
exclude.append(os.getenv("PW_PYTHON_CIPD_INSTALL_DIR"))

for command in self.COMMANDS:
command = find_command(command, exclude=exclude)
if command is not None:
self._python_config_exe = command
break
else:
raise RuntimeError("Could not find python3-config in PATH")

def _get_config(self, *args):
return subprocess.check_output([self._python_config_exe, *args], text=True)

def get_cflags(self):
return [x for x in self._get_config("--cflags").split()
if not x.startswith("-I")]

def get_include_dirs(self):
return [re.sub(r"^-I", "", x)
Expand All @@ -36,16 +89,19 @@ def get_lib_dirs(self):

def get_libs(self):
return [re.sub(r"^-l", "", x)
for x in self._get_config("--libs").split()]
for x in self._get_config("--libs").split()
if x.startswith("-l")]

def get_libs_embed(self):
return [re.sub(r"^-l", "", x)
for x in self._get_config("--libs", "--embed").split()]
for x in self._get_config("--libs", "--embed").split()
if x.startswith("-l")]


if __name__ == '__main__':
config = Python3Config()
print(json.dumps({
'cflags': config.get_cflags(),
'include_dirs': config.get_include_dirs(),
'lib_dirs': config.get_lib_dirs(),
'libs': config.get_libs(),
Expand Down

0 comments on commit 1795724

Please sign in to comment.