Need help with PyRun_String

Michael P. Reilly arcege at shore.net
Sat Jan 8 12:58:37 EST 2000


Arinte <jamarijr at hotmail.com> wrote:
: How do you uses
: PyObject* PyRun_String (char *str, int start, PyObject *globals,
: PyObject *locals);

: I don't know what to put in for the params (except str).

The start value should be one of "Py_single_input", "Py_file_input"
or "Py_eval_input".  Use "Py_file_input" if you mean to use the "exec"
command (or execfile() function) and use "Py_eval_input" for eval()
operations.  The "Py_single_input" value works like interactive mode.

The globals and locals arguments are to be PyDictObject objects or
NULL to use the results of globals() and locals().

Often it is easier to just use PyRun_SimpleString().

: Also, I need tips on handling errors, like how can I get the trace
: string thingie.

Unfortunately, you cannot trap these values using PyRun_String;
traceback output will be sent to stderr.  It is probably desirable to
replace the sys.stderr binding with a cStringIO object.

  { PyObject *mod, *klass, *obj;

    mod = PyImport_ImportModule("cStringIO");
    klass = PyObject_GetAttrString(mod, "StringIO");
    obj = PyObject_CallFunction(klass, NULL);
    Py_DECREF(klass);

    /* redirect sys.stderr to a cStringIO instance */
    PySys_SetObject("stderr", obj);
  }

But you can also get access to the exception data using the normal
C/API functions:

  PyRun_String(...);
  if (PyErr_Occurred())
    { PyObject *exc_type, *exc_value, *exc_tb;
      PyErr_Fetch(&exc_type, &exc_value, &exc_tb);
      ...
    }

I hope this helps.
  -Arcege




More information about the Python-list mailing list