0

I want to use a python virtual environment with pybind11. My system uses python2 by default. I have a virtual environment (created using virtualenvwrapper) that uses python3. How should I modify the CMake to use the virtual environment? The path of the virutalenv site-packages is

 ~.virtualenvs/name-of-virtual-env/lib/python3.6/site-packages

I tried

but that did not work for me. I am using ubuntu.

This is what I have.

CmakeLists.txt

cmake_minimum_required(VERSION 3.4)
project(example)

add_subdirectory(pybind11)

add_executable(example src/main.cpp)
target_link_libraries(example PRIVATE pybind11::embed)

main.cpp

#include <pybind11/embed.h> // everything needed for embedding
namespace py = pybind11;
using namespace py::literals;


int main() {
    py::scoped_interpreter guard{}; // start the interpreter and keep it alive

    py::module_ sys = py::module_::import("sys");
    py::print(sys.attr("path"));
    py::print("python version: ", sys.attr("version_info"));

    }

output

python version:  sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)

Your help is very much appreciated

1 Answer 1

1

The initial problem is that the CMake FindPython script prefers the system Python over a virtual environment by default. You can adjust this by setting the Python_VIRTUALENV to FIRST (starting with CMake 3.15).

set(Python_VIRTUALENV FIRST)

Another point to keep in mind is that the find_package call will select the newest version of Python unless you specify an EXACT version.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.