Search code examples
pythoncembedding

python embedding in C : define the python script as a C string?


I would like to invoke the following python script in C :

#!/usr/bin/python2.7

import parser

def evaluate(text):
   code = parser.expr(text).compile()
   return eval(code)

as explained in the following page https://docs.python.org/2/extending/embedding.html, i can call this script from C using the pwd(path) of the file.

However, i would like to know if it's possible to not load the script by calling python on a C string directly, defining the script.

For example, i would like to let's say i put :

#define PYTHON_SCRIPT ((char*)(\      
  import parser\  
  \                    
  def evaluate(text):\   
    code = parser.expr(text).compile()\  
    return eval(code)\ 
  ))

is it possible to call the python interpreter directly on that string?

Indeed, knowing that i need to pass text as a variable, i can't use this Pyrun_SimpleString function, and i was not able to find something to answer this question.


Solution

  • As mentioned in the comment there is no Pyrun_SimpleString. How to execute Python functions from C is covered here. One way to do it:

    1. Compile your script using Py_CompileString
    2. Create a dictionary for globals/locals.
    3. Extract the function from your globals dict by using PyDict_GetItemString(name)
    4. Build your arguments tuple with PyArg_ParseTuple
    5. Execute your function object by using PyObject_CallFunction.