Embedding python question: PyRun_String only returns None not what I calculate

G. David Kuhlman dkuhlman at netcom.com
Tue Apr 6 20:09:24 EDT 1999


This is not the most convenient solution to your problem, but may
be useful in your case.

When you embed Python in an application, the application often
exposes functions that are callable from Python scripts.  You could
provide a function named setReturnValue(value), which when called,
passed a Python object (the value).  The script calls this
function, and then, when it exits, the embedding application (the
caller of PyRun_String or PyRun_SimpleString) uses the Python value
saved by this function.

My application needs to do something similar.  It needs to be able
to evaluate scripts, passing in one or more values and to "catch" a
value returned by the script.  Effectively, we want scripts to be
functions.  If you find a smoother way to do this than what I
described above, please let me know.

  - Dave

Barry Scott <barry at scottbb.demon.co.uk> wrote:
> What I want to do is call python to run python code and return the results
> to
> my app. But I cannot find anyway to do this.

> It would seem that I should be using PyRun_String to run a piece of python
> and return a result object to me. But I can only get a return value of None.
> NULL is returned if the code does not run.

> How do I get python to return 2 to me when I ask it what 1+1 is?

> Below is a fragment of code that I'm using to investigate PyRun_String.

>         BArry

> //
>  // Test getting an object back from a command
>  //
>  char *command = "1+1";

>  PyObject *m = PyImport_AddModule("__main__");
>  if (m == NULL)
>           return EXIT_FAILURE;

>  PyObject *d = PyModule_GetDict(m);
>  PyObject *v = PyRun_String(command, Py_file_input, d, d);
>  if (v == NULL)
>        {
>        PyErr_Print();
>        return EXIT_FAILURE;
>        }

>  PyObject *result = PyObject_Str( v );

>  char *string = PyString_AsString( result );
>  printf("Python returned: %s", string );

>  Py_DECREF(result);
>  Py_DECREF(v);






More information about the Python-list mailing list