Skip to main content
GameDev.net gamedev.net
🔒 Locked

Weird environmental variable error

Started by Genjix Jun 4, 2006 at 3:18 AM 0 replies 400+ views
Original Post
Genjix
Genjix
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);
#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;
}

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()
{
  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.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.