Search code examples
c++python-3.xtensorflowembedding

How to fix "ImportError: No module named 'tensorflow'" when embedding python in C++


My question is about embedding python in C++. I want to embed a python module which imports tensorflow, and numpy. I was able to embed a python code which doesn't import tensorflow or numpy successfully. Also, there is no problem with using tensorflow in my python. My setup is OS: Linux Ubuntu 16.04 Python version: 3.5

I tested various cases using PyRun_SimpleString(). I tried 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();

but it gave an error as

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)

Here are my main.cpp and CMakeLists.txt files:

main.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})

build the code using command:

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

Execute using command:

./Demo

When the program is executed following error prompts:

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

Instead of "import tensorflow", if I used "import os"/"import time" the "Hello TF!!!" is the result.

How can I resolve this error? Is there any missing thing in the CMakeList.txt?


Solution

  • Again I installed Tensorflow according to the steps given in https://www.tensorflow.org/install/pip and executed the above code in the created virtual environment. Then, the issue was resolved.