0

I have two versions of python 2.7 (32 and 64 bit) installed in windows machine. I need to embed one 32 bit python into c++ program. I have created PYTHONPATH environment variable with value C:\ProgramData\Anaconda2\Lib and appended C:\ProgramData\Anaconda2 into PATH. So this example works

int main()
{
      Py_Initialize();
      PyRun_SimpleString("from time import time,ctime\n"
                         "print 'Today is',ctime(time())\n");
      Py_Finalize();
      return 0;
}

Now I need to be able to change between python version inside c++. So modifications of env variables should canceled and they should be specified inside c++.

First I removed PYTHONPATH, program gives the error:

ImportError: No module named site

setting python home solves the problem:

char python_home[] = "C:\\ProgramData\\Anaconda2";
Py_SetPythonHome(python_home);

Second I removed C:\ProgramData\Anaconda2 from PATH and have specified program name

char program_name[] = "C:\\ProgramData\\Anaconda2\\python";
Py_SetProgramName(program_name);

program terminates with

exited with code -1073741515

By commenting lines I have found that problem caused by

Py_SetProgramName(program_name);

Final version looks like this

int main()
{
    char program_name[] = "C:\\ProgramData\\Anaconda2\\python";
    Py_SetProgramName(program_name);
//    char python_home[] = "C:\\ProgramData\\Anaconda2";
//    Py_SetPythonHome(python_home);
//    Py_Initialize();
//    PyRun_SimpleString("from time import time,ctime\n"
//                       "print 'Today is',ctime(time())\n");
//    Py_Finalize();
    return 0;
}
LNK
  • 171
  • 2
  • 14
  • Shouldn't you call setProgramName in between initialize and finalize? – Aconcagua Apr 03 '18 at 16:12
  • 2
    Any of the functions that you're calling are from *python27.dll* which is **loaded at program startup**. So changing variables will not get you where you want. Also your program can only load the *Python* dll that has **the same architecture** (*x86* or *x64*). Maybe https://stackoverflow.com/questions/39539089/what-files-are-required-for-py-initialize-to-run could offer more details. – CristiFati Apr 03 '18 at 16:17
  • @jdehesa: [\[Python2\]: void Py_SetProgramName(char *name)](https://docs.python.org/2/c-api/init.html#c.Py_SetProgramName) – CristiFati Apr 03 '18 at 16:20
  • @jdehesa there are no Py_SetPath method in python 2.7 – LNK Apr 03 '18 at 17:36

0 Answers0