2

I tried to use the Python C api to call a function from python in C++, the test was successful.

But if I intend to import a module already importing other module, the Pymodule_findmodule will return Null even though it's there and created a compiled file. Here is my code

Py_Initialize();
PySys_SetPath("C:/Users/Mik/Documents/GitHub/youtube-dl");      
PyObject * pythonFile = PyImport_ImportModule("test2");

Here is the python filed named test2.py at that directory with a file named test_dl.py and a class called TESTDL inside it

from test_dl import TESTDL 
def someFunction(someInput):
    return 12345

As soon as I added the import line my program doesnot recognize it as module anymore

Edit: turns out the test_dl has the first line as:

 from __future__ import unicode_literals

That's the reason I got this ImportError: No module named future

Thanks!

Hongjun Han
  • 55
  • 2
  • 6
  • 1
    Sounds like you might have gotten an exception when trying to import `test_dl` or retrieve the `TESTDL` object from it. – user2357112 Feb 01 '16 at 18:00
  • What does `PyErr_Print()` print after your call to `PyImport_ImportModule("test2")`? – tynn Feb 01 '16 at 18:22

1 Answers1

7

A function call to PySys_SetPath() completely overwrites the Python module path. The result is that your Python script test_dl cannot find Python system modules (in this case __future__) and throws an exception.

What you need to do is to append the directory of your module to the system path instead. To do that, first query the existing value of the system path, and then add your path to it:

PyObject *sys_path = PySys_GetObject("path");
PyList_Append(sys_path, PyString_FromString("C:/Users/Mik/Documents/GitHub/youtube-dl"));
kfx
  • 8,136
  • 3
  • 28
  • 52
  • Thanks so much :) Didn't realize I need the python lib as well – Hongjun Han Feb 01 '16 at 19:24
  • That only works with Python >=2.7. Here a more compatible version: append_path = PYTHON_PATH ":."; //append_path = '"'PYTHON_PATH:."; setenv("PYTHONPATH", append_path, 1); //Set PYTHONPATH TO working directory – Joniale Jun 26 '18 at 09:01
  • 4
    PyString_FromString is not compliant with python >3.5, use PyUnicode_FromString instead – Julien Aug 24 '20 at 21:09