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

**URL:** <https://discourse.cmake.org/t/possible-to-create-a-python-virtual-env-from-cmake-and-then-find-it-with-findpython3/1132>\
**Category:** Code\
**Created:** [May 1, 2020, 6:38am UTC](https://discourse.cmake.org/t/possible-to-create-a-python-virtual-env-from-cmake-and-then-find-it-with-findpython3/1132 "2020-05-01T06:38:53Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![alex](https://discourse.cmake.org/user_avatar/discourse.cmake.org/alex/32/125_2.png) [@alex](https://discourse.cmake.org/u/alex)\
**Post date:** [May 1, 2020, 6:38am UTC](https://discourse.cmake.org/t/possible-to-create-a-python-virtual-env-from-cmake-and-then-find-it-with-findpython3/1132/1 "2020-05-01T06:38:53Z")

</div>

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?

---

<div class="post-metadata">

**Author:** ![marc.chevrier](https://discourse.cmake.org/letter_avatar_proxy/v4/letter/m/ecb155/32.png) [@marc.chevrier](https://discourse.cmake.org/u/marc.chevrier)\
**Post date:** [May 1, 2020, 9:00am UTC](https://discourse.cmake.org/t/possible-to-create-a-python-virtual-env-from-cmake-and-then-find-it-with-findpython3/1132/2 "2020-05-01T09:00:21Z")

</div>

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

```cmake
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)

```
