如何在C++中嵌入python时修复"导入错误:没有名为'tensorflow'的模块"
How to fix "ImportError: No module named 'tensorflow'" when embedding python in C++
我的问题是关于在C++中嵌入python。我想嵌入一个导入 tensorflow 和 numpy 的 python 模块。我能够嵌入一个无法成功导入张量流或numpy的python代码。此外,在我的 python 中使用 tensorflow 没有问题。 我的设置是 操作系统: Linux Ubuntu 16.04 蟒蛇版本:3.5
我使用 PyRun_SimpleString() 测试了各种情况。我尝试在 c++ 中嵌入 python 时导入张量流返回空
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)
以下是我的主要.cpp和CMakeList.txt文件:
主.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;
}
CMakeList.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",结果是"Hello TF!!"。
如何解决此错误?CMakeList.txt中有什么遗漏吗?
我再次按照 https://www.tensorflow.org/install/pip 中给出的步骤安装了 Tensorflow,并在创建的虚拟环境中执行了上述代码。然后,问题解决了。
相关文章:
- 尝试导入pybind-opencv模块时出现libgtk错误
- 当我尝试加载内核模块时,如何修复C++中的这个 malloc() 错误?
- C++20 个模块在 clang (Windows):在最简单的示例中键入信息错误
- 尝试运行 wasm 函数时出现模块未定义错误
- 从 pybind11 构建导入模块时出现"分段错误(核心转储)"
- 处理程序的模块列表中有一个错误的模块"WebSocketModule"
- Qmake 错误:QT: 图表中的未知模块
- QT 数据库模块错误
- .exe应用程序在windows10中创建新模块时抛出错误,但在windows7中工作正常
- 项目错误:QT中的未知模块:Mac上的图表
- 通过 sh 导入模块错误运行.py脚本
- Python 和 C++ (Pybind11):Python 扩展模块导入错误
- 错误 带有模块的一元"*"(具有"int")的类型参数无效
- pybind11:属性错误:尝试从 py 文件运行函数时,模块'XXX'没有属性'YYY'
- 在FreesWitch中使用AWS C SDK加载模块时未定义的符号错误
- 在 Lua 中加载 C++ 模块时'Attempt to index a string value'错误
- 致命错误LNK1112:在 npm 安装期间,模块计算机类型'X86'与目标计算机类型'x64'冲突
- Python 错误:在 SWIG 生成的C++模板化代码模块中没有定义构造函数
- QT模块错误-LNK 1112在qtopengl中
- 另一个子模块错误的 omnet 访问方法 - 调用 'check_and_cast(cModule*&)' 没有匹配函数