Original Post
Hi, Not sure if this is to due with python or my use of environmental variables, but I am trying to write some code so I can call python files like RunPythonFile(path, file); This crashes with Segmentation fault, but if I move the environment variable code before the Py_Initialize() call, it works fine.
#include <iostream>
#include <Python.h>
int main()
{
Py_Initialize();
//-----------------
char* env = getenv ("PYTHONPATH");
if (!env)
return -1;
putenv ("PYTHONPATH=/home/genjix/tmp/py/");
PyObject *module = PyImport_ImportModule ("amir");
PyObject *foo = PyObject_GetAttrString (module, "foo");
PyObject *arg1 = PyInt_FromLong(3), *arg2 = PyInt_FromLong(8);
PyObject *args = PyTuple_New(2);
PyTuple_SetItem(args, 0, arg1);
PyTuple_SetItem(args, 1, arg2);
PyObject *ret = PyEval_CallObject(foo, args);
int result = PyInt_AsLong(ret);
std::cout << result << "!\n";
putenv (env);
//-----------------
Py_Finalize();
return 0;
}
#include <iostream>
#include <Python.h>
int main()
{
char* env = getenv ("PYTHONPATH");
if (!env)
return -1;
putenv ("PYTHONPATH=/home/genjix/tmp/py/");
Py_Initialize();
//-----------------
PyObject *module = PyImport_ImportModule ("amir");
PyObject *foo = PyObject_GetAttrString (module, "foo");
PyObject *arg1 = PyInt_FromLong(3), *arg2 = PyInt_FromLong(8);
PyObject *args = PyTuple_New(2);
PyTuple_SetItem(args, 0, arg1);
PyTuple_SetItem(args, 1, arg2);
PyObject *ret = PyEval_CallObject(foo, args);
int result = PyInt_AsLong(ret);
std::cout << result << "!\n";
putenv (env);
//-----------------
Py_Finalize();
return 0;
}
$ ./pycall
24!
$
Can someone explain why this is happening? Thanks.