0

I have written a simple program in Visual Studio C++ using PyRun_SimpleString, where I am importing the library sympy. The following is the code I have written in C++.

#include "Python.h"
#include<iostream>
#include<Windows.h>
#include<stdlib.h>
using namespace std;
int main()
{

    Py_Initialize();
    PySys_SetPath(L"C:/Users/acer/source/repos/merger/merger");
    PyRun_SimpleString("import sys\n"
                       "sys.path.insert(0, 'C:/Users/acer/source/repos/merger/merger/site-packages')\n"
                       "import sympy\n"
                       "print('Hello World')");
    Py_Finalize();
    return 0;
}

I used sys.path.insert() to tell the program the location of the library sympy. But when the program runs init in sumpy, it shows error as it cannot find the module future, which is imported in the first line of init. The following is the error being shown -

Traceback (most recent call last):
  File "<string>", line 3, in <module>
  File "C:/Users/acer/source/repos/merger/merger/site-packages\sympy\__init__.py", line 15, in <module>
    from __future__ import absolute_import, print_function
ModuleNotFoundError: No module named '__future__'

What is the reason for this error? I have already copied the libraries into my project folder. I don't know how to get rid of this problem. Any help would be greatly appreciated.

Pratham Yadav
  • 69
  • 1
  • 8
  • 1
    See [here](https://stackoverflow.com/questions/7624529/python-c-api-doesnt-load-module). You are overriding the module search path where it would normally find `__future__` (and everything else) – ChrisD Apr 28 '20 at 09:11
  • Thanks! That helped me a lot and now the program is running. But let's say that I want to run a Python module by using PyImport_ImportModule in the C++ Program, and not use the PyRun_SimpleString. I have the program already created in Python and the program imports sympy. Would I have to do the same thing in that case too? – Pratham Yadav Apr 28 '20 at 09:23
  • 1
    If the module is in the current working directory it should be able to find it it (I am not sure that you need to append `"."` to `sys.path` as in the link.) And importing a module executes every statement in it. But you might also want to look at `PyRun_File`. – ChrisD Apr 28 '20 at 10:11

1 Answers1

1

When you call PySys_SetPath you should concatenate the directory you want to add to the existing path.

Here you are setting only this directory in the Path.

No surprise than that the basic python module are not found.

sandwood
  • 2,038
  • 20
  • 38
  • Honestly, I just learned this yesterday. So I'm super new to this. Can you please explain which directory I should concatenate to the existing path? Thankyou. – Pratham Yadav Apr 28 '20 at 09:10