Possible to create a Python virtual env from CMake and then find it with FindPython3?

It’s basically all in the title. My project ships with a requirements.txt that lists a set of dependencies that need to be present to test the bindings to the C++ library I’m building.

I would like to be able to perform the following steps:

  1. Find a suitable version of Python3 with the standard FindPython3 module.
  2. Use the discovered Python interpreter to create a virtual environment. (Ideally only if it doesn’t already exist)
  3. Install the requirements.txt into that virtual environment.
  4. Re-run FindPython3 to point the imported targets Python3::Interpreter, Python3::Module, etc. to the virtual environment.

Is this possible? If not, is there something that’s equivalently convenient?

1 Like

It is not a common pattern but you can try the following:

find_package (Python3 COMPONENTS Interpreter)
execute_process (COMMAND "${Python3_EXECUTABLE}" -m venv "/path/to/venv")

# Here is the trick
## update the environment with VIRTUAL_ENV variable (mimic the activate script)
set (ENV{VIRTUAL_ENV} "/path/to/venv")
## change the context of the search
set (Python3_FIND_VIRTUALENV FIRST)
## unset Python3_EXECUTABLE because it is also an input variable (see documentation, Artifacts Specification section)
unset (Python3_EXECUTABLE)
## Launch a new search
find_package (Python3 COMPONENTS Interpreter Development)
1 Like