Equivalent Python API Code

Michael P. Reilly arcege at shore.net
Sat Dec 4 13:45:51 EST 1999


winkjj at my-deja.com wrote:
: Could someone show me how to implement the following Python code using
: the C API?

:>>> mystr = '[100,200,300]'
:>>> mylist = eval(mystr)
:>>> mylist
: [100, 200, 300]

: Basically, I want to take a char* that holds the value of mystr, and
: eval it, obtaining a PyObject* to a list.

: Generically, I want to be able to eval any char* that represents some
: code, and obtain a PyObject* to the real object...

: I've tried using PyRun_String with the start token set to
: Py_eval_input, but this doesn't work correctly.

It is not in the API documentation.  You need to review the source
code, but you want to compile the string and evaluate that result.
Here is some example code.

#include <stdio.h>
#include <Python.h>
#include <compile.h>

int main(ac, av)
  int ac;
  char *av[];
  { char *stmt1 = "mystr = '[100,200,300]'",
         *stmt2 = "eval(mystr)";
    PyObject *globals, *co, *result, *PyEval_EvalCode();

    Py_Initialize();
    globals = PyDict_New();

    /* compile a statement */
    PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
    if ((co = Py_CompileString(stmt1, "<stdin>", Py_file_input)) == NULL) {
      PyErr_Print();
      exit(1);
    }

    /* evaluate the compiled code */
    result = PyEval_EvalCode((PyCodeObject *)co, globals, NULL);
    Py_DECREF(co);
    if (result == NULL) {
      PyErr_Print();
      exit(1);
    }

    /* print the result */
    PyObject_Print(result, stdout, Py_PRINT_RAW);
    fprintf(stdout, "\n");
    Py_DECREF(result);

    /* compile an expression */
    if ((co = Py_CompileString(stmt2, "<stdin>", Py_eval_input)) == NULL) {
      PyErr_Print();
      exit(1);
    }
    result = PyEval_EvalCode((PyCodeObject *)co, globals, NULL);
    Py_DECREF(co);
    if (result == NULL) {
      PyErr_Print();
      exit(1);
    }

    /* print the result */
    PyObject_Print(result, stdout, Py_PRINT_RAW);
    fprintf(stdout, "\n");
    Py_DECREF(result);

    Py_DECREF(globals);
    Py_Finalize();
    exit(0);
  }

This should give you some direction on using compiled statements in C.

  -Arcege





More information about the Python-list mailing list