【问题标题】:Embedding python witn pybind11 using virtualenv使用 virtualenv 嵌入 python 和 pybind11
【发布时间】:2021-09-18 23:32:28
【问题描述】:

我想在 pybind11 中使用 python 虚拟环境。我的系统默认使用python2。我有一个使用 python3 的虚拟环境(使用 virtualenvwrapper 创建)。我应该如何修改 CMake 以使用虚拟环境? virutalenv 站点包的路径是

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

我试过了

但这对我不起作用。我正在使用 ubuntu。

这就是我所拥有的。

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"));

    }

输出

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

非常感谢您的帮助

【问题讨论】:

    标签: python c++ cmake virtualenv pybind11


    【解决方案1】:

    最初的问题是默认情况下 CMake FindPython 脚本更喜欢系统 Python 而不是虚拟环境。您可以通过设置 the Python_VIRTUALENV to FIRST 来调整它(从 CMake 3.15 开始)。

    set(Python_VIRTUALENV FIRST)
    

    要记住的另一点是find_package 调用将select the newest version of Python unless you specify an EXACT version

    【讨论】:

      猜你喜欢
      • 2018-05-25
      • 1970-01-01
      • 2019-02-27
      • 2019-11-16
      • 1970-01-01
      • 2019-04-28
      • 1970-01-01
      • 1970-01-01
      • 2020-04-22
      相关资源
      最近更新 更多