简体   繁体   中英

How to run the python interpreter from a virtualenv using pybind11?

I am trying to execute a python interpreter from a python environment, called env_tensorflow , using pybind11 library.

Even though, I include and link the cpp file to the pybind11 library which is included from that environment ( env_tensorflow ), the interpreter prints its binary path as:

/usr/bin/python3

However, I expect the output to be:

/home/user/miniconda3/envs/env_tensorflow/bin/python3

What am I doing wrong? How can I run the python interpreter from a specific environment?

main.cpp

#include "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/Python.h"
#include "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/pybind11/pybind11.h"
#include "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/pybind11/embed.h"

namespace py = pybind11;
int main() {
    py::scoped_interpreter guard{};
    py::module sys = py::module::import("sys");
    py::print(sys.attr("executable"));
    //prints: /usr/bin/python3
    //expected print: /home/user/miniconda3/envs/env_tensorflow/bin/python3
    return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.12)
project(my_proj)
set(CMAKE_CXX_STANDARD 11)

add_library(my_python3.6m SHARED IMPORTED)
set_target_properties(my_python3.6m PROPERTIES
        IMPORTED_LOCATION "/home/user/miniconda3/envs/env_tensorflow/lib/libpython3.6m.so"
        INTERFACE_INCLUDE_DIRECTORIES "/home/user/miniconda3/envs/env_tensorflow/include/python3.6m/"
        )

add_executable(my_proj main.cpp)
target_link_libraries(my_proj my_python3.6m)

You need to activate the Conda environment:

source activate env_tensorflow

Once you've done that, you should be able to run cmake, make, and your application with the correct Python interpreter. You probably don't need the IMPORTED target in CMake, you can just link against python3.6m as normal, so long as the environment is active during the build process.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM