0

When I tried to call a python file using Tensorflow library in C++ environment, I got a problem like this. I have no idea how to solve it.

This is my C++ code.

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


int main(int argc, wchar_t** argv)
{
    const char* picpath ="/home/senius/Pictures/zys.jpg";
    Py_Initialize();
    //PySys_SetArgv(argc, argv);
    //PyRun_SimpleString("import sys\nprint sys.argv");
    if ( !Py_IsInitialized() ) {
        return -1;
    }
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('/home/senius/Python/Ctensor/')");
    PyObject* pMod = NULL;
    PyObject* pFunc = NULL;
    PyObject* pParm = NULL;
    PyObject* pRetVal = NULL;
    int iRetVal = -999;
    const char* modulName="classify";    //这个是被调用的py文件模块名字
    pMod = PyImport_ImportModule(modulName);
    if(!pMod)
    {
        std::cout<<"Import module failed!";
        PyErr_Print();
        return -1;
    }
    const char* funcName="evaluate";  //这是此py文件模块中被调用的函数名字
    pFunc = PyObject_GetAttrString(pMod, funcName);
    if(!pFunc)
    {
        std::cout<<"Import function failed!";
        return -2;
    }
   pParm = PyTuple_New(1);
   PyTuple_SetItem(pParm, 0, Py_BuildValue("s",picpath));//传入的参数,是图片的路径
   pRetVal = PyEval_CallObject(pFunc, pParm);//这里开始执行py脚本
   PyArg_Parse(pRetVal, "i", &iRetVal);//py脚本返回值给iRetVal
   //PyErr_Print();
   std::cout<<iRetVal;
   return iRetVal;
}

This is my python code.

from PIL import Image
import numpy as np
import sys
import tensorflow as tf

def evaluate(pic):
    if not hasattr(sys, 'argv'):
        sys.argv  =  ['']
    image = Image.open(pic)
    image = image.resize([256, 256])
    image_array = np.array(image)
    max_index = np.argmax([1, 2, 32])
    return max_index

Once I import Tensorflow in python code, there will be a error. If I don't import Tensorflow, error disappears.

Error information is as followed.

Import module failed!Traceback (most recent call last):
File "/home/senius/Python/Ctensor/classify.py", line 4, in <module>
  import tensorflow as tf
File "/home/senius/anaconda3/lib/python3.6/site-    packages/tensorflow/__init__.py", line 24, in <module>
  from tensorflow.python import *
File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 63, in <module>
  from tensorflow.python.framework.framework_lib import *
File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/framework_lib.py", line 76, in <module>
  from tensorflow.python.framework.ops import Graph
File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 37, in <module>
  from tensorflow.python.eager import context
File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/python/eager/context.py", line 28, in <module>
  from tensorflow.python.platform import app
File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/python/platform/app.py", line 23, in <module>
  from tensorflow.python.platform import flags
File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/python/platform/flags.py", line 26, in <module>
  _global_parser = _argparse.ArgumentParser()
File "/home/senius/anaconda3/lib/python3.6/argparse.py", line 1622, in __init__
prog = _os.path.basename(_sys.argv[0])
AttributeError: module 'sys' has no attribute 'argv'
  • 2
    http://idownvotedbecau.se/imageofanexception - or at least I assume it's an exception ... my proxy doesn't allow me to view the image. – UKMonkey Jan 04 '18 at 14:16
  • Some information is as followed. Import module failed!Traceback (most recent call last): File "/home/senius/Python/Ctensor/classify.py", line 4, in import tensorflow as tf File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/__init__.py", line 24, in from tensorflow.python import * File "/home/senius/anaconda3/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 63, in ......AttributeError: module 'sys' has no attribute 'argv' @UKMonkey – Zhao Yongsen Jan 04 '18 at 14:27
  • I suppose you aren't deleting the `argv` member form `sys` somewhere in the code. What happens if you run the script directly from *Python*?, then what happens if you execute `import tensorflow` directly in your *Python* console? Check [\[SO\]: Calling Python function with parametrs from C++ project (Visual Studio)](https://stackoverflow.com/questions/47942845/calling-python-function-with-parametrs-from-c-project-visual-studio) for more *C*/*Python* embedding (that's on *Win*). Do you by any chance have a *sys.py* file in your folder? – CristiFati Jan 04 '18 at 15:02

1 Answers1

0

You import the tensorflow module - and during that import it attempts to use sys.argv (as you can see from your stack trade) and then sometime later in some function, you have

if not hasattr(sys, 'argv'): 
    sys.argv  =  ['']`

which is the workaround to this error - but it can never be called because the import failed.

The fix is to move this to before you import the tensorflow module

UKMonkey
  • 6,941
  • 3
  • 21
  • 30