1

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.

2
  • There is no PyRun_FromString function in the Python-C-API. Do you mean PyRun_SimpleString? Why can't you use it? It is one possible way to execute Python in C. Commented Sep 14, 2015 at 9:00
  • ah yes indeed, i correct it. The problem with PyRun_SimpleString is that it seems to not take variables as arguments... Commented Sep 14, 2015 at 9:09

2 Answers 2

2

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.
Sign up to request clarification or add additional context in comments.

1 Comment

thanks i was able to do what i wanted using your answer
1

Take a look at Weave, it allows you to include C code directly in Python code.

1 Comment

thank you, but i want to do the opposite : calling python within C ^^

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.