gpt4 book ai didi

c++ - 在 C++ 中嵌入 python 时如何修复 "ImportError: No module named ' tensorflow'"

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:20 24 4
gpt4 key购买 nike

我的问题是关于在 C++ 中嵌入 python。我想嵌入一个导入 tensorflow 和 numpy 的 python 模块。我能够嵌入一个不能成功导入 tensorflow 或 numpy 的 python 代码。另外,在我的python中使用tensorflow也没有问题。我的设置是操作系统:Linux Ubuntu 16.04Python版本:3.5

我使用 PyRun_SimpleString() 测试了各种情况。我试过 Importing tensorflow when embedding python in c++ returns null

Py_Initialize();
PySys_SetArgv(argc, (wchar_t**)argv);
PyRun_SimpleString("import os \n"
"print('Hello TF!!!')");)
Py_Finalize();

但是报错了

Fatal Python error: no mem for sys.argv
ValueError: character U+65442f2e is not in range [U+0000; U+10ffff]

Current thread 0x00007f5a69506740 (most recent call first):
Aborted (core dumped)

这是我的 main.cpp 和 CMakeLists.txt 文件:

ma​​in.cpp:

#include "Python.h"
#include <iostream>

using namespace std;

int main(int argc, char *argv[]) {

Py_Initialize();
PyRun_SimpleString("import tensorflow \n"
"print('Hello TF!!!')");
Py_Finalize();
return 0;
}

CMakeLists.txt

cmake_minimum_required(VERSION 3.13)
project(Demo)

set(CMAKE_CXX_STANDARD 14)
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/usr/include/python3.5 -I/usr/include/x86_64-linux-gnu/python3.5 -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes")

add_executable(Demo main.cpp)

set(PYTHON_EXECUTABLE "/usr/bin/python3.5")
set(PYTHON_INCLUDE_DIR "/usr/include/python3.5m")
set(PYTHON_LIBRARIES "/usr/lib/x86_64-linux-gnu/libpython3.5m.so")

include_directories(${PYTHON_INCLUDE_DIRS})
include_directories(${PYTHON_DIRECTORIES})
target_link_libraries(Demo ${PYTHON_LIBRARIES})

使用命令构建代码:

cmake --build . --target Demo -- -j 2

使用命令执行:

./Demo

程序执行时出现以下错误提示:

Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named 'tensorflow'

如果我使用“import os”/“import time”而不是“import tensorflow”,那么“Hello TF!!!”是结果。

我该如何解决这个错误? CMakeList.txt 中是否缺少任何内容?

最佳答案

我再次按照 https://www.tensorflow.org/install/pip 中给出的步骤安装了 Tensorflow并在创建的虚拟环境中执行上述代码。然后,问题就解决了。

关于c++ - 在 C++ 中嵌入 python 时如何修复 "ImportError: No module named ' tensorflow'",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55439016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com