1# SPDX-License-Identifier: Apache-2.0
2
3include_guard(GLOBAL)
4
5# On Windows, instruct Python to output UTF-8 even when not
6# interacting with a terminal. This is required since Python scripts
7# are invoked by CMake code and, on Windows, standard I/O encoding defaults
8# to the current code page if not connected to a terminal, which is often
9# not what we want.
10if (WIN32)
11  set(ENV{PYTHONIOENCODING} "utf-8")
12endif()
13
14set(PYTHON_MINIMUM_REQUIRED 3.8)
15
16find_package(Deprecated COMPONENTS PYTHON_PREFER)
17
18if(NOT DEFINED Python3_EXECUTABLE AND DEFINED WEST_PYTHON)
19  set(Python3_EXECUTABLE "${WEST_PYTHON}")
20endif()
21
22if(NOT Python3_EXECUTABLE)
23  # We are using foreach here, instead of
24  # find_program(PYTHON_EXECUTABLE_SYSTEM_DEFAULT "python" "python3")
25  # cause just using find_program directly could result in a python2.7 as python,
26  # and not finding a valid python3.
27  foreach(candidate "python" "python3")
28    find_program(Python3_EXECUTABLE ${candidate} PATHS ENV VIRTUAL_ENV NO_CMAKE_PATH)
29    if(Python3_EXECUTABLE)
30        execute_process (COMMAND "${Python3_EXECUTABLE}" -c
31                                 "import sys; sys.stdout.write('.'.join([str(x) for x in sys.version_info[:2]]))"
32                         RESULT_VARIABLE result
33                         OUTPUT_VARIABLE version
34                         OUTPUT_STRIP_TRAILING_WHITESPACE)
35
36       if(version VERSION_LESS PYTHON_MINIMUM_REQUIRED)
37         set(Python3_EXECUTABLE "Python3_EXECUTABLE-NOTFOUND" CACHE INTERNAL "Path to a program")
38       endif()
39    endif()
40  endforeach()
41endif()
42
43find_package(Python3 ${PYTHON_MINIMUM_REQUIRED} REQUIRED)
44
45# Zephyr internally used Python variable.
46set(PYTHON_EXECUTABLE ${Python3_EXECUTABLE})
47