如何使用pybind11从virtualenv运行python解释器?

时间:2018-09-24 11:51:45

标签: python c++ pip pybind11

我正在尝试使用 pybind11 库从称为 env_tensorflow 的python环境中执行python解释器。

尽管如此,即使我将cpp文件包含并链接到该环境( env_tensorflow )中包含的pybind11库中,解释器也会将其二进制路径打印为:

  

/ usr / bin / python3

但是,我希望输出为:

  

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

我在做什么错?如何在特定环境中运行python解释器?

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)

1 个答案:

答案 0 :(得分:1)

您需要激活Conda环境:

source activate env_tensorflow

完成此操作后,您应该能够使用正确的Python解释器运行cmake,make和您的应用程序。您可能不需要CMake中的IMPORTED目标,只要在构建过程中环境处于活动状态,就可以照常链接到python3.6m