Skip to content

Commit 7a32d0a

Browse files
authored
[build] ensure Python to be found in vcpkg (#24713)
### Description <!-- Describe your changes. --> Sometimes Python cannot be found by CMake when using vcpkg. This is because vcpkg does not inherit environment `PATH` from the parent process when launching CMake (which is intentionally done by vcpkg), and in this case, a non-standard Python installation (eg. virtual env or conda) may fail the `find_package(Python3 REQUIRED)`. This PR write the env variable `Python3_ROOT_DIR` and adds it to `VCPKG_KEEP_ENV_VARS` to ensure CMake launched by vcpkg to be able to always find Python that runs `build.py`. This change should not break the existing behavior unless there are scenarios that intentionally uses different python for running build.py and vcpkg build.
1 parent c76991c commit 7a32d0a

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

tools/ci_build/build.py

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1228,9 +1228,28 @@ def generate_build_tree(
12281228
]
12291229
env = {}
12301230
if args.use_vcpkg:
1231-
env["VCPKG_KEEP_ENV_VARS"] = "TRT_UPLOAD_AUTH_TOKEN;EMSDK;EMSDK_NODE;EMSDK_PYTHON"
1231+
vcpkg_keep_env_vars = ["TRT_UPLOAD_AUTH_TOKEN"]
1232+
12321233
if args.build_wasm:
12331234
env["EMSDK"] = emsdk_dir
1235+
vcpkg_keep_env_vars += ["EMSDK", "EMSDK_NODE", "EMSDK_PYTHON"]
1236+
1237+
#
1238+
# Workaround for vcpkg failed to find the correct path of Python
1239+
#
1240+
# Since vcpkg does not inherit the environment variables `PATH` from the parent process, CMake will fail to
1241+
# find the Python executable if the Python executable is not in the default location. This usually happens
1242+
# to the Python installed by Anaconda.
1243+
#
1244+
# To minimize the impact of this problem, we set the `Python3_ROOT_DIR` environment variable to the
1245+
# directory of current Python executable.
1246+
#
1247+
# see https://cmake.org/cmake/help/latest/module/FindPython3.html
1248+
#
1249+
env["Python3_ROOT_DIR"] = str(Path(os.path.dirname(sys.executable)).resolve())
1250+
vcpkg_keep_env_vars += ["Python3_ROOT_DIR"]
1251+
1252+
env["VCPKG_KEEP_ENV_VARS"] = ";".join(vcpkg_keep_env_vars)
12341253

12351254
run_subprocess(
12361255
[*temp_cmake_args, f"-DCMAKE_BUILD_TYPE={config}"],

0 commit comments

Comments
 (0)