1

I want to call a python scipt sayhello.py which located at D:/semantic_segmentation/scripts in my c++ program, here is my c++ code:

Py_Initialize();
PyRun_SimpleString("import sys");
PyRun_SimpleString("sys.path.append('D:/semantic_segmentation/scripts')");
PyObject* pModule = PyImport_ImportModule("sayhello");

the code of sayhello.py is:

import sys
sys.path.append("..")
import a

def _sayhello(x):
    print('hello')
    return x

_sayhello(1)

When I run my C++ program the function PyImport_ImportModule returns NULL, but when I run sayhello.py with python -m sayhello.py directly it works fine. How can i fix this?

edit: I found the problem is in the following code:

sys.path.append("..")
import a

the c++ program doesn't work when i import other script in sayhello.py. But when i move a.py to the same path with sayhello.py, and import a.py only with import a, my c++ program works. So my question is, how can i make my c++ program calling python script work, when the called script calls another script which located in other path?

xiaojifeng
  • 45
  • 3
  • what is `import a`? – Mansoor Jul 28 '20 at 09:14
  • it is another script a.py, which is located at *D:/semantic_segmentation*. If i remove ```import a```, i can run my c++ praogram successfully. It turns out that when i import other scripts in *sayhello.py*, my c++ program doesn't work. – xiaojifeng Jul 28 '20 at 09:22

1 Answers1

0

It looks like your python code assumes the current working directory of the process is the D:/semantic_segmentation/scripts directory, which is not necessarily the case.

Here are two solutions:

  • change the working directory of your c++ program with chdir or the windows equivalent, or
  • change the python code to compute an absolute path starting from the script file instead of the current working directory. See this answer.
Botje
  • 26,269
  • 3
  • 31
  • 41